diff --git a/.github/workflows/mobile.yml b/.github/workflows/mobile.yml index 0f39b9c1f4a..4eb8ec63f31 100644 --- a/.github/workflows/mobile.yml +++ b/.github/workflows/mobile.yml @@ -27,7 +27,6 @@ on: - 'src/main/runtime/agent-session/agent-session-account-*.ts' - 'src/main/runtime/agent-session/agent-session-acquisition-*.ts' - 'src/main/runtime/agent-session/agent-session-conversation-*.ts' - - 'src/main/runtime/agent-session/agent-session-death-*.ts' - 'src/main/runtime/agent-session/agent-session-launch-*.ts' - 'src/main/runtime/agent-session/agent-session-operation-*.ts' - 'src/main/runtime/agent-session/agent-session-rewind-*.ts' @@ -116,7 +115,6 @@ on: - 'src/main/runtime/agent-session/agent-session-account-*.ts' - 'src/main/runtime/agent-session/agent-session-acquisition-*.ts' - 'src/main/runtime/agent-session/agent-session-conversation-*.ts' - - 'src/main/runtime/agent-session/agent-session-death-*.ts' - 'src/main/runtime/agent-session/agent-session-launch-*.ts' - 'src/main/runtime/agent-session/agent-session-operation-*.ts' - 'src/main/runtime/agent-session/agent-session-rewind-*.ts' diff --git a/.github/workflows/performance-contracts.yml b/.github/workflows/performance-contracts.yml index 2c453310526..461cfb7a12d 100644 --- a/.github/workflows/performance-contracts.yml +++ b/.github/workflows/performance-contracts.yml @@ -21,16 +21,13 @@ on: - 'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts' - 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts' - 'src/shared/agent-launch/permissions/tui-agent-permission-choice.test.ts' - - 'src/main/runtime/rpc/methods/projects/repo.test.ts' - 'src/renderer/src/components/tab-bar/use-new-tab-agent-menu-host-preferences.test.tsx' - 'src/main/sqlite/sync-database.test.ts' - 'src/main/runtime/orchestration/db/row-column-lists.test.ts' - 'src/main/codex-usage/codex-rollout-file-lifetime.test.ts' - 'src/main/codex-usage/scanner-incremental-append.test.ts' - - 'src/main/usage/jsonl-file-reader.test.ts' - - 'src/main/usage/jsonl-file-snapshot.test.ts' + - 'src/main/usage/source-input/jsonl/jsonl-file-reader.test.ts' - 'src/main/claude-usage/scanner-incremental-append.test.ts' - - 'src/main/claude-usage/store-checkpoint-persistence.test.ts' permissions: contents: read diff --git a/cloud/apps/relay-edge/src/host-relay-base.ts b/cloud/apps/relay-edge/src/host-relay-base.ts index d550b6ca840..da0b038d345 100644 --- a/cloud/apps/relay-edge/src/host-relay-base.ts +++ b/cloud/apps/relay-edge/src/host-relay-base.ts @@ -77,6 +77,9 @@ export const NO_DEADLINE = Number.MAX_SAFE_INTEGER // How long a silent keepalive control has to answer the relay ping before it is closed. export const KEEPALIVE_PROBE_MS = 10_000 export const SWEEP_AT_KEY = 'sweepAt' +// Diagnostics only: the host's last control close, read once by the next activation. +export const LAST_CONTROL_CLOSE_KEY = 'lastControlClose' +export type LastControlClose = { goneAt: number; closedAt: number; code: number } // 6 h ± 30 min, as the cells: desktops re-ask the director at least this often. export const LEASE_BASE_MS = 6 * 60 * 60 * 1000 export const LEASE_JITTER_MS = 30 * 60 * 1000 @@ -181,6 +184,7 @@ export abstract class HostRelayBase extends DurableObject { this.attach(ws, null) if (a.k === 'control' && a.phase === 'active') { metric(this.env, 'control_close', 1, String(code), [], '', a.place) } if (a.k === 'control' && a.phase === 'active' && !this.activeControl()) { + await this.ctx.storage.put(LAST_CONTROL_CLOSE_KEY, { goneAt, closedAt: Date.now(), code }) const session = await this.ctx.storage.get('session') if (session && session.generation === a.generation) { const hostReason = relayHostCloseReasonFrom(reason) diff --git a/cloud/apps/relay-edge/src/host-relay-handshake.ts b/cloud/apps/relay-edge/src/host-relay-handshake.ts index 1d9995d44bf..36c7a86a2af 100644 --- a/cloud/apps/relay-edge/src/host-relay-handshake.ts +++ b/cloud/apps/relay-edge/src/host-relay-handshake.ts @@ -7,7 +7,7 @@ import { RELAY_CLOSE_CODE } from '../../../packages/relay-contract/src/close-cod import { metric } from './metrics' import type { EdgeClaims } from './env' import { b64, b64url, fromB64, hmacSha256, sha256B64url, timingSafeEqualStr } from './bytes' -import { HostRelayBase, ASSIGNMENT_CHECK_DEADLINE_MS, NO_DEADLINE, LEASE_BASE_MS, LEASE_JITTER_MS, type ControlAttachment, type Session } from './host-relay-base' +import { HostRelayBase, ASSIGNMENT_CHECK_DEADLINE_MS, NO_DEADLINE, LEASE_BASE_MS, LEASE_JITTER_MS, type ControlAttachment, type Session, LAST_CONTROL_CLOSE_KEY, type LastControlClose } from './host-relay-base' export abstract class HostRelayHandshake extends HostRelayBase { protected async onHostHello(ws: WebSocket, a: ControlAttachment, type: unknown, body: Record): Promise { @@ -193,6 +193,11 @@ export abstract class HostRelayHandshake extends HostRelayBase { // After the ack, which strict shipped parsers must see unchanged; only hosts that asked get it. if (a.clientKeepalive) { this.send(ws, { type: 'keepalive-offer', v: 1, intervalMs: this.config.pingIntervalMs }) } metric(this.env, 'control_active', 1, rebind ? 'rebind' : 'new', [a.openedAt === undefined ? -1 : now - a.openedAt], a.clientKeepalive ? 'keepalive' : 'legacy', a.place) + const last = await this.ctx.storage.get(LAST_CONTROL_CLOSE_KEY) + if (last) { + await this.ctx.storage.delete(LAST_CONTROL_CLOSE_KEY) + metric(this.env, 'reconnect_gap', Math.round((now - last.goneAt) / 1000), String(last.code), [Math.round((last.closedAt - last.goneAt) / 1000)], a.clientKeepalive ? 'keepalive' : 'legacy', a.place) + } await this.reschedule() } } diff --git a/cloud/apps/relay-edge/src/metrics.ts b/cloud/apps/relay-edge/src/metrics.ts index ea76d7f7f2c..c49284a7b06 100644 --- a/cloud/apps/relay-edge/src/metrics.ts +++ b/cloud/apps/relay-edge/src/metrics.ts @@ -33,6 +33,11 @@ export type MetricEvent = | 'auth_expired_close' // Control closed for silence (deadControlMetric, host-relay-control.ts). | 'silence_close' + // A host's control came back after its last control closed: value = seconds from when that + // control was last known alive (silence closes) or closed (others) to this activation; label = + // that close code; double2 = seconds between last-known-alive and the actual close. + // reason 'keepalive' | 'legacy' of the new control. + | 'reconnect_gap' // Pre-auth socket refused by the per-source limiter: label 'phone' | 'data' | 'health'. Unpushed-host phones: 'not_on_edge'. | 'preauth_limited' | 'not_on_edge' diff --git a/cloud/apps/relay/src/assignment/assignment-connection-headroom.test.ts b/cloud/apps/relay/src/assignment/assignment-connection-headroom.test.ts index af1f9924358..b8fce08afc5 100644 --- a/cloud/apps/relay/src/assignment/assignment-connection-headroom.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-connection-headroom.test.ts @@ -46,462 +46,7 @@ async function setup( return { database, store } } -async function setupHeadroomReassignment(): Promise<{ - database: RelayDatabase - store: RelayAssignmentStore - source: RelayCellConfig - target: RelayCellConfig -}> { - const database = await openInMemoryRelayDatabase() - databases.push(database) - const store = new RelayAssignmentStore(database, () => 100, { - requireLiveCells: true, - heartbeatTtlMs: 45_000 - }) - const source = { - ...LIMITED_CELL, - id: 'saturated-source', - url: 'https://saturated-source.example.com' - } - const target = { - ...LIMITED_CELL, - id: 'available-target', - url: 'https://available-target.example.com' - } - await store.reconcileCells([source, target], true) - await store.recordCellHeartbeat({ - cellId: source.id, - cellUrl: source.url, - cellIncarnation: '11111111-1111-4111-8111-111111111111', - startedAt: 50, - ready: true, - observedRequests: 0, - totalConnections: 450, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 450, - connectionHardCap: 600, - connectionUnobservedBound: 50 - }) - await store.recordCellHeartbeat({ - cellId: target.id, - cellUrl: target.url, - cellIncarnation: '22222222-2222-4222-8222-222222222222', - startedAt: 50, - ready: true, - observedRequests: 0, - totalConnections: 0, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 0, - connectionHardCap: 600, - connectionUnobservedBound: 50 - }) - return { database, store, source, target } -} - describe('relay assignment connection headroom', () => { - it('requires exact, internally consistent telemetry from limited cells', async () => { - const database = await openInMemoryRelayDatabase() - databases.push(database) - const store = new RelayAssignmentStore(database, () => 100) - await store.reconcileCells([LIMITED_CELL], true) - const heartbeat = { - cellId: LIMITED_CELL.id, - cellUrl: LIMITED_CELL.url, - cellIncarnation: '11111111-1111-4111-8111-111111111111', - startedAt: 50, - ready: true, - observedRequests: 0 - } - - await expect(store.recordCellHeartbeat(heartbeat)).rejects.toThrow( - 'cell_connection_telemetry_mismatch' - ) - await expect( - store.recordCellHeartbeat({ - ...heartbeat, - totalConnections: 550, - inFlightConnections: 2, - reservedConnectionUnits: 3, - enforcedConnectionUnits: 554, - connectionHardCap: 600, - connectionUnobservedBound: 50 - }) - ).rejects.toThrow('cell_connection_telemetry_mismatch') - await expect( - store.recordCellHeartbeat({ - ...heartbeat, - totalConnections: 601, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 601, - connectionHardCap: 600, - connectionUnobservedBound: 50 - }) - ).resolves.toBeUndefined() - }) - - it('keeps placing against the old cap until the cell reports a raised one', async () => { - const { store } = await setup(449) - const expanded = { - ...LIMITED_CELL, - connectionHardCap: 1_000 as const - } - - await store.reconcileCells([expanded], true) - await expect(store.cellDeploymentStatus(expanded.id)).resolves.toMatchObject({ - connectionCapacity: { hardCap: 1_000, effectiveHardCap: 600, heartbeatFresh: true } - }) - await expect( - store.assign({ userId: 'transition-user', relayHostId: 'host000000000099' }) - ).resolves.toMatchObject({ cellId: expanded.id }) - await expect( - store.assign({ userId: 'transition-user-2', relayHostId: 'host000000000096' }) - ).rejects.toThrow('relay_capacity_exhausted') - - await store.recordCellHeartbeat({ - cellId: expanded.id, - cellUrl: expanded.url, - cellIncarnation: '22222222-2222-4222-8222-222222222222', - startedAt: 200, - ready: true, - observedRequests: 0, - totalConnections: 449, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 449, - connectionHardCap: 1_000, - connectionUnobservedBound: 50 - }) - await expect(store.cellDeploymentStatus(expanded.id)).resolves.toMatchObject({ - connectionCapacity: { - hardCap: 1_000, - ordinaryConnectionLimit: 900, - normalAdmissionPause: 850, - heartbeatFresh: true - } - }) - }) - - it('fails placement closed while the admin path changes the unobserved bound', async () => { - const { store } = await setup(0) - const lowered = { - ...LIMITED_CELL, - connectionUnobservedBound: 49 - } - - await store.configureCell(lowered, 'general') - await expect( - store.assign({ userId: 'admin-transition', relayHostId: 'host000000000098' }) - ).rejects.toThrow('relay_capacity_exhausted') - await expect(store.cellDeploymentStatus(lowered.id)).resolves.toMatchObject({ - connectionCapacity: { hardCap: 600, heartbeatFresh: false } - }) - - await store.recordCellHeartbeat({ - cellId: lowered.id, - cellUrl: lowered.url, - cellIncarnation: '22222222-2222-4222-8222-222222222222', - startedAt: 200, - ready: true, - observedRequests: 0, - totalConnections: 0, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 0, - connectionHardCap: 600, - connectionUnobservedBound: 49 - }) - await expect( - store.assign({ userId: 'admin-restored', relayHostId: 'host000000000097' }) - ).resolves.toMatchObject({ cellId: lowered.id }) - }) - - it('admits exactly one reservation at the admission boundary', async () => { - const { database, store } = await setup(449) - const results = await Promise.allSettled([ - store.assign({ userId: 'user-1', relayHostId: 'host000000000001' }), - store.assign({ userId: 'user-2', relayHostId: 'host000000000002' }) - ]) - - expect(results.filter(({ status }) => status === 'fulfilled')).toHaveLength(1) - expect( - results - .filter(({ status }) => status === 'rejected') - .map((result) => (result.status === 'rejected' ? result.reason : null)) - ).toEqual([expect.objectContaining({ message: 'relay_capacity_exhausted' })]) - expect( - await database.query( - `SELECT activity_id FROM relay_assignment_activity_leases - WHERE activity_kind = 'control' AND activity_id LIKE 'control-pending:%'` - ) - ).toHaveLength(1) - }) - - it('rejects at the boundary before mutating durable assignment state', async () => { - const { database, store } = await setup(450) - - await expect( - store.assign({ userId: 'user-1', relayHostId: 'host000000000001' }) - ).rejects.toThrow('relay_capacity_exhausted') - expect(await database.query(`SELECT * FROM relay_assignments`)).toEqual([]) - expect(await database.query(`SELECT * FROM relay_assignment_activity_leases`)).toEqual([]) - }) - - it('charges every active reservation state at the admission boundary', async () => { - const { database, store } = await setup(447) - await database.query( - `INSERT INTO relay_control_connection_reservations - (reservation_id, idempotency_key, user_id, relay_host_id, - assignment_epoch, cell_id, state, created_at, timeout_at, updated_at) - VALUES - ('active-reserved', 'active-reserved', 'state-user', 'state-host-1', - 1, ?, 'reserved', 1, 2, 1), - ('active-debt', 'active-debt', 'state-user', 'state-host-2', - 1, ?, 'late-arrival-debt', 1, 2, 1), - ('active-claimed', 'active-claimed', 'state-user', 'state-host-3', - 1, ?, 'claimed', 1, 2, 1)`, - [LIMITED_CELL.id, LIMITED_CELL.id, LIMITED_CELL.id] - ) - - await expect( - store.assign({ userId: 'blocked-user', relayHostId: 'blockedhost00001' }) - ).rejects.toThrow('relay_capacity_exhausted') - expect(await database.query(`SELECT * FROM relay_assignment_activity_leases`)).toEqual([]) - }) - - it('does not charge released reservation history', async () => { - const { database, store } = await setup(449) - await database.query( - `INSERT INTO relay_control_connection_reservations - (reservation_id, idempotency_key, user_id, relay_host_id, - assignment_epoch, cell_id, state, created_at, timeout_at, updated_at) - VALUES ('released-history', 'released-history', 'state-user', 'state-host', - 1, ?, 'released', 1, 2, 1)`, - [LIMITED_CELL.id] - ) - - await expect( - store.assign({ userId: 'admitted-user', relayHostId: 'admittedhost0001' }) - ).resolves.toMatchObject({ cellId: LIMITED_CELL.id }) - }) - - it('rejects sticky control restoration before mutating assignment state', async () => { - const { database, store } = await setup(450) - const identity = { userId: 'sticky-user', relayHostId: 'stickyhost000001' } - await database.query( - `INSERT INTO relay_assignments - (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, - last_activity_at, reserved_controls, reserved_splices, reserved_invites, - pending_installs, pending_confirmations, migration_leases) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - [identity.userId, identity.relayHostId, LIMITED_CELL.id, 1, 10_000, 100, 0, 0, 1, 0, 0, 0] - ) - - await expect(store.assign(identity)).rejects.toThrow('relay_connection_headroom_exhausted') - expect( - await database.query( - `SELECT cell_id, assignment_epoch, reserved_controls, reserved_invites - FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([ - { - cell_id: LIMITED_CELL.id, - assignment_epoch: 1, - reserved_controls: 0, - reserved_invites: 1 - } - ]) - expect(await database.query(`SELECT * FROM relay_assignment_activity_leases`)).toEqual([]) - }) - - it('moves a zero-activity assignment off a general cell without connection headroom', async () => { - const { database, store, source, target } = await setupHeadroomReassignment() - const identity = { userId: 'movable-user', relayHostId: 'movablehost000001' } - await database.query( - `INSERT INTO relay_assignments - (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, - last_activity_at, reserved_controls, reserved_splices, reserved_invites, - pending_installs, pending_confirmations, migration_leases) - VALUES (?, ?, ?, ?, ?, ?, 0, 0, 0, 0, 0, 0)`, - [identity.userId, identity.relayHostId, source.id, 7, 10_000, 100] - ) - await database.query( - `INSERT INTO relay_control_connection_reservations - (reservation_id, idempotency_key, user_id, relay_host_id, - assignment_epoch, cell_id, state, inclusion_watermark, - claim_activity_id, created_at, timeout_at, claimed_at, released_at, - updated_at) - VALUES (?, ?, ?, ?, ?, ?, 'late-arrival-debt', NULL, NULL, ?, ?, NULL, NULL, ?)`, - [ - 'superseded-reservation', - 'superseded-reservation', - identity.userId, - identity.relayHostId, - 7, - source.id, - 50, - 99, - 100 - ] - ) - - await expect(store.assign(identity)).resolves.toMatchObject({ - cellId: target.id, - assignmentEpoch: 8 - }) - expect( - await database.query( - `SELECT cell_id, assignment_epoch, reserved_controls - FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ cell_id: target.id, assignment_epoch: 8, reserved_controls: 1 }]) - expect( - await database.query( - `SELECT cell_id, activity_kind FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ cell_id: target.id, activity_kind: 'control' }]) - expect( - await database.query( - `SELECT cell_id, assignment_epoch, state - FROM relay_control_connection_reservations - WHERE user_id = ? AND relay_host_id = ? - ORDER BY assignment_epoch`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([ - { cell_id: source.id, assignment_epoch: 7, state: 'released' }, - { cell_id: target.id, assignment_epoch: 8, state: 'reserved' } - ]) - }) - - it('keeps non-control activity pinned when its cell has no connection headroom', async () => { - const { database, store, source } = await setupHeadroomReassignment() - const identity = { userId: 'pinned-user', relayHostId: 'pinnedhost0000001' } - await database.query( - `INSERT INTO relay_assignments - (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, - last_activity_at, reserved_controls, reserved_splices, reserved_invites, - pending_installs, pending_confirmations, migration_leases) - VALUES (?, ?, ?, ?, ?, ?, 0, 0, 1, 0, 0, 0)`, - [identity.userId, identity.relayHostId, source.id, 7, 10_000, 100] - ) - - await expect(store.assign(identity)).rejects.toThrow('relay_connection_headroom_exhausted') - expect(await store.resolve(identity)).toMatchObject({ - cellId: source.id, - assignmentEpoch: 7 - }) - }) - - it('keeps a zero-activity assignment pinned on an existing-only cell', async () => { - const { database, store, source } = await setupHeadroomReassignment() - const identity = { userId: 'pinned-existing-only-user', relayHostId: 'pinnedexistingonl' } - await store.setCellAdmissionState(source.id, 'existing-only') - await database.query( - `INSERT INTO relay_assignments - (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, - last_activity_at, reserved_controls, reserved_splices, reserved_invites, - pending_installs, pending_confirmations, migration_leases) - VALUES (?, ?, ?, ?, ?, ?, 0, 0, 0, 0, 0, 0)`, - [identity.userId, identity.relayHostId, source.id, 7, 10_000, 100] - ) - - await expect(store.assign(identity)).rejects.toThrow('relay_connection_headroom_exhausted') - expect(await store.resolve(identity)).toMatchObject({ - cellId: source.id, - assignmentEpoch: 7 - }) - expect(await database.query(`SELECT * FROM relay_assignment_activity_leases`)).toEqual([]) - }) - - it('keeps a zero-activity assignment pinned on an unstamped migration-only cell', async () => { - // Why: an evacuation target is deliberately migration-only and deliberately - // full. Without the roll's isolate stamp it must keep the hosts it holds. - const { database, store, source } = await setupHeadroomReassignment() - const identity = { userId: 'pinned-migration-only-user', relayHostId: 'pinnedmigrationonly' } - await store.setCellAdmissionState(source.id, 'migration-only') - await database.query( - `INSERT INTO relay_assignments - (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, - last_activity_at, reserved_controls, reserved_splices, reserved_invites, - pending_installs, pending_confirmations, migration_leases) - VALUES (?, ?, ?, ?, ?, ?, 0, 0, 0, 0, 0, 0)`, - [identity.userId, identity.relayHostId, source.id, 7, 10_000, 100] - ) - - await expect(store.assign(identity)).rejects.toThrow('relay_connection_headroom_exhausted') - expect(await store.resolve(identity)).toMatchObject({ - cellId: source.id, - assignmentEpoch: 7 - }) - }) - - it('renames a pending reservation exactly once on control activation', async () => { - const { database, store } = await setup(449) - const identity = { userId: 'user-1', relayHostId: 'host000000000001' } - const assignment = await store.assign(identity) - - await store.activateControl(identity, { - cellId: LIMITED_CELL.id, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - await store.activateControl(identity, { - cellId: LIMITED_CELL.id, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - - expect( - await database.query( - `SELECT activity_id, request_units FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ activity_id: 'control:limited:1', request_units: 1 }]) - }) - - it('keeps expired pending reservations charged as late-arrival debt', async () => { - let now = 100 - const { database, store } = await setup(449, () => now) - await store.assign({ userId: 'user-1', relayHostId: 'host000000000001' }) - now += ASSIGNMENT_LIMITS.activityLeaseMs + 1 - await store.releaseExpiredActivityLeases() - await store.recordCellHeartbeat({ - cellId: LIMITED_CELL.id, - cellUrl: LIMITED_CELL.url, - cellIncarnation: '11111111-1111-4111-8111-111111111111', - startedAt: 50, - ready: true, - observedRequests: 0, - totalConnections: 449, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 449, - connectionHardCap: 600, - connectionUnobservedBound: 50 - }) - - await expect( - store.assign({ userId: 'user-2', relayHostId: 'host000000000002' }) - ).rejects.toThrow('relay_capacity_exhausted') - expect( - await database.query( - `SELECT activity_id FROM relay_assignment_activity_leases - WHERE activity_kind = 'control' AND activity_id LIKE 'control-pending:%'` - ) - ).toHaveLength(0) - expect(await database.query(`SELECT state FROM relay_control_connection_reservations`)).toEqual( - [{ state: 'late-arrival-debt' }] - ) - }) - it('reconciles late-arrival debt only after a covering absolute snapshot', async () => { let now = 100 const { database, store } = await setup(449, () => now) @@ -559,386 +104,4 @@ describe('relay assignment connection headroom', () => { store.assign({ userId: 'blocked-user', relayHostId: 'blockedhost00001' }) ).rejects.toThrow('relay_capacity_exhausted') }) - - it('rejects duplicate and out-of-order absolute snapshots', async () => { - const { database, store } = await setup(0) - const heartbeat = { - cellId: LIMITED_CELL.id, - cellUrl: LIMITED_CELL.url, - cellIncarnation: '11111111-1111-4111-8111-111111111111', - startedAt: 50, - ready: true, - observedRequests: 0, - totalConnections: 10, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 10, - connectionInclusionWatermark: 10, - connectionHardCap: 600 as const, - connectionUnobservedBound: 50 - } - await store.recordCellHeartbeat(heartbeat) - await expect(store.recordCellHeartbeat(heartbeat)).rejects.toThrow('stale_connection_snapshot') - await expect( - store.recordCellHeartbeat({ - ...heartbeat, - totalConnections: 9, - enforcedConnectionUnits: 9, - connectionInclusionWatermark: 9 - }) - ).rejects.toThrow('stale_connection_snapshot') - expect( - await database.query( - `SELECT inclusion_watermark, enforced_connection_units - FROM relay_cell_connection_snapshots` - ) - ).toEqual([{ inclusion_watermark: 10, enforced_connection_units: 10 }]) - }) - - it('keeps crash retries bound to one reservation claim', async () => { - let now = 100 - const { database, store } = await setup(448, () => now) - const identity = { userId: 'retry-user', relayHostId: 'retryhost0000001' } - const assignment = await store.assign(identity) - await new RelayAssignmentStore(database, () => now, { - requireLiveCells: true, - heartbeatTtlMs: 45_000 - }).assign(identity) - expect(await database.query(`SELECT state FROM relay_control_connection_reservations`)).toEqual( - [{ state: 'reserved' }] - ) - now += ASSIGNMENT_LIMITS.activityLeaseMs + 1 - await store.releaseExpiredActivityLeases() - await store.recordCellHeartbeat({ - cellId: LIMITED_CELL.id, - cellUrl: LIMITED_CELL.url, - cellIncarnation: '11111111-1111-4111-8111-111111111111', - startedAt: 50, - ready: true, - observedRequests: 0, - totalConnections: 448, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 448, - connectionHardCap: 600, - connectionUnobservedBound: 50 - }) - await store.assign(identity) - const restarted = new RelayAssignmentStore(database, () => now, { - requireLiveCells: true, - heartbeatTtlMs: 45_000 - }) - - const activation = { - cellId: LIMITED_CELL.id, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1, - connectionInclusionWatermark: 5 - } - await restarted.activateControl(identity, activation) - await restarted.activateControl(identity, activation) - - expect( - await database.query( - `SELECT state, claim_activity_id - FROM relay_control_connection_reservations - ORDER BY created_at ASC, reservation_id ASC` - ) - ).toEqual([{ state: 'claimed', claim_activity_id: 'control:limited:1' }]) - }) - - it('releases only redundant expired debt after a fresh absolute snapshot', async () => { - let now = 100 - const { database, store } = await setup(449, () => now) - const identity = { userId: 'debt-user', relayHostId: 'debthost000000001' } - const assignment = await store.assign(identity) - now += ASSIGNMENT_LIMITS.activityLeaseMs + 1 - await store.releaseExpiredActivityLeases() - await database.query( - `INSERT INTO relay_control_connection_reservations - (reservation_id, idempotency_key, user_id, relay_host_id, - assignment_epoch, cell_id, state, inclusion_watermark, - claim_activity_id, created_at, timeout_at, claimed_at, released_at, - updated_at) - VALUES (?, ?, ?, ?, ?, ?, 'late-arrival-debt', NULL, NULL, ?, ?, NULL, NULL, ?)`, - [ - 'duplicate-reservation', - 'duplicate-reservation', - identity.userId, - identity.relayHostId, - assignment.assignmentEpoch, - LIMITED_CELL.id, - 101, - now - 1, - now - ] - ) - - await store.recordCellHeartbeat({ - cellId: LIMITED_CELL.id, - cellUrl: LIMITED_CELL.url, - cellIncarnation: '11111111-1111-4111-8111-111111111111', - startedAt: 50, - ready: true, - observedRequests: 0, - totalConnections: 449, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 449, - connectionInclusionWatermark: 5, - connectionHardCap: 600, - connectionUnobservedBound: 50 - }) - - expect( - await database.query( - `SELECT state, COUNT(*) AS count - FROM relay_control_connection_reservations - GROUP BY state ORDER BY state` - ) - ).toEqual([ - { state: 'late-arrival-debt', count: 1 }, - { state: 'released', count: 1 } - ]) - }) - - it('releases expired debt for a snapshot-proven aborted older epoch', async () => { - const now = 1_000 - const { database, store } = await setup(0, () => now) - const identity = { userId: 'aborted-user', relayHostId: 'abortedhost00001' } - await database.query( - `INSERT INTO relay_assignments - (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, - last_activity_at, reserved_controls, reserved_splices, reserved_invites, - pending_installs, pending_confirmations, migration_leases) - VALUES (?, ?, ?, ?, ?, ?, 0, 0, 0, 0, 0, 0)`, - [identity.userId, identity.relayHostId, LIMITED_CELL.id, 3, now, now] - ) - await database.query( - `INSERT INTO relay_assignment_migrations - (user_id, relay_host_id, source_cell_id, target_cell_id, - previous_epoch, assignment_epoch, source_request_units, - target_reserved_units, expires_at, target_registered_at, - completed_at, aborted_at, created_at, updated_at) - VALUES (?, ?, ?, ?, 1, 2, 0, 1, ?, ?, NULL, ?, ?, ?)`, - [ - identity.userId, - identity.relayHostId, - 'source', - LIMITED_CELL.id, - now - 2, - now - 3, - now - 1, - now - 4, - now - 1 - ] - ) - await database.query( - `INSERT INTO relay_control_connection_reservations - (reservation_id, idempotency_key, user_id, relay_host_id, - assignment_epoch, cell_id, state, inclusion_watermark, - claim_activity_id, created_at, timeout_at, claimed_at, released_at, - updated_at) - VALUES (?, ?, ?, ?, 2, ?, 'late-arrival-debt', NULL, NULL, ?, ?, NULL, NULL, ?)`, - [ - 'aborted-reservation', - 'aborted-reservation', - identity.userId, - identity.relayHostId, - LIMITED_CELL.id, - now - 4, - now - 2, - now - 1 - ] - ) - - await store.recordCellHeartbeat({ - cellId: LIMITED_CELL.id, - cellUrl: LIMITED_CELL.url, - cellIncarnation: '11111111-1111-4111-8111-111111111111', - startedAt: 50, - ready: true, - observedRequests: 0, - totalConnections: 0, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 0, - connectionInclusionWatermark: 5, - connectionHardCap: 600, - connectionUnobservedBound: 50 - }) - - expect( - await database.query( - `SELECT state FROM relay_control_connection_reservations - WHERE reservation_id = ?`, - ['aborted-reservation'] - ) - ).toEqual([{ state: 'released' }]) - }) - - it('fails a limited cell closed on stale telemetry while leaving legacy cells unchanged', async () => { - let now = 100 - const { store } = await setup(0, () => now) - now += 45_001 - await expect( - store.assign({ userId: 'user-1', relayHostId: 'host000000000001' }) - ).rejects.toThrow('relay_capacity_exhausted') - - const legacyDatabase = await openInMemoryRelayDatabase() - databases.push(legacyDatabase) - const legacyStore = new RelayAssignmentStore(legacyDatabase, () => now, { - requireLiveCells: true, - heartbeatTtlMs: 45_000 - }) - const legacy = { - id: 'legacy', - url: 'https://legacy.example.com', - capacityRequests: 10 - } - await legacyStore.reconcileCells([legacy], true) - await legacyStore.recordCellHeartbeat({ - cellId: legacy.id, - cellUrl: legacy.url, - cellIncarnation: '22222222-2222-4222-8222-222222222222', - startedAt: now, - ready: true, - observedRequests: 0 - }) - await expect( - legacyStore.assign({ userId: 'user-2', relayHostId: 'host000000000002' }) - ).resolves.toMatchObject({ cellId: 'legacy' }) - }) - - it('does not create connection debt for mixed-version uncapped cells', async () => { - let now = 100 - const legacy = { - id: 'legacy', - url: 'https://legacy.example.com', - capacityRequests: 10 - } - const { database, store } = await setup(0, () => now) - await store.reconcileCells([legacy], true) - await store.recordCellHeartbeat({ - cellId: legacy.id, - cellUrl: legacy.url, - cellIncarnation: '22222222-2222-4222-8222-222222222222', - startedAt: 50, - ready: true, - observedRequests: 0 - }) - - await store.assign({ userId: 'legacy-user', relayHostId: 'legacyhost000001' }) - expect(await database.query(`SELECT * FROM relay_control_connection_reservations`)).toEqual([]) - expect(await store.releaseExpiredActivityLeases()).toBe(0) - now += ASSIGNMENT_LIMITS.activityLeaseMs + 1 - expect(await store.releaseExpiredActivityLeases()).toBe(1) - expect(await database.query(`SELECT * FROM relay_control_connection_reservations`)).toEqual([]) - }) - - it('rejects dormant rebalance before changing the assignment epoch', async () => { - const now = ASSIGNMENT_LIMITS.dormantTtlMs + 100 - const database = await openInMemoryRelayDatabase() - databases.push(database) - const store = new RelayAssignmentStore(database, () => now, { - requireLiveCells: true, - heartbeatTtlMs: 45_000 - }) - const source = { - id: 'source', - url: 'https://source.example.com', - capacityRequests: 10 - } - await store.reconcileCells([source, LIMITED_CELL], true) - await store.recordCellHeartbeat({ - cellId: source.id, - cellUrl: source.url, - cellIncarnation: '22222222-2222-4222-8222-222222222222', - startedAt: now - 50, - ready: true, - observedRequests: 0 - }) - await store.recordCellHeartbeat({ - cellId: LIMITED_CELL.id, - cellUrl: LIMITED_CELL.url, - cellIncarnation: '11111111-1111-4111-8111-111111111111', - startedAt: now - 50, - ready: true, - observedRequests: 0, - totalConnections: 450, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 450, - connectionHardCap: 600, - connectionUnobservedBound: 50 - }) - const identity = { userId: 'dormant-user', relayHostId: 'dormanthost00001' } - await database.query( - `INSERT INTO relay_assignments - (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, - last_activity_at, reserved_controls, reserved_splices, reserved_invites, - pending_installs, pending_confirmations, migration_leases) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - [identity.userId, identity.relayHostId, source.id, 7, 0, 0, 0, 0, 0, 0, 0, 0] - ) - - await expect(store.rebalanceDormant(identity, LIMITED_CELL.id)).rejects.toThrow( - 'relay_connection_headroom_exhausted' - ) - expect(await store.resolve(identity)).toMatchObject({ - cellId: source.id, - assignmentEpoch: 7 - }) - expect(await database.query(`SELECT * FROM relay_assignment_activity_leases`)).toEqual([]) - }) - - it('rejects an evacuation target at its pause before migration mutation', async () => { - const database = await openInMemoryRelayDatabase() - databases.push(database) - const store = new RelayAssignmentStore(database, () => 100, { - requireLiveCells: true, - heartbeatTtlMs: 45_000 - }) - const source = { - id: 'source', - url: 'https://source.example.com', - capacityRequests: 10 - } - await store.reconcileCells([source, { ...LIMITED_CELL, initiallyEnabled: false }], true) - await store.recordCellHeartbeat({ - cellId: source.id, - cellUrl: source.url, - cellIncarnation: '22222222-2222-4222-8222-222222222222', - startedAt: 50, - ready: true, - observedRequests: 0 - }) - await store.recordCellHeartbeat({ - cellId: LIMITED_CELL.id, - cellUrl: LIMITED_CELL.url, - cellIncarnation: '11111111-1111-4111-8111-111111111111', - startedAt: 50, - ready: true, - observedRequests: 0, - totalConnections: 450, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 450, - connectionHardCap: 600, - connectionUnobservedBound: 50 - }) - const identity = { userId: 'user-1', relayHostId: 'host000000000001' } - const assignment = await store.assign(identity) - expect(assignment.cellId).toBe(source.id) - await store.setCellEnabled(LIMITED_CELL.id, true) - - await expect(store.startEvacuation(identity, LIMITED_CELL.id)).rejects.toThrow( - 'relay_connection_headroom_exhausted' - ) - expect(await database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) - expect(await store.resolve(identity)).toMatchObject({ - cellId: source.id, - assignmentEpoch: assignment.assignmentEpoch - }) - }) }) diff --git a/cloud/apps/relay/src/assignment/assignment-isolated-cell-replacement-postgres.test.ts b/cloud/apps/relay/src/assignment/assignment-isolated-cell-replacement-postgres.test.ts index d552d8710e8..8e533d9468b 100644 --- a/cloud/apps/relay/src/assignment/assignment-isolated-cell-replacement-postgres.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-isolated-cell-replacement-postgres.test.ts @@ -1,4 +1,3 @@ -import { ASSIGNMENT_LIMITS } from '@orca-cloud/relay-contract/assignment-invariants' import { createHash } from 'node:crypto' import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' import { RelayAssignmentRowBusyError, RelayAssignmentStore } from './assignment-store.js' @@ -52,7 +51,6 @@ const OTHER_REGION: RelayCellConfig = { ...CAPPED } const CELLS = [ISOLATED, ...TARGETS, OTHER_REGION] -const HOST_COUNT = 50 function hostIdentity(index: number): { userId: string; relayHostId: string } { return { @@ -74,48 +72,6 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () => return Number(rows[0]!['reserved_requests']) } - // The accounting invariant the migration paths assert: a cell's counter is - // exactly the units of the leases held on it. - async function expectReservationAccounting(): Promise { - for (const cell of CELLS) { - const leased = await databases[0]!.query( - `SELECT COALESCE(SUM(request_units), 0) AS units - FROM relay_assignment_activity_leases WHERE cell_id = ?`, - [cell.id] - ) - expect({ cell: cell.id, reserved: await reservedRequests(cell.id) }).toEqual({ - cell: cell.id, - reserved: Number(leased[0]!['units']) - }) - } - } - - async function expectReservationAccountingExcept(cellId: string): Promise { - for (const cell of CELLS.filter(({ id }) => id !== cellId)) { - const leased = await databases[0]!.query( - `SELECT COALESCE(SUM(request_units), 0) AS units - FROM relay_assignment_activity_leases WHERE cell_id = ?`, - [cell.id] - ) - expect(await reservedRequests(cell.id)).toBe(Number(leased[0]!['units'])) - } - } - - async function counters(identity: { - userId: string - relayHostId: string - }): Promise<{ controls: number; splices: number }> { - const rows = await databases[0]!.query( - `SELECT reserved_controls, reserved_splices FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - return { - controls: Number(rows[0]!['reserved_controls']), - splices: Number(rows[0]!['reserved_splices']) - } - } - // Holds the named relay_cells rows in another session until released, the // way a release from a far cell holds its row across a round trip. async function holdCellRows(cellIds: string[]): Promise<() => Promise> { @@ -144,40 +100,18 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () => } async function waitForLock(table: 'relay_cells' | 'relay_assignments'): Promise { - await vi.waitFor(async () => { - const rows = await databases[0]!.query( - `SELECT COUNT(*) AS waiting FROM pg_stat_activity + await vi.waitFor( + async () => { + const rows = await databases[0]!.query( + `SELECT COUNT(*) AS waiting FROM pg_stat_activity WHERE datname = current_database() AND wait_event_type = 'Lock' AND application_name = ? AND query LIKE ? AND query LIKE '%FOR UPDATE%'`, - [databaseApplicationName(1), `%${table}%`] - ) - expect(Number(rows[0]?.['waiting'])).toBeGreaterThan(0) - }, { timeout: 4_000, interval: 10 }) - } - - // Puts a host on the source with a live control and a splice, then isolates - // the source for a roll with both targets open. - async function seedActiveHostOnIsolatedSource(index: number): Promise<{ - identity: { userId: string; relayHostId: string } - first: { cellId: string; assignmentEpoch: number } - }> { - const identity = hostIdentity(index) - await applySelector({ [TARGETS[0]!.id]: 'migration-only', [TARGETS[1]!.id]: 'migration-only' }) - const first = await stores[0]!.assign(identity, 'us-central1') - expect(first.cellId).toBe(ISOLATED.id) - await stores[0]!.activateControl(identity, { - cellId: ISOLATED.id, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await stores[0]!.acquireActivity(identity, { - activityId: 'splice:keep-1', - kind: 'splice', - cellId: ISOLATED.id - }) - await applySelector({ [TARGETS[0]!.id]: 'general', [TARGETS[1]!.id]: 'general' }) - await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id]) - return { identity, first } + [databaseApplicationName(1), `%${table}%`] + ) + expect(Number(rows[0]?.['waiting'])).toBeGreaterThan(0) + }, + { timeout: 4_000, interval: 10 } + ) } // `enforced` puts a cell at its connection cap, which leaves it no headroom. @@ -211,9 +145,7 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () => const current = await stores[0]!.inspectCellAdmissionSelector() // Built from relay_cells, not from the selector's own membership: the apply // requires exact coverage of the fleet, and this database is shared. - const fleet = await databases[0]!.query( - `SELECT cell_id FROM relay_cells ORDER BY cell_id ASC` - ) + const fleet = await databases[0]!.query(`SELECT cell_id FROM relay_cells ORDER BY cell_id ASC`) const membership: CellAdmissionMembership = { existingOnly: [], migrationOnly: [], @@ -251,15 +183,6 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () => }) } - async function rollIsolatedAt(cellId: string): Promise { - const rows = await databases[0]!.query( - `SELECT roll_isolated_at FROM relay_cell_admission WHERE cell_id = ?`, - [cellId] - ) - const value = rows[0]?.['roll_isolated_at'] - return value === undefined || value === null ? null : Number(value) - } - // Every case starts from the whole fleet general; a case that leaves a cell // isolated would otherwise starve the next one of placement candidates. async function resetFleet(): Promise { @@ -301,11 +224,13 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () => // Four connections so the concurrent dials below really contend on the // fleet-wide relay_cells lock rather than queueing in one client. for (let index = 0; index < 4; index += 1) { - databases.push(await openRelayDatabase({ - databaseUrl, - dataDir: '', - applicationName: databaseApplicationName(index) - })) + databases.push( + await openRelayDatabase({ + databaseUrl, + dataDir: '', + applicationName: databaseApplicationName(index) + }) + ) } stores = databases.map( (database) => @@ -344,129 +269,6 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () => for (const connection of databases) await connection.close() }) - it('stamps only the named cell on isolate and clears it on restore', async () => { - await resetFleet() - expect(await rollIsolatedAt(ISOLATED.id)).toBeNull() - - await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id]) - const stamped = await rollIsolatedAt(ISOLATED.id) - expect(stamped).toBe(NOW) - // Cells the isolate did not name stay unmarked even when parked in the same - // apply: that is every non-roll flow, and its hosts must keep their pin. - await applySelector({ [TARGETS[0]!.id]: 'migration-only' }) - expect(await rollIsolatedAt(TARGETS[0]!.id)).toBeNull() - - // A failed wave re-isolates rather than restoring; the stamp survives, and - // does not move, so the hosts left behind stay eligible. - await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id]) - expect(await rollIsolatedAt(ISOLATED.id)).toBe(stamped) - - // Restore writes 'general', and the same statement clears the stamp. - await applySelector({ [ISOLATED.id]: 'general' }) - expect(await rollIsolatedAt(ISOLATED.id)).toBeNull() - }, 30_000) - - it('classifies a reconnect by its home cell’s stamp in the verification read', async () => { - await resetFleet() - const identity = hostIdentity(903) - const classify = { classifyHomeRollIsolation: true } - await applySelector({ [TARGETS[0]!.id]: 'migration-only', [TARGETS[1]!.id]: 'migration-only' }) - const first = await stores[0]!.assign(identity, 'us-central1') - await applySelector({ [TARGETS[0]!.id]: 'general', [TARGETS[1]!.id]: 'general' }) - expect(first.cellId).toBe(ISOLATED.id) - expect(await stores[0]!.resolve(identity, classify)).not.toHaveProperty('homeCellRollIsolated') - - await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id]) - expect(await stores[0]!.resolve(identity, classify)).toMatchObject({ - cellId: ISOLATED.id, - homeCellRollIsolated: true - }) - - await applySelector({ [ISOLATED.id]: 'general' }) - expect(await stores[0]!.resolve(identity, classify)).not.toHaveProperty('homeCellRollIsolated') - }, 30_000) - - it('ignores a stamp older than the roll it is supposed to describe', async () => { - // A failed wave keeps its stamp on purpose and can sit for hours; past the - // bound the cell stops shedding hosts one dial at a time. - await resetFleet() - const identity = hostIdentity(902) - const first = await stores[0]!.assign(identity, 'us-central1') - await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id]) - await databases[0]!.query( - `UPDATE relay_cell_admission SET roll_isolated_at = ? WHERE cell_id = ?`, - [NOW - (2 * 60 * 60_000 + 1), ISOLATED.id] - ) - - expect(await stores[0]!.assign(identity, 'us-central1')).toMatchObject({ - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch - }) - }, 30_000) - - it('re-places every host off an isolated cell without leaking a reservation', async () => { - await resetFleet() - const identities = Array.from({ length: HOST_COUNT }, (_, index) => hostIdentity(index)) - const sourceBaseline = await reservedRequests(ISOLATED.id) - const targetBaseline = - (await reservedRequests(TARGETS[0]!.id)) + (await reservedRequests(TARGETS[1]!.id)) - - // Everyone lands on the cell about to be isolated. - await applySelector({ [TARGETS[0]!.id]: 'migration-only', [TARGETS[1]!.id]: 'migration-only' }) - const first = new Map() - for (const identity of identities) { - const grant = await stores[0]!.assign(identity, 'us-central1') - expect(grant.cellId).toBe(ISOLATED.id) - first.set(identity.relayHostId, grant) - } - await applySelector({ [TARGETS[0]!.id]: 'general', [TARGETS[1]!.id]: 'general' }) - - // The isolate step. The state and the stamp are written by one UPDATE under - // the fleet-wide relay_cells lock, so there is no torn state to race against. - await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id]) - expect(await rollIsolatedAt(ISOLATED.id)).not.toBeNull() - - const grants = await Promise.all( - identities.map( - async (identity, index) => - await stores[1 + (index % (stores.length - 1))]!.assign(identity, 'us-central1') - ) - ) - - for (const [index, grant] of grants.entries()) { - const identity = identities[index]! - expect(grant.cellId).not.toBe(ISOLATED.id) - expect(TARGETS.map(({ id }) => id)).toContain(grant.cellId) - // Exactly once: a double bump would mean two transactions both moved it. - expect(grant.assignmentEpoch).toBe(first.get(identity.relayHostId)!.assignmentEpoch + 1) - } - - // The placement leaves the source row alone: each host's pending control - // there still counts until the source releases it. - expect(await reservedRequests(ISOLATED.id)).toBe(sourceBaseline + HOST_COUNT) - expect( - (await reservedRequests(TARGETS[0]!.id)) + (await reservedRequests(TARGETS[1]!.id)) - ).toBe(targetBaseline + HOST_COUNT) - await expectReservationAccounting() - for (const identity of identities) { - expect( - await stores[0]!.releaseActivity( - identity, - `control-pending:${first.get(identity.relayHostId)!.assignmentEpoch}` - ) - ).toBe(true) - } - expect(await reservedRequests(ISOLATED.id)).toBe(sourceBaseline) - await expectReservationAccounting() - - const rows = await databases[0]!.query( - `SELECT COUNT(*) AS count FROM relay_assignments - WHERE user_id LIKE '${USER_PREFIX}-%' AND cell_id = ?`, - [ISOLATED.id] - ) - expect(Number(rows[0]!['count'])).toBe(0) - }, 60_000) - it('lets exactly one of a host’s racing dials win the re-placement', async () => { await resetFleet() const identity = hostIdentity(900) @@ -486,9 +288,7 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () => stores[1]!.assign(identity, 'us-central1'), stores[2]!.assign(identity, 'us-central1') ]) - const granted = raced.flatMap((result) => - result.status === 'fulfilled' ? [result.value] : [] - ) + const granted = raced.flatMap((result) => (result.status === 'fulfilled' ? [result.value] : [])) expect(granted.length).toBeGreaterThan(0) // Concurrent dials may grant repeatedly but commit one move: one epoch/unit on target, preserving source leases until release. @@ -502,399 +302,6 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () => ).toBe(targetBaseline + 1) }, 30_000) - it('grants no host the isolated cell after the admission flip commits', async () => { - await resetFleet() - const identity = hostIdentity(901) - const first = await stores[0]!.assign(identity, 'us-central1') - await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id]) - - for (let dial = 0; dial < 5; dial += 1) { - const grant = await stores[1 + (dial % (stores.length - 1))]!.assign( - identity, - 'us-central1' - ) - expect(grant.cellId).not.toBe(ISOLATED.id) - } - // Only the first dial re-places; the rest are ordinary sticky re-grants. - expect((await stores[0]!.resolve(identity))?.assignmentEpoch).toBe( - first.assignmentEpoch + 1 - ) - }, 30_000) - it('leaves the source row to the source’s own releases and keeps the host’s counters', async () => { - await resetFleet() - const { identity, first } = await seedActiveHostOnIsolatedSource(910) - const sourceBefore = await reservedRequests(ISOLATED.id) - const targetsBefore = - (await reservedRequests(TARGETS[0]!.id)) + (await reservedRequests(TARGETS[1]!.id)) - expect(sourceBefore).toBe(3) - expect(await counters(identity)).toEqual({ controls: 1, splices: 1 }) - - const moved = await stores[1]!.assign(identity, 'us-central1') - expect(TARGETS.map(({ id }) => id)).toContain(moved.cellId) - expect(moved.assignmentEpoch).toBe(first.assignmentEpoch + 1) - expect(await reservedRequests(ISOLATED.id)).toBe(sourceBefore) - expect( - (await reservedRequests(TARGETS[0]!.id)) + (await reservedRequests(TARGETS[1]!.id)) - ).toBe(targetsBefore + 1) - // One control added on the target; the source's control and splice kept. - expect(await counters(identity)).toEqual({ controls: 2, splices: 1 }) - await expectReservationAccounting() - - // The source closes the host's sockets: each release takes its own units. - expect(await stores[0]!.releaseActivity(identity, `control:${ISOLATED.id}:1`)).toBe(true) - expect(await reservedRequests(ISOLATED.id)).toBe(sourceBefore - 1) - expect(await counters(identity)).toEqual({ controls: 1, splices: 1 }) - expect(await stores[0]!.releaseActivity(identity, 'splice:keep-1')).toBe(true) - expect(await reservedRequests(ISOLATED.id)).toBe(0) - // The target's control survives the source's releases. - expect(await counters(identity)).toEqual({ controls: 1, splices: 0 }) - await expectReservationAccounting() - }, 30_000) - - it('re-places an isolated incumbent while the source row is held', async () => { - await resetFleet() - const { identity, first } = await seedActiveHostOnIsolatedSource(911) - const sourceBefore = await reservedRequests(ISOLATED.id) - const release = await holdCellRows([ISOLATED.id]) - try { - // Held far past the 500ms bounded wait: a placement that asked for the - // source row could not finish inside this window. - const moved = await Promise.race([ - stores[1]!.assign(identity, 'us-central1'), - new Promise<'blocked'>((resolve) => setTimeout(() => resolve('blocked'), 3_000)) - ]) - expect(moved).not.toBe('blocked') - expect(moved).toMatchObject({ assignmentEpoch: first.assignmentEpoch + 1 }) - } finally { - await release() - } - expect(await reservedRequests(ISOLATED.id)).toBe(sourceBefore) - await expectReservationAccounting() - }, 30_000) - - it('waits for the target rows it increments', async () => { - await resetFleet() - const { identity, first } = await seedActiveHostOnIsolatedSource(912) - const targetsBefore = - (await reservedRequests(TARGETS[0]!.id)) + (await reservedRequests(TARGETS[1]!.id)) - const release = await holdCellRows(TARGETS.map(({ id }) => id)) - const placement = stores[1]!.assign(identity, 'us-central1') - try { - await waitForLock('relay_cells') - } finally { - await release() - await placement.catch(() => undefined) - } - expect(await placement).toMatchObject({ assignmentEpoch: first.assignmentEpoch + 1 }) - expect( - (await reservedRequests(TARGETS[0]!.id)) + (await reservedRequests(TARGETS[1]!.id)) - ).toBe(targetsBefore + 1) - await expectReservationAccounting() - }, 30_000) - - it('keeps the pin when no general cell in any region has headroom', async () => { - await resetFleet() - const { identity, first } = await seedActiveHostOnIsolatedSource(913) - const sourceBefore = await reservedRequests(ISOLATED.id) - await databases[0]!.query( - `UPDATE relay_cells SET reserved_requests = capacity_requests WHERE cell_id IN (?, ?, ?)`, - [...TARGETS, OTHER_REGION].map(({ id }) => id) - ) - try { - expect(await stores[1]!.assign(identity, 'us-central1')).toMatchObject({ - cellId: ISOLATED.id, - assignmentEpoch: first.assignmentEpoch - }) - expect(await reservedRequests(ISOLATED.id)).toBe(sourceBefore) - expect(await counters(identity)).toEqual({ controls: 1, splices: 1 }) - } finally { - await databases[0]!.query( - `UPDATE relay_cells SET reserved_requests = 0 WHERE cell_id IN (?, ?, ?)`, - [...TARGETS, OTHER_REGION].map(({ id }) => id) - ) - } - }, 30_000) - - it('moves to another region when its own is at the connection cap, without the source row', async () => { - await resetFleet() - const { identity, first } = await seedActiveHostOnIsolatedSource(917) - const sourceBefore = await reservedRequests(ISOLATED.id) - await heartbeatAll(Object.fromEntries(TARGETS.map(({ id }) => [id, 600]))) - const release = await holdCellRows([ISOLATED.id]) - try { - const moved = await Promise.race([ - stores[1]!.assign(identity, 'us-central1'), - new Promise<'blocked'>((resolve) => setTimeout(() => resolve('blocked'), 3_000)) - ]) - expect(moved).toMatchObject({ - cellId: OTHER_REGION.id, - region: 'asia-east2', - assignmentEpoch: first.assignmentEpoch + 1 - }) - } finally { - await release() - await heartbeatAll() - } - expect(await reservedRequests(ISOLATED.id)).toBe(sourceBefore) - expect(await reservedRequests(OTHER_REGION.id)).toBe(1) - await expectReservationAccounting() - }, 30_000) - it('places a dormant host without asking for its old cell row', async () => { - await resetFleet() - const identity = hostIdentity(914) - await applySelector({ [TARGETS[0]!.id]: 'migration-only', [TARGETS[1]!.id]: 'migration-only' }) - const first = await stores[0]!.assign(identity, 'us-central1') - expect(first.cellId).toBe(ISOLATED.id) - // Dormant: no units held and no activity inside the dormancy window. - await databases[0]!.query( - `DELETE FROM relay_assignment_activity_leases WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - await databases[0]!.query( - `UPDATE relay_assignments SET reserved_controls = 0, last_activity_at = ? - WHERE user_id = ? AND relay_host_id = ?`, - [NOW - ASSIGNMENT_LIMITS.dormantTtlMs, identity.userId, identity.relayHostId] - ) - await databases[0]!.query(`UPDATE relay_cells SET reserved_requests = 0 WHERE cell_id = ?`, [ - ISOLATED.id - ]) - await applySelector({ [TARGETS[0]!.id]: 'general', [TARGETS[1]!.id]: 'general' }) - await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id]) - - const release = await holdCellRows([ISOLATED.id]) - try { - const moved = await Promise.race([ - stores[1]!.assign(identity, 'us-central1'), - new Promise<'blocked'>((resolve) => setTimeout(() => resolve('blocked'), 3_000)) - ]) - expect(moved).toMatchObject({ assignmentEpoch: first.assignmentEpoch + 1 }) - expect(TARGETS.map(({ id }) => id)).toContain(moved === 'blocked' ? moved : moved.cellId) - } finally { - await release() - } - await expectReservationAccounting() - }, 30_000) - // Moves a seeded host onto TARGETS[0] next to another host whose splice there - // outlives the test, so an over-charge shows instead of clamping at zero. - async function seedMovedHostBesideNeighbour(index: number): Promise<{ - identity: { userId: string; relayHostId: string } - neighbour: { userId: string; relayHostId: string } - }> { - const { identity } = await seedActiveHostOnIsolatedSource(index) - await applySelector({ [TARGETS[1]!.id]: 'migration-only' }) - const neighbour = hostIdentity(index + 50) - expect((await stores[0]!.assign(neighbour, 'us-central1')).cellId).toBe(TARGETS[0]!.id) - await stores[0]!.acquireActivity(neighbour, { - activityId: 'splice:neighbour', - kind: 'splice', - cellId: TARGETS[0]!.id, - expiresAt: NOW + 10 * 60 * 60_000 - }) - expect((await stores[1]!.assign(identity, 'us-central1')).cellId).toBe(TARGETS[0]!.id) - expect(await counters(identity)).toEqual({ controls: 2, splices: 1 }) - await expectReservationAccounting() - return { identity, neighbour } - } - - it('leaves a host with leases on two cells to the lease sweep', async () => { - await resetFleet() - const { identity } = await seedMovedHostBesideNeighbour(915) - // Past every lease but the neighbour's splice. - const later = new RelayAssignmentStore(databases[0]!, () => NOW + 60 * 60_000, { - requireLiveCells: true, - heartbeatTtlMs: 45_000 - }) - try { - // Aggregate expiry first, with the source's leases still present: the - // order a lease sweep skipped on a busy row leaves behind. - await later.releaseExpiredActivity() - expect(await counters(identity)).toEqual({ controls: 2, splices: 1 }) - await expectReservationAccounting() - await later.releaseExpiredActivityLeases() - await later.releaseExpiredActivity() - expect(await counters(identity)).toEqual({ controls: 0, splices: 0 }) - expect(await reservedRequests(ISOLATED.id)).toBe(0) - // Only the neighbour's splice is left on the target. - expect(await reservedRequests(TARGETS[0]!.id)).toBe(2) - await expectReservationAccounting() - } finally { - await applySelector({ [TARGETS[1]!.id]: 'general' }) - } - }, 30_000) - - it('frees the source leases on their own cell when the target dies', async () => { - await resetFleet() - const { identity } = await seedMovedHostBesideNeighbour(916) - // The roll finishes, then the target stops heartbeating before the source - // has released the host. Uncapped, so no fence is needed to move off it. - await applySelector({ [ISOLATED.id]: 'general' }) - await databases[0]!.query(`UPDATE relay_cell_runtime SET ready = 0 WHERE cell_id = ?`, [ - TARGETS[0]!.id - ]) - await databases[0]!.query(`DELETE FROM relay_cell_connection_limits WHERE cell_id = ?`, [ - TARGETS[0]!.id - ]) - try { - const moved = await stores[1]!.assign(identity, 'us-central1') - expect(moved.cellId).toBe(ISOLATED.id) - expect(await counters(identity)).toEqual({ controls: 1, splices: 0 }) - // The deleted source leases took their units with them; a late release - // from the source finds nothing and charges nothing. - expect(await stores[0]!.releaseActivity(identity, `control:${ISOLATED.id}:1`)).toBe(false) - expect(await reservedRequests(ISOLATED.id)).toBe(1) - expect(await reservedRequests(TARGETS[0]!.id)).toBe(3) - await expectReservationAccounting() - } finally { - // Re-registers the connection limit, then the heartbeat restores ready. - await stores[0]!.reconcileCells(CELLS, false) - await heartbeatAll() - await applySelector({ [TARGETS[1]!.id]: 'general' }) - } - }, 30_000) - // A host main's old placement left behind: its counters were reset while its - // source lease stayed, and the lease's release floored them at zero. - async function seedDriftedHost( - index: number, - counted: { controls: number; unbackedSourceUnits: number } - ): Promise<{ identity: { userId: string; relayHostId: string }; epoch: number }> { - const identity = hostIdentity(index) - await applySelector({ [TARGETS[0]!.id]: 'migration-only', [TARGETS[1]!.id]: 'migration-only' }) - const first = await stores[0]!.assign(identity, 'us-central1') - expect(first.cellId).toBe(ISOLATED.id) - await stores[0]!.activateControl(identity, { - cellId: ISOLATED.id, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await databases[0]!.query( - `UPDATE relay_assignments SET reserved_controls = ? WHERE user_id = ? AND relay_host_id = ?`, - [counted.controls, identity.userId, identity.relayHostId] - ) - // Units the source still counts with no lease behind them. - await databases[0]!.query( - `UPDATE relay_cells SET reserved_requests = reserved_requests + ? WHERE cell_id = ?`, - [counted.unbackedSourceUnits, ISOLATED.id] - ) - await applySelector({ [TARGETS[0]!.id]: 'general', [TARGETS[1]!.id]: 'general' }) - await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id]) - return { identity, epoch: first.assignmentEpoch } - } - - it('heals counters below the leases on the narrowed path', async () => { - await resetFleet() - const { identity, epoch } = await seedDriftedHost(918, { controls: 0, unbackedSourceUnits: 0 }) - expect(await counters(identity)).toEqual({ controls: 0, splices: 0 }) - await expectReservationAccounting() - const release = await holdCellRows([ISOLATED.id]) - try { - const moved = await Promise.race([ - stores[1]!.assign(identity, 'us-central1'), - new Promise<'blocked'>((resolve) => setTimeout(() => resolve('blocked'), 3_000)) - ]) - expect(moved).toMatchObject({ assignmentEpoch: epoch + 1 }) - expect(TARGETS.map(({ id }) => id)).toContain(moved === 'blocked' ? moved : moved.cellId) - } finally { - await release() - } - // The kept source control plus the new one. - expect(await counters(identity)).toEqual({ controls: 2, splices: 0 }) - await expectReservationAccounting() - expect(await stores[0]!.releaseActivity(identity, `control:${ISOLATED.id}:1`)).toBe(true) - expect(await counters(identity)).toEqual({ controls: 1, splices: 0 }) - expect(await reservedRequests(ISOLATED.id)).toBe(0) - await expectReservationAccounting() - }, 30_000) - - it('takes the all-rows path for units no lease backs', async () => { - await resetFleet() - const { identity, epoch } = await seedDriftedHost(919, { controls: 3, unbackedSourceUnits: 2 }) - await expectReservationAccountingExcept(ISOLATED.id) - const release = await holdCellRows([ISOLATED.id]) - const held = stores[1]!.assign(identity, 'us-central1').then( - () => 'placed' as const, - () => 'failed' as const - ) - try { - // It needs the source row to take the unbacked units off it, so while the - // row is held it either waits or times out; it never places. - expect( - await Promise.race([ - held, - new Promise<'waiting'>((resolve) => setTimeout(() => resolve('waiting'), 1_000)) - ]) - ).not.toBe('placed') - } finally { - await release() - } - await held - // Whether the held dial finished after the release or failed, the next one - // lands the single move. - expect(await stores[1]!.assign(identity, 'us-central1')).toMatchObject({ - assignmentEpoch: epoch + 1 - }) - expect(await counters(identity)).toEqual({ controls: 2, splices: 0 }) - await expectReservationAccounting() - }, 30_000) - it('refuses at once while the host’s own release holds its assignment row', async () => { - await resetFleet() - const { identity, epoch } = await seedDriftedHost(921, { controls: 1, unbackedSourceUnits: 0 }) - const release = await holdRows( - `SELECT user_id FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - try { - const startedAt = performance.now() - await expect(stores[1]!.assign(identity, 'us-central1')).rejects.toBeInstanceOf( - RelayAssignmentRowBusyError - ) - // An isolated pin gets no wait: far under the 1s a release can hold it. - expect(performance.now() - startedAt).toBeLessThan(500) - } finally { - await release() - } - expect((await stores[0]!.resolve(identity))?.assignmentEpoch).toBe(epoch) - expect((await stores[1]!.assign(identity, 'us-central1')).assignmentEpoch).toBe(epoch + 1) - await expectReservationAccounting() - }, 30_000) - - it('waits up to a second for the row of a host pinned to a live general cell', async () => { - await resetFleet() - const identity = hostIdentity(922) - const first = await stores[0]!.assign(identity, 'us-central1') - const holdAssignment = async (): Promise<() => Promise> => - await holdRows( - `SELECT user_id FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - - // A short hold, like a calm host's own release: the sticky re-grant waits. - const shortHold = await holdAssignment() - const regrant = stores[1]!.assign(identity, 'us-central1') - try { - await waitForLock('relay_assignments') - } finally { - await shortHold() - await regrant.catch(() => undefined) - } - expect(await regrant).toMatchObject({ - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch - }) - - // Held past the bound: refused, after about the bound and not the pool's. - const longHold = await holdAssignment() - try { - const startedAt = performance.now() - await expect(stores[1]!.assign(identity, 'us-central1')).rejects.toBeInstanceOf( - RelayAssignmentRowBusyError - ) - const waitedMs = performance.now() - startedAt - expect(waitedMs).toBeGreaterThanOrEqual(900) - expect(waitedMs).toBeLessThan(2_000) - } finally { - await longHold() - } - }, 30_000) it('never waits on the assignment row while its retry holds the pinned cell row', async () => { await resetFleet() const identity = hostIdentity(923) diff --git a/cloud/apps/relay/src/assignment/assignment-isolated-cell-replacement.test.ts b/cloud/apps/relay/src/assignment/assignment-isolated-cell-replacement.test.ts index 49bf26fde73..5c3fe055fa0 100644 --- a/cloud/apps/relay/src/assignment/assignment-isolated-cell-replacement.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-isolated-cell-replacement.test.ts @@ -1,7 +1,7 @@ import { createHash } from 'node:crypto' import { afterEach, describe, expect, it, vi } from 'vitest' -import { RelayAssignmentStore, RelayHomeCellUnavailableError } from './assignment-store.js' -import { ReservePaceError } from './reserve-placement/reserve-assignment.js' +import { RelayAssignmentStore } from './assignment-store.js' + import { encodeMembership, type CellAdmissionMembership, @@ -41,16 +41,10 @@ afterEach(async () => { for (const database of databases.splice(0)) await database.close() }) -// Counts the reads this change adds, so the general hot path can be held to a -// single admission lookup and no migration lookup at all. -class QueryCountingDatabase implements RelayDatabase { - readonly sql: string[] = [] +class WriteFailureDatabase implements RelayDatabase { // Fails the first statement containing this fragment, so a test can roll a // transaction back at a chosen point. failOnce: string | undefined - // Locked statements that report the row busy, in order: each fragment fires - // once, on the first locked statement containing it after the one before. - lockUnavailableSequence: string[] = [] constructor(private readonly delegate: RelayDatabase) {} @@ -58,12 +52,7 @@ class QueryCountingDatabase implements RelayDatabase { return this.delegate.dialect } - count(fragment: string): number { - return this.sql.filter((statement) => statement.includes(fragment)).length - } - record(sql: string): void { - this.sql.push(sql) if (this.failOnce !== undefined && sql.includes(this.failOnce)) { this.failOnce = undefined throw new Error('injected_placement_write_failure') @@ -80,17 +69,8 @@ class QueryCountingDatabase implements RelayDatabase { params?: unknown[], options?: RelayLockOptions ): Promise { - this.recordLocked(sql) - return await this.delegate.queryLocked(sql, params, options) - } - - recordLocked(sql: string): void { this.record(sql) - const next = this.lockUnavailableSequence[0] - if (next !== undefined && sql.includes(next)) { - this.lockUnavailableSequence.shift() - throw new Error('database_lock_unavailable') - } + return await this.delegate.queryLocked(sql, params, options) } async transaction( @@ -107,8 +87,7 @@ class QueryCountingDatabase implements RelayDatabase { await this.delegate.close() } - // A nested transaction shares this one's tape, so a whole assign() is - // measured as a unit. + // Inject the failure inside the transaction so the real database rolls it back. private recording(inner: RelayDatabase): RelayDatabase { return { dialect: inner.dialect, @@ -117,7 +96,7 @@ class QueryCountingDatabase implements RelayDatabase { return await inner.query(sql, params) }, queryLocked: async (sql, params, options) => { - this.recordLocked(sql) + this.record(sql) return await inner.queryLocked(sql, params, options) }, transaction: async (operation, options) => await inner.transaction(operation, options), @@ -129,7 +108,7 @@ class QueryCountingDatabase implements RelayDatabase { interface Harness { store: RelayAssignmentStore database: RelayDatabase - counter: QueryCountingDatabase + counter: WriteFailureDatabase heartbeat: (cell: RelayCellConfig, at?: number) => Promise setNow: (value: number) => void /** The real isolate path: one selector apply that names the cell it stamps. */ @@ -144,7 +123,7 @@ interface Harness { async function setup(cells: RelayCellConfig[] = CELLS): Promise { const inner = await openInMemoryRelayDatabase() databases.push(inner) - const counter = new QueryCountingDatabase(inner) + const counter = new WriteFailureDatabase(inner) let now = START_MS const store = new RelayAssignmentStore(counter, () => now, { requireLiveCells: true, @@ -233,43 +212,6 @@ async function setup(cells: RelayCellConfig[] = CELLS): Promise { } } -async function insertMigration( - database: RelayDatabase, - input: { - sourceCellId: string - targetCellId: string - assignmentEpoch: number - leases: number - settled?: 'completed' | 'aborted' - } -): Promise { - await database.query( - `INSERT INTO relay_assignment_migrations - (user_id, relay_host_id, source_cell_id, target_cell_id, previous_epoch, - assignment_epoch, source_request_units, target_reserved_units, expires_at, - target_registered_at, completed_at, aborted_at, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, 1, 1, ?, NULL, ?, ?, ?, ?)`, - [ - IDENTITY.userId, - IDENTITY.relayHostId, - input.sourceCellId, - input.targetCellId, - input.assignmentEpoch - 1, - input.assignmentEpoch, - START_MS + 900_000, - input.settled === 'completed' ? START_MS : null, - input.settled === 'aborted' ? START_MS : null, - START_MS, - START_MS - ] - ) - await database.query( - `UPDATE relay_assignments SET migration_leases = ? - WHERE user_id = ? AND relay_host_id = ?`, - [input.leases, IDENTITY.userId, IDENTITY.relayHostId] - ) -} - type ConsoleWarnSpy = { mock: { calls: unknown[][] } } function jsonEvents(warn: ConsoleWarnSpy, event: string): unknown[] { @@ -280,381 +222,6 @@ function jsonEvents(warn: ConsoleWarnSpy, event: string): unknown[] { } describe('re-placing a host off a cell isolated for a roll', () => { - it('leaves a host on a live general cell untouched, at one added admission read', async () => { - const { store, counter } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - - counter.sql.length = 0 - const second = await store.assign(IDENTITY, 'us-central1') - - // Identical, not merely same-celled: the clock has not moved, so every - // field including the lease deadline must match; only the first was placed. - expect(second).toEqual({ ...first, placed: undefined }) - // One row read answers both the stranded rule and the roll-stamp check. - expect(counter.count('relay_cell_admission')).toBe(1) - expect(counter.count('relay_assignment_migrations')).toBe(0) - // No placement: the sticky lane never reaches the fleet-wide inventory. - expect(counter.count('ORDER BY cell_id ASC')).toBe(0) - }) - - it('keeps a host pinned to a migration-only cell with no roll stamp', async () => { - // Unstamped non-roll parking must retain hosts or undo evacuation/Asia rollback/operator intent. - const { store, park, rollIsolatedAt } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - await park(first.cellId, 'migration-only') - - expect(await rollIsolatedAt(first.cellId)).toBeNull() - const pinned = await store.assign(IDENTITY, 'us-central1') - expect(pinned).toMatchObject({ cellId: first.cellId, assignmentEpoch: first.assignmentEpoch }) - expect(pinned.placed).toBeUndefined() - }) - - it('re-places a host once the roll stamp is set', async () => { - const { store, counter, isolateForRoll, rollIsolatedAt } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - await isolateForRoll(first.cellId) - - expect(await rollIsolatedAt(first.cellId)).toBe(START_MS) - counter.sql.length = 0 - const moved = await store.assign(IDENTITY, 'us-central1') - - expect(moved.cellId).not.toBe(first.cellId) - expect(moved.assignmentEpoch).toBe(first.assignmentEpoch + 1) - expect(moved.placed).toBe(true) - expect(counter.count('relay_assignment_migrations')).toBeGreaterThan(0) - - // Durable: the next dial does not bounce back to the isolated cell. - const kept = await store.assign(IDENTITY, 'us-central1') - expect(kept).toMatchObject({ cellId: moved.cellId, assignmentEpoch: moved.assignmentEpoch }) - expect(kept.placed).toBeUndefined() - }) - - it.each([ - { label: 'just inside the bound', age: 2 * 60 * 60_000 - 1, moves: true }, - { label: 'just outside the bound', age: 2 * 60 * 60_000 + 1, moves: false } - ])('treats a stamp $label as $moves', async ({ age, moves }) => { - // Past a normal ~15-minute roll, stamps may be failed-wave or old-restore orphans; keep possibly healthy hosts pinned for operator recovery. - const { store, heartbeat, isolateForRoll, setNow } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - await isolateForRoll(first.cellId) - - const later = START_MS + age - setNow(later) - for (const cell of CELLS) await heartbeat(cell, later) - const grant = await store.assign(IDENTITY, 'us-central1') - - if (moves) { - expect(grant.cellId).not.toBe(first.cellId) - expect(grant.assignmentEpoch).toBe(first.assignmentEpoch + 1) - } else { - expect(grant.cellId).toBe(first.cellId) - expect(grant.assignmentEpoch).toBe(first.assignmentEpoch) - } - }) - - it('stops re-placing once restore clears the stamp', async () => { - const { store, isolateForRoll, restore, rollIsolatedAt } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - await isolateForRoll(first.cellId) - await restore(first.cellId) - - expect(await rollIsolatedAt(first.cellId)).toBeNull() - expect(await store.assign(IDENTITY, 'us-central1')).toMatchObject({ - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch - }) - }) - - it('keeps a host pinned to an existing-only cell that still serves it', async () => { - // Why: existing-only cells serve the hosts they already hold (PR #194). Only - // assignmentStrandedOnUnservedCell may release that pin, and only on proof - // the cell stopped serving this host. - const { store, database, heartbeat, park, setNow } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - await park(first.cellId, 'existing-only') - await database.query( - `INSERT INTO relay_assignment_activity_leases - (user_id, relay_host_id, activity_id, activity_kind, cell_id, - request_units, expires_at, updated_at) - VALUES (?, ?, 'control:live-1', 'control', ?, 1, ?, ?)`, - [IDENTITY.userId, IDENTITY.relayHostId, first.cellId, START_MS + 600_000, START_MS] - ) - - // Past the stranded rule's minimum grant age, which outlives the heartbeat TTL. - setNow(START_MS + 61_000) - for (const cell of CELLS) await heartbeat(cell, START_MS + 61_000) - expect(await store.assign(IDENTITY, 'us-central1')).toMatchObject({ - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch - }) - }) - - it('keeps a host pinned on an unstamped cell whose migration has completed', async () => { - // Completed evacuations await separate promotion in migration-only; re-placement would undo them. - const { store, database, park } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - await insertMigration(database, { - sourceCellId: 'us-c2', - targetCellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - leases: 0, - settled: 'completed' - }) - await park(first.cellId, 'migration-only') - - expect(await store.assign(IDENTITY, 'us-central1')).toMatchObject({ - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch - }) - }) - - it('re-places a stamped cell whose migration has completed', async () => { - const { store, database, isolateForRoll } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - await insertMigration(database, { - sourceCellId: 'us-c2', - targetCellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - leases: 0, - settled: 'completed' - }) - await isolateForRoll(first.cellId) - - expect((await store.assign(IDENTITY, 'us-central1')).cellId).not.toBe(first.cellId) - }) - - it('keeps the pin while a migration lease is outstanding', async () => { - const { store, database, isolateForRoll } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - await insertMigration(database, { - sourceCellId: first.cellId, - targetCellId: 'us-c2', - assignmentEpoch: first.assignmentEpoch, - leases: 1 - }) - await isolateForRoll(first.cellId) - - expect(await store.assign(IDENTITY, 'us-central1')).toMatchObject({ - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch - }) - }) - - it('keeps the pin while a migration row is open but its lease has lapsed', async () => { - // Migration rows outlive their 15-minute counters and cannot roll back from non-general sources; re-placement would strand them. - const { store, database, isolateForRoll } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - await insertMigration(database, { - sourceCellId: first.cellId, - targetCellId: 'us-c2', - assignmentEpoch: first.assignmentEpoch, - leases: 0 - }) - await isolateForRoll(first.cellId) - - expect(await store.assign(IDENTITY, 'us-central1')).toMatchObject({ - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch - }) - }) - - it('crosses a region boundary only when its own region has no room', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { store, isolateForRoll, park } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - const other = CELLS.find((cell) => cell.region === 'us-central1' && cell.id !== first.cellId)! - await park(other.id, 'migration-only') - await isolateForRoll(first.cellId) - - warn.mockClear() - expect(await store.assign(IDENTITY, 'us-central1')).toMatchObject({ - cellId: 'asia-c1', - assignmentEpoch: first.assignmentEpoch + 1 - }) - expect(jsonEvents(warn, 'orca_relay_sticky_replaced_off_isolated_cell')).toEqual([ - { - event: 'orca_relay_sticky_replaced_off_isolated_cell', - fromCellId: first.cellId, - fromRegion: 'us-central1', - admissionState: 'migration-only', - toCellId: 'asia-c1', - region: 'asia-east2' - } - ]) - }) - - it('keeps the pin, and says so, when no region has a general cell with room', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { store, isolateForRoll, park } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - for (const cell of CELLS) { - if (cell.id !== first.cellId) await park(cell.id, 'migration-only') - } - await isolateForRoll(first.cellId) - - warn.mockClear() - expect(await store.assign(IDENTITY, 'us-central1')).toMatchObject({ - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch - }) - expect(jsonEvents(warn, 'orca_relay_sticky_replacement_deferred')).toEqual([ - { - event: 'orca_relay_sticky_replacement_deferred', - reason: 'no_same_region_headroom', - cellId: first.cellId, - region: 'us-central1' - } - ]) - expect(jsonEvents(warn, 'orca_relay_sticky_replaced_off_isolated_cell')).toEqual([]) - }) - - it('prefers its own region over a less loaded cell elsewhere', async () => { - const { store, isolateForRoll } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - await isolateForRoll(first.cellId) - const moved = await store.assign(IDENTITY, 'us-central1') - expect(moved.region).toBe('us-central1') - expect(moved.cellId).not.toBe(first.cellId) - }) - - it('moves the only cell of a region to another region', async () => { - const { store, isolateForRoll } = await setup() - const first = await store.assign(IDENTITY, 'asia-east2') - expect(first.region).toBe('asia-east2') - await isolateForRoll(first.cellId) - - // asia-c1 is the only Asia cell, so the only in-region candidate is gone. - const moved = await store.assign(IDENTITY, 'asia-east2') - expect(moved.region).toBe('us-central1') - expect(moved.assignmentEpoch).toBe(first.assignmentEpoch + 1) - }) - - describe('with a reserve cell in its own region', () => { - const onReserve = { - ...IDENTITY, - cellId: 'asia-reserve', - cellUrl: 'https://asia-reserve.example.com', - assignmentEpoch: 9, - leaseExpiresAt: START_MS + 1_000_000, - region: 'asia-east2' as const - } - - it('leaves the region as before when the reserve cell has no room either', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { store, isolateForRoll } = await setup() - const first = await store.assign(IDENTITY, 'asia-east2') - await isolateForRoll(first.cellId) - warn.mockClear() - const regionReserve = vi.fn(async () => null) - const moved = await store.assign(IDENTITY, 'asia-east2', 'asia-east2', undefined, { - regionReserve - }) - expect(moved).toMatchObject({ - region: 'us-central1', - assignmentEpoch: first.assignmentEpoch + 1 - }) - expect(regionReserve).toHaveBeenCalledOnce() - expect(jsonEvents(warn, 'orca_relay_sticky_replaced_off_isolated_cell')).toMatchObject([ - { fromCellId: first.cellId, region: 'us-central1' } - ]) - }) - - it('treats a throttled reserve cell as no room, so the drain does not wait on its intake', async () => { - const { store, isolateForRoll } = await setup() - const first = await store.assign(IDENTITY, 'asia-east2') - await isolateForRoll(first.cellId) - const regionReserve = vi.fn(async () => { - throw new ReservePaceError(4) - }) - await expect( - store.assign(IDENTITY, 'asia-east2', 'asia-east2', undefined, { regionReserve }) - ).resolves.toMatchObject({ - region: 'us-central1', - assignmentEpoch: first.assignmentEpoch + 1 - }) - expect(regionReserve).toHaveBeenCalledOnce() - }) - - describe('when no database cell has room anywhere', () => { - const onUsReserve = { ...onReserve, cellId: 'us-reserve', region: 'us-central1' as const } - const isolateWithNoDatabaseRoom = async () => { - const harness = await setup() - const first = await harness.store.assign(IDENTITY, 'asia-east2') - await harness.isolateForRoll(first.cellId) - for (const cell of CELLS.filter((entry) => entry.region === 'us-central1')) { - await harness.park(cell.id, 'migration-only') - } - return { ...harness, first } - } - - // Today's rule: a live isolated cell keeps a host no other cell can take. - it('keeps the pin and never asks the spill', async () => { - const { store, first } = await isolateWithNoDatabaseRoom() - const reserveSpill = vi.fn(async () => onUsReserve) - const kept = await store.assign(IDENTITY, 'asia-east2', 'asia-east2', undefined, { - reserveSpill - }) - expect(kept).toMatchObject({ cellId: first.cellId, assignmentEpoch: first.assignmentEpoch }) - expect(reserveSpill).not.toHaveBeenCalled() - }) - }) - - it('does not hold a host whose preferred region is elsewhere', async () => { - const { store, isolateForRoll, park } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - const other = CELLS.find((cell) => cell.region === 'us-central1' && cell.id !== first.cellId)! - await park(other.id, 'migration-only') - await isolateForRoll(first.cellId) - const regionReserve = vi.fn(async () => onReserve) - await expect( - store.assign(IDENTITY, 'asia-east2', 'asia-east2', undefined, { regionReserve }) - ).resolves.toMatchObject({ cellId: 'asia-c1' }) - expect(regionReserve).not.toHaveBeenCalled() - }) - }) - - it('takes the dead-cell path when a stamped cell stops heartbeating', async () => { - // Why: the fence is the only proof that a cell we cannot reach has stopped - // serving the sockets it still holds. A stamp does not make it reachable. - const { store, heartbeat, isolateForRoll, setNow } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - await isolateForRoll(first.cellId) - - const stale = START_MS + HEARTBEAT_TTL_MS + 1_000 - setNow(stale) - for (const cell of CELLS) { - if (cell.id !== first.cellId) await heartbeat(cell, stale) - } - - await expect(store.assign(IDENTITY, 'us-central1')).rejects.toBeInstanceOf( - RelayHomeCellUnavailableError - ) - }) - - it('leaves the source cell activity leases in place', async () => { - // Contrast with the fence and stranded paths, which delete them: an isolated - // cell is alive and still owns drainable work behind those leases. - const { store, database, isolateForRoll } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - await database.query( - `INSERT INTO relay_assignment_activity_leases - (user_id, relay_host_id, activity_id, activity_kind, cell_id, - request_units, expires_at, updated_at) - VALUES (?, ?, 'splice:keep-1', 'splice', ?, 1, ?, ?)`, - [IDENTITY.userId, IDENTITY.relayHostId, first.cellId, START_MS + 600_000, START_MS] - ) - await isolateForRoll(first.cellId) - - await store.assign(IDENTITY, 'us-central1') - expect( - await database.query( - `SELECT activity_id FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ? AND activity_id = 'splice:keep-1'`, - [IDENTITY.userId, IDENTITY.relayHostId] - ) - ).toHaveLength(1) - }) - it('emits nothing when the placement rolls back after the decision', async () => { // Log only committed moves; stdout cannot roll back with a failed lease/reservation transaction. const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) @@ -682,169 +249,4 @@ describe('re-placing a host off a cell isolated for a roll', () => { expect(moved.cellId).not.toBe(first.cellId) expect(jsonEvents(warn, 'orca_relay_sticky_replaced_off_isolated_cell')).toHaveLength(1) }) - describe('a host whose leases span two cells after the move', () => { - const NEIGHBOUR = { userId: 'user-b', relayHostId: 'host000000000002' } - - async function reserved(database: RelayDatabase, cellId: string): Promise { - const rows = await database.query( - `SELECT reserved_requests FROM relay_cells WHERE cell_id = ?`, - [cellId] - ) - return Number(rows[0]!['reserved_requests']) - } - - async function expectAccounting(database: RelayDatabase): Promise { - for (const cell of CELLS) { - const leased = await database.query( - `SELECT COALESCE(SUM(request_units), 0) AS units - FROM relay_assignment_activity_leases WHERE cell_id = ?`, - [cell.id] - ) - expect({ cell: cell.id, reserved: await reserved(database, cell.id) }).toEqual({ - cell: cell.id, - reserved: Number(leased[0]!['units']) - }) - } - } - - async function counters(database: RelayDatabase): Promise { - const rows = await database.query( - `SELECT reserved_controls, reserved_splices FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [IDENTITY.userId, IDENTITY.relayHostId] - ) - return [Number(rows[0]!['reserved_controls']), Number(rows[0]!['reserved_splices'])] - } - - // us-c1 is isolated with the host's control and splice on it; the host - // moves to us-c2, where a neighbour's splice outlives every other lease. - async function movedHost(): Promise { - const harness = await setup() - const { store, isolateForRoll } = harness - const first = await store.assign(IDENTITY, 'us-central1') - expect(first.cellId).toBe('us-c1') - await store.activateControl(IDENTITY, { - cellId: 'us-c1', - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.acquireActivity(IDENTITY, { - activityId: 'splice:keep-1', - kind: 'splice', - cellId: 'us-c1' - }) - await isolateForRoll('us-c1') - expect((await store.assign(NEIGHBOUR, 'us-central1')).cellId).toBe('us-c2') - await store.acquireActivity(NEIGHBOUR, { - activityId: 'splice:neighbour', - kind: 'splice', - cellId: 'us-c2', - expiresAt: START_MS + 10 * 60 * 60_000 - }) - expect((await store.assign(IDENTITY, 'us-central1')).cellId).toBe('us-c2') - expect(await counters(harness.database)).toEqual([2, 1]) - await expectAccounting(harness.database) - return harness - } - - it('is left to the lease sweep by aggregate expiry', async () => { - const { store, database, setNow } = await movedHost() - setNow(START_MS + 60 * 60_000) - await store.releaseExpiredActivity() - expect(await counters(database)).toEqual([2, 1]) - await expectAccounting(database) - await store.releaseExpiredActivityLeases() - await store.releaseExpiredActivity() - expect(await counters(database)).toEqual([0, 0]) - expect(await reserved(database, 'us-c1')).toBe(0) - expect(await reserved(database, 'us-c2')).toBe(2) - await expectAccounting(database) - }) - - it('frees the source leases on their own cell when the target dies', async () => { - const { store, database, setNow, heartbeat, restore } = await movedHost() - await restore('us-c1') - // Uncapped, so the dead-cell path needs no fence to move off it. - await database.query(`DELETE FROM relay_cell_connection_limits WHERE cell_id = 'us-c2'`) - setNow(START_MS + HEARTBEAT_TTL_MS + 5_000) - await heartbeat(CELLS[0]!) - await heartbeat(CELLS[2]!) - - expect((await store.assign(IDENTITY, 'us-central1')).cellId).toBe('us-c1') - expect(await counters(database)).toEqual([1, 0]) - expect(await store.releaseActivity(IDENTITY, 'control:us-c1:1')).toBe(false) - expect(await reserved(database, 'us-c1')).toBe(1) - expect(await reserved(database, 'us-c2')).toBe(3) - await expectAccounting(database) - }) - }) - it('retries a busy isolated attempt in its own tier, never under the all-rows lock', async () => { - const { store, counter, isolateForRoll } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - await isolateForRoll(first.cellId) - counter.sql.length = 0 - // The first attempt finds a target row busy, then its retry finds the host's - // lease rows busy after it has already taken the tier's rows. - counter.lockUnavailableSequence = [ - 'SELECT * FROM relay_cells WHERE cell_id IN (', - 'FROM relay_assignment_activity_leases' - ] - - const moved = await store.assign(IDENTITY, 'us-central1') - expect(counter.lockUnavailableSequence).toEqual([]) - expect(moved).toMatchObject({ - region: 'us-central1', - assignmentEpoch: first.assignmentEpoch + 1 - }) - expect(counter.count('SELECT * FROM relay_cells ORDER BY cell_id ASC')).toBe(0) - }) -}) - -describe('classifying a reconnect whose home is isolated for a roll', () => { - const classify = { classifyHomeRollIsolation: true } - - it('reads the classification in the verification query itself', async () => { - const { store, counter, isolateForRoll } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - await isolateForRoll(first.cellId) - - counter.sql.length = 0 - await store.resolve(IDENTITY, classify) - - expect(counter.sql.filter((sql) => sql.includes('FROM relay_assignments'))).toHaveLength(1) - expect(counter.count('relay_cell_admission')).toBe(1) - }) - - it('still treats a host its draining cell already released as a drain return', async () => { - // A drain releases the host's control lease before it tells the host, so the redial - // finds no activity: the stamp, not a live lease, has to carry the classification. - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const { store, database, isolateForRoll } = await setup() - const first = await store.assign(IDENTITY, 'us-central1') - await store.activateControl(IDENTITY, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await isolateForRoll(first.cellId) - expect(await store.releaseActivity(IDENTITY, `control:${first.cellId}:1`)).toBe(true) - expect( - await database.query( - `SELECT activity_id FROM relay_assignment_activity_leases WHERE user_id = ?`, - [IDENTITY.userId] - ) - ).toEqual([]) - - expect(await store.resolve(IDENTITY, classify)).toMatchObject({ - cellId: first.cellId, - homeCellRollIsolated: true - }) - warn.mockClear() - const moved = await store.assign(IDENTITY, 'us-central1') - expect(moved.cellId).not.toBe(first.cellId) - expect(moved.assignmentEpoch).toBe(first.assignmentEpoch + 1) - expect(jsonEvents(warn, 'orca_relay_sticky_replaced_off_isolated_cell')).toMatchObject([ - { fromCellId: first.cellId, toCellId: moved.cellId } - ]) - }) }) diff --git a/cloud/apps/relay/src/assignment/assignment-store.test.ts b/cloud/apps/relay/src/assignment/assignment-store.test.ts index fab6a34fd95..e45e81ca20b 100644 --- a/cloud/apps/relay/src/assignment/assignment-store.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-store.test.ts @@ -2,12 +2,11 @@ import { ASSIGNMENT_LIMITS } from '@orca-cloud/relay-contract/assignment-invaria import { createHash } from 'node:crypto' import { afterEach, describe, expect, it, vi } from 'vitest' import type { RelayCellConfig } from '../config.js' +import { RelayAssignmentStore } from './assignment-store.js' import { - RelayAssignmentRowBusyError, - RelayAssignmentStore, - STRANDED_MIGRATION_ABANDON_MS -} from './assignment-store.js' -import { encodeMembership, type CellAdmissionMembership } from '../cell/admission/cell-admission-selector.js' + encodeMembership, + type CellAdmissionMembership +} from '../cell/admission/cell-admission-selector.js' import { openInMemoryRelayDatabase, type RelayDatabase, @@ -20,35 +19,6 @@ const CELLS: RelayCellConfig[] = [ { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 2 }, { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 2 } ] -const NO_EXPIRED_EVACUATION_DIAGNOSTICS = { - expiredUnregistered: 0, - repairableExpiredUnregistered: 0, - abortableExpiredUnregistered: 0, - blockedExpiredUnregistered: 0, - blockedExpiredOnNewerTargetAssignment: 0 -} -const NO_REGISTERED_EVACUATION_DIAGNOSTICS = { - registeredSourceActive: 0, - registeredCompletable: 0, - registeredTargetInactive: 0 -} -const NO_ACTIVE_MIGRATION_LEASE = { - oldestExpiresAt: null, - oldestRemainingMs: null -} -const FENCE_PLAN_BINDING = { - planObjectName: - 'terraform/state/relay-fence-plans/production/22222222-2222-4222-8222-222222222222.tfplan', - planObjectGeneration: '123456789', - varFileSha256: 'c'.repeat(64), - terraformStateLineage: '33333333-3333-4333-8333-333333333333', - terraformStateSerial: 7, - terraformStateObjectGeneration: '987654321', - terraformStateObjectSha256: 'd'.repeat(64), - requestReason: 'orca-relay-fence/22222222-2222-4222-8222-222222222222' -} -const FENCE_INVOCATION_ID = '55555555-5555-4555-8555-555555555555' -const FENCE_INVOCATION_REASON = `${FENCE_PLAN_BINDING.requestReason}/${FENCE_INVOCATION_ID}` async function applyGenerationZeroSelector( store: RelayAssignmentStore, @@ -65,85 +35,6 @@ async function applyGenerationZeroSelector( }) } -function cellFenceEvidence(attemptId = '22222222-2222-4222-8222-222222222222') { - return { - attemptId, - environment: 'production' as const, - cellId: 'cell-a', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - migName: 'orca-relay-c1', - instanceGroup: 'https://compute.example/instanceGroups/orca-relay-c1', - generationIdentity: 'https://compute.example/instanceTemplates/orca-relay-c1-abc', - fenceCommit: 'a'.repeat(40), - planSha256: 'b'.repeat(64), - ...FENCE_PLAN_BINDING - } -} - -class RepeatedDrainAccountingFailureDatabase implements RelayDatabase { - refreshAttempts = 0 - private armed = false - private failuresRemaining = 0 - - constructor(private readonly delegate: RelayDatabase) {} - - arm(failures: number): void { - this.armed = true - this.failuresRemaining = failures - this.refreshAttempts = 0 - } - - async query(sql: string, params: unknown[] = []): Promise { - return await this.delegate.query(sql, params) - } - - async queryLocked( - sql: string, - params: unknown[] = [], - options: RelayLockOptions = {} - ): Promise { - return await this.lockedQuery(this.delegate, sql, params, options) - } - - async transaction(operation: (transaction: RelayDatabase) => Promise): Promise { - return await this.delegate.transaction( - async (transaction) => - await operation({ - dialect: transaction.dialect, - query: async (sql, params = []) => await transaction.query(sql, params), - queryLocked: async (sql, params = [], options = {}) => - await this.lockedQuery(transaction, sql, params, options), - transaction: async (nested) => await transaction.transaction(nested), - close: async () => {} - }) - ) - } - - async close(): Promise { - await this.delegate.close() - } - - private async lockedQuery( - database: RelayDatabase, - sql: string, - params: unknown[], - options: RelayLockOptions - ): Promise { - const drainRefresh = - sql.includes('SELECT migration.*') && - sql.includes('WHERE migration.source_cell_id = ?') && - !sql.includes('source_cell_incarnation') - if (this.armed && drainRefresh) { - this.refreshAttempts++ - if (this.failuresRemaining > 0) { - this.failuresRemaining-- - throw new Error('migration_activity_accounting_mismatch') - } - } - return await database.queryLocked(sql, params, options) - } -} - // Runs a side effect between the sticky lane and the placement lane, the window // in which a host can acquire control after the sticky read called it dormant. class SeedBetweenAssignmentLanesDatabase implements RelayDatabase { @@ -240,1149 +131,6 @@ describe('RelayAssignmentStore', () => { }) } - it('admits only cells with a fresh ready heartbeat', async () => { - let now = 100 - const store = await setupWithHeartbeats(() => now, [CELLS[0]!]) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - - await expect(store.assign(identity)).rejects.toThrow('relay_capacity_exhausted') - await heartbeat(store, CELLS[0]!, { ready: false }) - await expect(store.assign(identity)).rejects.toThrow('relay_capacity_exhausted') - await heartbeat(store) - expect((await store.assign(identity)).cellId).toBe('cell-a') - now += 45_001 - expect(await store.resolve(identity)).toBeNull() - }) - - it('fences stale incarnations and origin mismatches', async () => { - const store = await setupWithHeartbeats(() => 100, [CELLS[0]!]) - await heartbeat(store, CELLS[0]!, { startedAt: 50 }) - await expect( - heartbeat(store, { ...CELLS[0]!, url: 'https://other.example.com' }) - ).rejects.toThrow('cell_origin_mismatch') - await expect( - heartbeat(store, CELLS[0]!, { - incarnation: '22222222-2222-4222-8222-222222222222', - startedAt: 50 - }) - ).rejects.toThrow('stale_cell_incarnation') - await heartbeat(store, CELLS[0]!, { - incarnation: '22222222-2222-4222-8222-222222222222', - startedAt: 51 - }) - await expect(heartbeat(store, CELLS[0]!, { startedAt: 50 })).rejects.toThrow( - 'stale_cell_incarnation' - ) - }) - - it('records receipt-relative legacy drain states and pins post-send migrations', async () => { - let now = 100 - const store = await setupWithHeartbeats(() => now) - await heartbeat(store, CELLS[0]!) - await heartbeat(store, CELLS[1]!, { - incarnation: '22222222-2222-4222-8222-222222222222' - }) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await store.assign(identity) - await store.setCellEnabled('cell-a', false) - const migration = await store.startEvacuation(identity, 'cell-b') - await database!.query( - `UPDATE relay_assignments SET migration_leases = migration_leases + 1 - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - const incarnation = '11111111-1111-4111-8111-111111111111' - const attemptId = '33333333-3333-4333-8333-333333333333' - const traceValue = '44444444-4444-4444-8444-444444444444' - - await expect( - store.prepareCellDrainAttempt({ - attemptId, - cellId: 'cell-a', - cellIncarnation: incarnation, - traceValue, - plannedGraceMs: 120_000 - }) - ).resolves.toMatchObject({ state: 'prepared', shouldSend: false }) - expect(await database!.query(`SELECT * FROM relay_post_drain_migration_pins`)).toEqual([]) - await expect( - store.prepareCellDrainRecovery({ - attemptId, - cellId: 'cell-a', - cellIncarnation: incarnation - }) - ).resolves.toMatchObject({ - shouldSend: false, - preparedAttempt: { - attemptId, - state: 'prepared', - traceValue, - plannedGraceMs: 120_000 - } - }) - - await expect( - store.beginCellDrainSend({ - attemptId, - cellId: 'cell-a', - cellIncarnation: incarnation - }) - ).resolves.toMatchObject({ - state: 'send-may-have-started', - shouldSend: true, - sendPermitExpiresAt: 30_100 - }) - await expect( - database!.query( - `SELECT migration_leases FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).resolves.toEqual([{ migration_leases: 1 }]) - await expect( - store.beginCellDrainSend({ - attemptId, - cellId: 'cell-a', - cellIncarnation: incarnation - }) - ).resolves.toMatchObject({ - state: 'send-may-have-started', - shouldSend: false - }) - await expect( - store.prepareCellDrainRecovery({ - attemptId, - cellId: 'cell-a', - cellIncarnation: incarnation - }) - ).rejects.toThrow('drain_application_receipt_missing') - expect( - await database!.query( - `SELECT drain_attempt_id, source_cell_id, source_cell_incarnation, - target_cell_id, assignment_epoch - FROM relay_post_drain_migration_pins` - ) - ).toEqual([ - { - drain_attempt_id: attemptId, - source_cell_id: 'cell-a', - source_cell_incarnation: incarnation, - target_cell_id: 'cell-b', - assignment_epoch: migration.assignmentEpoch - } - ]) - - now = migration.expiresAt + 1 - expect(await store.abortExpiredEvacuations()).toBe(0) - expect(await store.releaseExpiredActivityLeases()).toBe(1) - expect( - await database!.query( - `SELECT activity_kind, cell_id FROM relay_assignment_activity_leases - WHERE user_id = ? ORDER BY activity_kind`, - [identity.userId] - ) - ).toEqual([ - { activity_kind: 'control', cell_id: 'cell-b' }, - { activity_kind: 'migration', cell_id: 'cell-b' } - ]) - - now = 200_000 - await expect( - store.recordCellDrainApplicationReceipt({ - attemptId, - cellId: 'cell-a', - cellIncarnation: incarnation, - traceValue, - backendStatus: 200 - }) - ).resolves.toMatchObject({ - state: 'application-receipt', - applicationReceiptAt: 200_000, - retryAfter: 350_000 - }) - await expect( - store.prepareCellDrainRecovery({ attemptId, cellId: 'cell-a', cellIncarnation: incarnation }) - ).rejects.toThrow('drain_recovery_too_early') - now = 350_000 - await expect( - store.prepareCellDrainRecovery({ attemptId, cellId: 'cell-a', cellIncarnation: incarnation }) - ).resolves.toEqual({ - shouldSend: true, - retryAfter: 350_000 - }) - await expect( - store.prepareCellDrainRecovery({ attemptId, cellId: 'cell-a', cellIncarnation: incarnation }) - ).resolves.toEqual({ - shouldSend: false, - retryAfter: 350_000 - }) - }) - - it('recovers a proven drain once after the source cell is replaced', async () => { - let now = 100 - const store = await setupWithHeartbeats(() => now) - const oldIncarnation = '11111111-1111-4111-8111-111111111111' - const newIncarnation = '22222222-2222-4222-8222-222222222222' - const newerIncarnation = '55555555-5555-4555-8555-555555555555' - const attempt = { - attemptId: '33333333-3333-4333-8333-333333333333', - cellId: 'cell-a', - cellIncarnation: oldIncarnation, - traceValue: '44444444-4444-4444-8444-444444444444', - plannedGraceMs: 120_000 - } - await heartbeat(store) - await store.setCellEnabled('cell-a', false) - await store.prepareCellDrainAttempt(attempt) - await store.beginCellDrainSend(attempt) - now = 200 - await store.recordCellDrainApplicationReceipt({ - ...attempt, - backendStatus: 200 - }) - - now = 150_200 - await heartbeat(store, CELLS[0]!, { - incarnation: newIncarnation, - startedAt: 51 - }) - await expect( - store.prepareCellDrainRecovery({ - cellId: 'cell-a', - cellIncarnation: newIncarnation - }) - ).resolves.toEqual({ shouldSend: true, retryAfter: 150_200 }) - await expect( - store.prepareCellDrainRecovery({ - cellId: 'cell-a', - cellIncarnation: newIncarnation - }) - ).resolves.toEqual({ shouldSend: false, retryAfter: 150_200 }) - - now = 150_300 - await heartbeat(store, CELLS[0]!, { - incarnation: newerIncarnation, - startedAt: 52 - }) - const concurrentRecoveries = await Promise.all([ - store.prepareCellDrainRecovery({ - cellId: 'cell-a', - cellIncarnation: newerIncarnation - }), - store.prepareCellDrainRecovery({ - cellId: 'cell-a', - cellIncarnation: newerIncarnation - }) - ]) - expect(concurrentRecoveries.map((recovery) => recovery.shouldSend).sort()).toEqual([ - false, - true - ]) - await expect( - store.prepareCellDrainRecovery({ - cellId: 'cell-a', - cellIncarnation: newerIncarnation - }) - ).resolves.toEqual({ shouldSend: false, retryAfter: 150_200 }) - await expect( - database!.query( - `SELECT cell_incarnation FROM relay_cell_drain_recovery_attempts - WHERE drain_attempt_id = ? ORDER BY cell_incarnation`, - [attempt.attemptId] - ) - ).resolves.toEqual([ - { cell_incarnation: newIncarnation }, - { cell_incarnation: newerIncarnation } - ]) - }) - - it('rejects an invalid receipt and a prepared drain from an old incarnation', async () => { - let now = 100 - const store = await setupWithHeartbeats(() => now) - const oldIncarnation = '11111111-1111-4111-8111-111111111111' - const newIncarnation = '22222222-2222-4222-8222-222222222222' - const attempt = { - attemptId: '33333333-3333-4333-8333-333333333333', - cellId: 'cell-a', - cellIncarnation: oldIncarnation, - traceValue: '44444444-4444-4444-8444-444444444444', - plannedGraceMs: 120_000 - } - await heartbeat(store) - await store.setCellEnabled('cell-a', false) - await store.prepareCellDrainAttempt(attempt) - now = 150_200 - await heartbeat(store, CELLS[0]!, { - incarnation: newIncarnation, - startedAt: 51 - }) - await expect( - store.prepareCellDrainRecovery({ - cellId: 'cell-a', - cellIncarnation: newIncarnation - }) - ).rejects.toThrow('drain_application_receipt_missing') - - await database!.query( - `UPDATE relay_cell_drain_attempt_states - SET state = 'application-receipt', application_receipt_at = ?, - receipt_cell_incarnation = ?, retry_after = ? - WHERE attempt_id = ?`, - [200, oldIncarnation, 150_200, attempt.attemptId] - ) - await expect( - store.prepareCellDrainRecovery({ - cellId: 'cell-a', - cellIncarnation: newIncarnation - }) - ).rejects.toThrow('drain_application_receipt_missing') - }) - - it('restores an expired registered migration lease before a prepared drain send', async () => { - let now = 100 - const store = await setupWithHeartbeats(() => now) - await heartbeat(store, CELLS[0]!) - await heartbeat(store, CELLS[1]!, { - incarnation: '22222222-2222-4222-8222-222222222222' - }) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await store.assign(identity) - await store.setCellEnabled('cell-a', false) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - const attempt = { - attemptId: '55555555-5555-4555-8555-555555555555', - cellId: 'cell-a', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - traceValue: '66666666-6666-4666-8666-666666666666', - plannedGraceMs: 120_000 - } - await store.prepareCellDrainAttempt(attempt) - - now = migration.expiresAt + 1 - expect(await store.releaseExpiredActivityLeases()).toBeGreaterThan(0) - await heartbeat(store, CELLS[0]!) - await heartbeat(store, CELLS[1]!, { - incarnation: '22222222-2222-4222-8222-222222222222' - }) - await expect( - store.beginCellDrainSend({ - attemptId: attempt.attemptId, - cellId: attempt.cellId, - cellIncarnation: attempt.cellIncarnation - }) - ).resolves.toMatchObject({ - state: 'send-may-have-started', - shouldSend: true - }) - await expect( - database!.query( - `SELECT activity_id, activity_kind, cell_id, request_units, expires_at - FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).resolves.toContainEqual({ - activity_id: `migration:${migration.assignmentEpoch}`, - activity_kind: 'migration', - cell_id: 'cell-b', - request_units: 1, - expires_at: now + ASSIGNMENT_LIMITS.migrationLeaseMs - }) - }) - - it('refreshes registered migration leases before prepared drain recovery', async () => { - let now = 100 - const cappedCells = CELLS.map((cell) => ({ - ...cell, - connectionHardCap: 600 as const, - connectionUnobservedBound: 50 - })) - const store = await setupWithHeartbeats(() => now, cappedCells) - await heartbeat(store, cappedCells[0]!) - await heartbeat(store, cappedCells[1]!, { - incarnation: '22222222-2222-4222-8222-222222222222' - }) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await store.assign(identity) - await store.setCellEnabled('cell-a', false) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - const attempt = { - attemptId: '99999999-9999-4999-8999-999999999999', - cellId: 'cell-a', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - traceValue: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', - plannedGraceMs: 120_000 - } - await store.prepareCellDrainAttempt(attempt) - - now = migration.expiresAt - 500_000 - await heartbeat(store, cappedCells[0]!) - await heartbeat(store, cappedCells[1]!, { - incarnation: '22222222-2222-4222-8222-222222222222' - }) - await expect(store.prepareCellDrainRecovery(attempt)).resolves.toMatchObject({ - shouldSend: false, - preparedAttempt: { attemptId: attempt.attemptId } - }) - const refreshedExpiresAt = now + ASSIGNMENT_LIMITS.migrationLeaseMs - await expect( - database!.query( - `SELECT expires_at FROM relay_assignment_migrations - WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, - [identity.userId, identity.relayHostId, migration.assignmentEpoch] - ) - ).resolves.toEqual([{ expires_at: refreshedExpiresAt }]) - await expect( - database!.query( - `SELECT state, timeout_at FROM relay_control_connection_reservations - WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, - [identity.userId, identity.relayHostId, migration.assignmentEpoch] - ) - ).resolves.toEqual([{ state: 'reserved', timeout_at: refreshedExpiresAt }]) - }) - - it('bounds repeated accounting repair before prepared drain recovery', async () => { - const delegate = await openInMemoryRelayDatabase() - const retryDatabase = new RepeatedDrainAccountingFailureDatabase(delegate) - database = retryDatabase - const store = new RelayAssignmentStore(retryDatabase, () => 100, { - requireLiveCells: true, - heartbeatTtlMs: 45_000 - }) - await store.reconcileCells(CELLS) - await heartbeat(store, CELLS[0]!) - await heartbeat(store, CELLS[1]!, { - incarnation: '22222222-2222-4222-8222-222222222222' - }) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await store.assign(identity) - await store.setCellEnabled('cell-a', false) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - const attempt = { - attemptId: '99999999-9999-4999-8999-999999999999', - cellId: 'cell-a', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - traceValue: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', - plannedGraceMs: 120_000 - } - await store.prepareCellDrainAttempt(attempt) - retryDatabase.arm(2) - - await expect(store.prepareCellDrainRecovery(attempt)).resolves.toMatchObject({ - shouldSend: false, - preparedAttempt: { attemptId: attempt.attemptId } - }) - expect(retryDatabase.refreshAttempts).toBe(3) - - retryDatabase.arm(4) - await expect(store.prepareCellDrainRecovery(attempt)).rejects.toThrow( - 'migration_activity_accounting_mismatch' - ) - expect(retryDatabase.refreshAttempts).toBe(4) - }) - - it('retires a pinned migration superseded by a newer authoritative assignment', async () => { - let now = 100 - const cells = [ - ...CELLS, - { - id: 'cell-c', - url: 'https://relay-c.example.com', - capacityRequests: 2 - } - ] - const store = await setupWithHeartbeats(() => now, cells) - await heartbeat(store, cells[0]!) - await heartbeat(store, cells[1]!, { - incarnation: '22222222-2222-4222-8222-222222222222' - }) - await heartbeat(store, cells[2]!, { - incarnation: '33333333-3333-4333-8333-333333333333' - }) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await store.assign(identity) - await store.setCellEnabled('cell-a', false) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - const attempt = { - attemptId: '99999999-9999-4999-8999-999999999999', - cellId: 'cell-a', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - traceValue: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', - plannedGraceMs: 120_000 - } - await store.prepareCellDrainAttempt(attempt) - await store.beginCellDrainSend(attempt) - const receipt = await store.recordCellDrainApplicationReceipt({ - ...attempt, - backendStatus: 200 - }) - - await database!.query( - `DELETE FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - await database!.query( - `UPDATE relay_assignments SET reserved_controls = 0, reserved_splices = 0, - reserved_invites = 0, pending_installs = 0, pending_confirmations = 0, - migration_leases = 0, lease_expires_at = 0, last_activity_at = 0 - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - await database!.query(`UPDATE relay_cells SET reserved_requests = 0 WHERE cell_id IN (?, ?)`, [ - 'cell-a', - 'cell-b' - ]) - now = ASSIGNMENT_LIMITS.dormantTtlMs + 1 - await heartbeat(store, cells[2]!, { - incarnation: '33333333-3333-4333-8333-333333333333' - }) - const current = await store.rebalanceDormant(identity, 'cell-c') - await store.activateControl(identity, { - cellId: 'cell-c', - assignmentEpoch: current.assignmentEpoch, - generation: 1 - }) - - expect(receipt.retryAfter).toBeLessThanOrEqual(now) - await heartbeat(store, cells[0]!) - await expect(store.prepareCellDrainRecovery(attempt)).resolves.toMatchObject({ - shouldSend: true - }) - await expect( - database!.query( - `SELECT aborted_at FROM relay_assignment_migrations - WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, - [identity.userId, identity.relayHostId, migration.assignmentEpoch] - ) - ).resolves.toEqual([{ aborted_at: now }]) - await expect( - database!.query( - `SELECT cell_id, assignment_epoch FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).resolves.toEqual([{ cell_id: 'cell-c', assignment_epoch: current.assignmentEpoch }]) - await expect( - database!.query( - `SELECT activity_id, cell_id FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).resolves.toEqual([{ activity_id: 'control:cell-c:1', cell_id: 'cell-c' }]) - }) - - it('refuses to restore a missing migration lease without durable target registration', async () => { - let now = 100 - const store = await setupWithHeartbeats(() => now) - await heartbeat(store, CELLS[0]!) - await heartbeat(store, CELLS[1]!, { - incarnation: '22222222-2222-4222-8222-222222222222' - }) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await store.assign(identity) - await store.setCellEnabled('cell-a', false) - const migration = await store.startEvacuation(identity, 'cell-b') - const attempt = { - attemptId: '77777777-7777-4777-8777-777777777777', - cellId: 'cell-a', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - traceValue: '88888888-8888-4888-8888-888888888888', - plannedGraceMs: 120_000 - } - await store.prepareCellDrainAttempt(attempt) - - now = migration.expiresAt + 1 - expect(await store.releaseExpiredActivityLeases()).toBeGreaterThan(0) - await heartbeat(store, CELLS[0]!) - await heartbeat(store, CELLS[1]!, { - incarnation: '22222222-2222-4222-8222-222222222222' - }) - await expect( - store.beginCellDrainSend({ - attemptId: attempt.attemptId, - cellId: attempt.cellId, - cellIncarnation: attempt.cellIncarnation - }) - ).rejects.toThrow('migration_activity_lease_shape_mismatch') - }) - - it('moves a dead assignment only after a completed exact-incarnation fence attempt', async () => { - let now = 100 - const cappedCells = CELLS.map((cell) => ({ - ...cell, - connectionHardCap: 600 as const, - connectionUnobservedBound: 50 - })) - const store = await setupWithHeartbeats(() => now, cappedCells) - await heartbeat(store, cappedCells[0]!) - await heartbeat(store, cappedCells[1]!, { - incarnation: '22222222-2222-4222-8222-222222222222' - }) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await store.assign(identity) - await store.setCellEnabled('cell-a', false) - now += 45_001 - await heartbeat(store, cappedCells[1]!, { - incarnation: '22222222-2222-4222-8222-222222222222' - }) - - await store.attestCellFence('cell-a', '11111111-1111-4111-8111-111111111111') - expect( - await database!.query( - `SELECT cell_id FROM relay_cell_legacy_fence_adoptions WHERE cell_id = ?`, - ['cell-a'] - ) - ).toEqual([]) - expect(await store.evacuateDeadCells()).toBe(0) - expect( - await database!.query( - `SELECT cell_id FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ cell_id: 'cell-a' }]) - - now += 300_001 - await heartbeat(store, cappedCells[1]!, { - incarnation: '22222222-2222-4222-8222-222222222222' - }) - const evidence = { - attemptId: '22222222-2222-4222-8222-222222222222', - environment: 'production' as const, - cellId: 'cell-a', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - migName: 'orca-relay-c1', - instanceGroup: 'https://compute.example/instanceGroups/orca-relay-c1', - generationIdentity: 'https://compute.example/instanceTemplates/orca-relay-c1-abc', - fenceCommit: 'a'.repeat(40), - planSha256: 'b'.repeat(64), - ...FENCE_PLAN_BINDING - } - await store.prepareCellFenceAttempt(evidence) - await store.bindCellFencePlanGeneration(evidence, evidence.planObjectGeneration) - await store.startCellFenceApply(evidence, FENCE_INVOCATION_ID, FENCE_INVOCATION_REASON) - await store.recordCellFenceOperation( - evidence, - FENCE_INVOCATION_ID, - FENCE_INVOCATION_REASON, - 'operation-1' - ) - await store.attestCellFenceAttempt(evidence, 'operation-1') - - expect(await store.evacuateDeadCells()).toBe(1) - expect((await store.resolve(identity))?.cellId).toBe('cell-b') - }) - - it('preserves proven non-delivery and permits one fresh full-grace attempt', async () => { - const store = await setupWithHeartbeats(() => 100, [CELLS[0]!]) - await heartbeat(store) - await store.setCellEnabled('cell-a', false) - const first = { - attemptId: '33333333-3333-4333-8333-333333333333', - cellId: 'cell-a', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - traceValue: '44444444-4444-4444-8444-444444444444', - plannedGraceMs: 120_000 - } - await store.prepareCellDrainAttempt(first) - await store.beginCellDrainSend(first) - await expect(store.proveCellDrainNotDelivered(first)).resolves.toMatchObject({ - state: 'proven-not-delivered', - provenNotDeliveredAt: 100 - }) - await expect( - store.prepareCellDrainAttempt({ - ...first, - attemptId: '55555555-5555-4555-8555-555555555555', - traceValue: '66666666-6666-4666-8666-666666666666' - }) - ).resolves.toMatchObject({ state: 'prepared' }) - }) - - it('binds fence attestation to one durable Terraform attempt', async () => { - let now = 100 - const store = await setupWithHeartbeats(() => now, [CELLS[0]!]) - await heartbeat(store) - await store.setCellEnabled('cell-a', false) - const evidence = { - attemptId: '22222222-2222-4222-8222-222222222222', - environment: 'production' as const, - cellId: 'cell-a', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - migName: 'orca-relay-c1', - instanceGroup: 'https://compute.example/instanceGroups/orca-relay-c1', - generationIdentity: 'https://compute.example/instanceTemplates/orca-relay-c1-abc', - fenceCommit: 'a'.repeat(40), - planSha256: 'b'.repeat(64), - ...FENCE_PLAN_BINDING - } - const prepared = await store.prepareCellFenceAttempt(evidence) - expect(prepared).toMatchObject({ createdAt: 100, expiresAt: 3_600_100 }) - expect(prepared.planObjectGeneration).toBeUndefined() - await expect( - store.bindCellFencePlanGeneration(evidence, evidence.planObjectGeneration) - ).resolves.toMatchObject({ - planObjectGeneration: evidence.planObjectGeneration - }) - await expect( - store.bindCellFencePlanGeneration(evidence, evidence.planObjectGeneration) - ).resolves.toMatchObject({ - planObjectGeneration: evidence.planObjectGeneration - }) - await expect(store.bindCellFencePlanGeneration(evidence, '987654321')).rejects.toThrow( - 'cell_fence_plan_generation_mismatch' - ) - for (const changed of [ - { attemptId: '33333333-3333-4333-8333-333333333333' }, - { environment: 'staging' as const }, - { cellId: 'cell-b' }, - { cellIncarnation: '33333333-3333-4333-8333-333333333333' }, - { migName: 'orca-relay-other' }, - { instanceGroup: `${evidence.instanceGroup}-other` }, - { generationIdentity: `${evidence.generationIdentity}-other` }, - { fenceCommit: 'c'.repeat(40) }, - { planSha256: 'c'.repeat(64) } - ]) { - await expect( - store.startCellFenceApply( - { ...evidence, ...changed }, - FENCE_INVOCATION_ID, - FENCE_INVOCATION_REASON - ) - ).rejects.toThrow() - } - await store.startCellFenceApply(evidence, FENCE_INVOCATION_ID, FENCE_INVOCATION_REASON) - await store.recordCellFenceOperation( - evidence, - FENCE_INVOCATION_ID, - FENCE_INVOCATION_REASON, - 'operation-1' - ) - now += 45_001 - await expect(store.attestCellFenceAttempt(evidence, 'operation-other')).rejects.toThrow( - 'cell_fence_operation_not_attested' - ) - const attested = await store.attestCellFenceAttempt(evidence, 'operation-1') - expect(attested).toMatchObject({ - expiresAt: now + 300_000, - attempt: { ...evidence, gceOperation: 'operation-1', completedAt: now } - }) - await expect(store.attestCellFenceAttempt(evidence, 'operation-1')).resolves.toEqual(attested) - now += 300_001 - await expect(store.attestCellFenceAttempt(evidence, 'operation-1')).resolves.toMatchObject({ - expiresAt: now + 300_000, - attempt: { completedAt: attested.attempt.completedAt } - }) - }) - - it('aborts only a Terraform fence whose apply never started', async () => { - const store = await setupWithHeartbeats(() => 100, [CELLS[0]!]) - await heartbeat(store) - await store.setCellEnabled('cell-a', false) - const evidence = { - attemptId: '22222222-2222-4222-8222-222222222222', - environment: 'production' as const, - cellId: 'cell-a', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - migName: 'orca-relay-c1', - instanceGroup: 'https://compute.example/instanceGroups/orca-relay-c1', - generationIdentity: 'https://compute.example/instanceTemplates/orca-relay-c1-abc', - fenceCommit: 'a'.repeat(40), - planSha256: 'b'.repeat(64), - ...FENCE_PLAN_BINDING - } - await store.prepareCellFenceAttempt(evidence) - await store.bindCellFencePlanGeneration(evidence, evidence.planObjectGeneration) - await expect(store.abortCellFenceAttempt(evidence)).resolves.toMatchObject({ - abortedAt: 100 - }) - await expect( - store.startCellFenceApply(evidence, FENCE_INVOCATION_ID, FENCE_INVOCATION_REASON) - ).rejects.toThrow('cell_fence_attempt_aborted') - }) - - it('adopts a stale disabled legacy fence only when no durable attempt exists', async () => { - let now = 100 - const store = await setupWithHeartbeats(() => now, [CELLS[0]!]) - await heartbeat(store) - await store.setCellEnabled('cell-a', false) - now += 45_001 - - await expect( - store.adoptLegacyCellFence('cell-a', '11111111-1111-4111-8111-111111111111') - ).resolves.toBe(now + 300_000) - await expect( - database!.query(`SELECT cell_id, cell_incarnation FROM relay_cell_fences WHERE cell_id = ?`, [ - 'cell-a' - ]) - ).resolves.toEqual([ - { - cell_id: 'cell-a', - cell_incarnation: '11111111-1111-4111-8111-111111111111' - } - ]) - await expect( - database!.query( - `SELECT cell_id, cell_incarnation - FROM relay_cell_legacy_fence_adoptions WHERE cell_id = ?`, - ['cell-a'] - ) - ).resolves.toEqual([]) - await store.commitLegacyCellFenceAdoption('cell-a', '11111111-1111-4111-8111-111111111111') - await expect( - database!.query( - `SELECT cell_id, cell_incarnation - FROM relay_cell_legacy_fence_adoptions WHERE cell_id = ?`, - ['cell-a'] - ) - ).resolves.toEqual([ - { - cell_id: 'cell-a', - cell_incarnation: '11111111-1111-4111-8111-111111111111' - } - ]) - - now += 1 - await expect( - store.adoptLegacyCellFence('cell-a', '11111111-1111-4111-8111-111111111111') - ).resolves.toBe(now + 300_000) - await store.commitLegacyCellFenceAdoption('cell-a', '11111111-1111-4111-8111-111111111111') - await expect( - database!.query( - `SELECT attested_at, expires_at - FROM relay_cell_legacy_fence_adoptions WHERE cell_id = ?`, - ['cell-a'] - ) - ).resolves.toEqual([{ attested_at: now, expires_at: now + 300_000 }]) - - await heartbeat(store) - await expect( - database!.query(`SELECT cell_id FROM relay_cell_legacy_fence_adoptions WHERE cell_id = ?`, [ - 'cell-a' - ]) - ).resolves.toEqual([]) - }) - - it.each(['active', 'completed', 'aborted'] as const)( - 'rejects legacy adoption after a %s durable attempt', - async (status) => { - let now = 100 - const store = await setupWithHeartbeats(() => now, [CELLS[0]!]) - await heartbeat(store) - await store.setCellEnabled('cell-a', false) - const evidence = cellFenceEvidence() - await store.prepareCellFenceAttempt(evidence) - if (status === 'aborted') await store.abortCellFenceAttempt(evidence) - if (status === 'completed') { - await store.bindCellFencePlanGeneration(evidence, evidence.planObjectGeneration) - await store.startCellFenceApply(evidence, FENCE_INVOCATION_ID, FENCE_INVOCATION_REASON) - await store.recordCellFenceOperation( - evidence, - FENCE_INVOCATION_ID, - FENCE_INVOCATION_REASON, - 'operation-1' - ) - } - now += 45_001 - if (status === 'completed') { - await store.attestCellFenceAttempt(evidence, 'operation-1') - } - - await expect( - store.adoptLegacyCellFence('cell-a', '11111111-1111-4111-8111-111111111111') - ).rejects.toThrow('legacy_cell_fence_attempt_exists') - } - ) - - it('serializes legacy adoption against durable attempt preparation', async () => { - let now = 100 - const store = await setupWithHeartbeats(() => now, [CELLS[0]!]) - await heartbeat(store) - await store.setCellEnabled('cell-a', false) - now += 45_001 - - const results = await Promise.allSettled([ - store.adoptLegacyCellFence('cell-a', '11111111-1111-4111-8111-111111111111'), - store.prepareCellFenceAttempt(cellFenceEvidence()) - ]) - expect(results.filter(({ status }) => status === 'fulfilled')).toHaveLength(1) - const attempts = await database!.query( - `SELECT COUNT(*) AS count FROM relay_cell_fence_attempts WHERE cell_id = ?`, - ['cell-a'] - ) - const fences = await database!.query( - `SELECT COUNT(*) AS count FROM relay_cell_fences WHERE cell_id = ?`, - ['cell-a'] - ) - const adoptions = await database!.query( - `SELECT COUNT(*) AS count FROM relay_cell_legacy_fence_adoptions - WHERE cell_id = ?`, - ['cell-a'] - ) - expect(Number(attempts[0]!.count) + Number(fences[0]!.count)).toBe(1) - expect(Number(adoptions[0]!.count)).toBe(0) - }) - - it('rejects an expired durable Terraform fence attempt', async () => { - let now = 100 - const store = await setupWithHeartbeats(() => now, [CELLS[0]!]) - await heartbeat(store) - await store.setCellEnabled('cell-a', false) - const evidence = { - attemptId: '22222222-2222-4222-8222-222222222222', - environment: 'production' as const, - cellId: 'cell-a', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - migName: 'orca-relay-c1', - instanceGroup: 'https://compute.example/instanceGroups/orca-relay-c1', - generationIdentity: 'https://compute.example/instanceTemplates/orca-relay-c1-abc', - fenceCommit: 'a'.repeat(40), - planSha256: 'b'.repeat(64), - ...FENCE_PLAN_BINDING - } - await store.prepareCellFenceAttempt(evidence) - await store.bindCellFencePlanGeneration(evidence, evidence.planObjectGeneration) - now += 3_600_001 - await expect( - store.startCellFenceApply(evidence, FENCE_INVOCATION_ID, FENCE_INVOCATION_REASON) - ).rejects.toThrow('cell_fence_attempt_expired') - }) - - it('keeps a started Terraform fence attempt recoverable after its preparation TTL', async () => { - let now = 100 - const store = await setupWithHeartbeats(() => now, [CELLS[0]!]) - await heartbeat(store) - await store.setCellEnabled('cell-a', false) - const evidence = { - attemptId: '22222222-2222-4222-8222-222222222222', - environment: 'production' as const, - cellId: 'cell-a', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - migName: 'orca-relay-c1', - instanceGroup: 'https://compute.example/instanceGroups/orca-relay-c1', - generationIdentity: 'https://compute.example/instanceTemplates/orca-relay-c1-abc', - fenceCommit: 'a'.repeat(40), - planSha256: 'b'.repeat(64), - ...FENCE_PLAN_BINDING - } - await store.prepareCellFenceAttempt(evidence) - await store.bindCellFencePlanGeneration(evidence, evidence.planObjectGeneration) - await store.startCellFenceApply(evidence, FENCE_INVOCATION_ID, FENCE_INVOCATION_REASON) - now += 3_600_001 - await expect( - store.recordCellFenceOperation( - evidence, - FENCE_INVOCATION_ID, - FENCE_INVOCATION_REASON, - 'operation-1' - ) - ).resolves.toMatchObject({ - attempt: { gceOperation: 'operation-1' }, - invocation: { gceOperation: 'operation-1' } - }) - await expect( - store.prepareCellFenceAttempt({ - ...evidence, - attemptId: '44444444-4444-4444-8444-444444444444', - planObjectName: - 'terraform/state/relay-fence-plans/production/44444444-4444-4444-8444-444444444444.tfplan', - requestReason: 'orca-relay-fence/44444444-4444-4444-8444-444444444444' - }) - ).rejects.toThrow('cell_fence_attempt_evidence_mismatch') - }) - - it('reports aggregate deployment state and heartbeat freshness without identities', async () => { - let now = 100 - const store = await setupWithHeartbeats(() => now, [CELLS[0]!]) - await heartbeat(store) - const identity = { userId: 'private-user', relayHostId: 'host000000000001' } - const assignment = await store.assign(identity) - expect(await store.cellDeploymentStatus('cell-a')).toMatchObject({ - activityLeases: 1, - activityRequestUnits: 1, - restartBlockingActivityLeases: 0, - restartBlockingActivityRequestUnits: 0, - restartBlockingReservedRequests: 0 - }) - await store.activateControl(identity, { - cellId: 'cell-a', - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - - expect(await store.cellDeploymentStatus('cell-a')).toEqual({ - cellId: 'cell-a', - cellUrl: 'https://relay-a.example.com', - region: 'us-central1', - enabled: true, - admissionState: 'general', - capacityRequests: 2, - reservedRequests: 1, - assignments: 1, - activityLeases: 1, - activityRequestUnits: 1, - restartBlockingActivityLeases: 1, - restartBlockingActivityRequestUnits: 1, - restartBlockingReservedRequests: 1, - outgoingMigrations: 0, - incomingMigrations: 0, - connectionCapacity: null, - runtime: { - cellUrl: 'https://relay-a.example.com', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - startedAt: 50, - ready: true, - observedRequests: 0, - lastHeartbeatAt: 100, - heartbeatFresh: true, - regionalRehomeProtocol: 0 - } - }) - now += 45_001 - expect((await store.cellDeploymentStatus('cell-a')).runtime?.heartbeatFresh).toBe(false) - await expect(store.cellDeploymentStatus('missing')).rejects.toThrow('cell_not_found') - }) - - it('keeps concurrent sticky assignment grants restart-safe', async () => { - const store = await setup( - () => 100, - [{ id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }] - ) - const identity = { userId: 'private-user', relayHostId: 'host000000000001' } - - await Promise.all(Array.from({ length: 20 }, async () => await store.assign(identity))) - - expect(await store.cellDeploymentStatus('cell-a')).toMatchObject({ - activityLeases: 1, - activityRequestUnits: 1, - reservedRequests: 1, - restartBlockingActivityLeases: 0, - restartBlockingActivityRequestUnits: 0, - restartBlockingReservedRequests: 0 - }) - }) - - it('classifies activated and non-control activity as restart-blocking', async () => { - const store = await setup( - () => 100, - [{ id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }] - ) - const identity = { userId: 'private-user', relayHostId: 'host000000000001' } - const assignment = await store.assign(identity) - await store.activateControl(identity, { - cellId: assignment.cellId, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - for (const kind of ['splice', 'invite', 'install', 'confirmation', 'migration'] as const) { - await store.acquireActivity(identity, { - activityId: `${kind}:test`, - kind, - cellId: assignment.cellId - }) - } - - expect(await store.cellDeploymentStatus('cell-a')).toMatchObject({ - activityLeases: 6, - activityRequestUnits: 7, - reservedRequests: 7, - restartBlockingActivityLeases: 6, - restartBlockingActivityRequestUnits: 7, - restartBlockingReservedRequests: 7 - }) - }) - - it('fails closed for malformed pending controls and unexplained reservations', async () => { - const store = await setup( - () => 100, - [{ id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }] - ) - await store.assign({ userId: 'private-user', relayHostId: 'host000000000001' }) - await database!.query( - `UPDATE relay_assignment_activity_leases SET request_units = 2 - WHERE cell_id = ?`, - ['cell-a'] - ) - expect(await store.cellDeploymentStatus('cell-a')).toMatchObject({ - restartBlockingActivityLeases: 1, - restartBlockingActivityRequestUnits: 2, - restartBlockingReservedRequests: 1 - }) - - await database!.query( - `UPDATE relay_assignment_activity_leases SET request_units = 1 WHERE cell_id = ?`, - ['cell-a'] - ) - await database!.query(`UPDATE relay_cells SET reserved_requests = 0 WHERE cell_id = ?`, [ - 'cell-a' - ]) - expect(await store.cellDeploymentStatus('cell-a')).toMatchObject({ - restartBlockingActivityLeases: 0, - restartBlockingActivityRequestUnits: 0, - restartBlockingReservedRequests: -1 - }) - - await database!.query(`UPDATE relay_cells SET reserved_requests = 2 WHERE cell_id = ?`, [ - 'cell-a' - ]) - expect(await store.cellDeploymentStatus('cell-a')).toMatchObject({ - restartBlockingActivityLeases: 0, - restartBlockingActivityRequestUnits: 0, - restartBlockingReservedRequests: 1 - }) - }) - - it('keeps a migration blocking when its target also has a pending control', async () => { - const store = await setup( - () => 100, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 20 } - ] - ) - const identity = { userId: 'private-user', relayHostId: 'host000000000001' } - await store.assign(identity) - await store.startEvacuation(identity, 'cell-b') - - expect(await store.cellDeploymentStatus('cell-b')).toMatchObject({ - activityLeases: 2, - restartBlockingActivityLeases: 1, - restartBlockingActivityRequestUnits: 1, - restartBlockingReservedRequests: 1, - incomingMigrations: 1 - }) - }) - - it('starts declared candidates disabled without overwriting later operator state', async () => { - const candidate: RelayCellConfig = { - id: 'candidate', - url: 'https://candidate.example.com', - capacityRequests: 20, - initiallyEnabled: false - } - const store = await setup(() => 100, [candidate]) - expect((await store.cellDeploymentStatus('candidate')).enabled).toBe(false) - await store.setCellEnabled('candidate', true) - await store.reconcileCells([candidate]) - expect((await store.cellDeploymentStatus('candidate')).enabled).toBe(true) - }) - it('moves a stranded host off an existing-only cell that stopped serving it', async () => { // C3 rejected attaches on an existing-only cell; repeated grants defeated dormancy (#194, #225). Use recent failed grants on assignment rows: no cap reservations exist, and expired leases are pruned. let now = 100 @@ -1409,457 +157,6 @@ describe('RelayAssignmentStore', () => { expect(settled.assignmentEpoch).toBe(moved.assignmentEpoch) }) - it('keeps a serving existing-only cell pinned for hosts with live activity', async () => { - let now = 100 - const store = await setup(() => now) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - await store.setCellEnabled(first.cellId, false) - // A live claimed control proves the cell still serves this host. - await database!.query( - `INSERT INTO relay_assignment_activity_leases - (user_id, relay_host_id, activity_id, activity_kind, cell_id, - request_units, expires_at, updated_at) - VALUES (?, ?, ?, 'control', ?, 1, ?, ?)`, - [identity.userId, identity.relayHostId, 'control:live-1', first.cellId, now + 600_000, now] - ) - now += 61_000 - const pinned = await store.assign(identity) - expect(pinned.cellId).toBe(first.cellId) - }) - - it('keeps migration-only cells pinned inside the stranded window', async () => { - // migration-only durably holds evacuation/Asia rollback/failed-wave hosts; only same-cap roll stamps authorize re-placement. - let now = 100 - const store = await setup(() => now) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - await store.setCellAdmissionState(first.cellId, 'migration-only') - now += 61_000 - const pinned = await store.assign(identity) - expect(pinned.cellId).toBe(first.cellId) - }) - - it('leaves quiet existing-only assignments to the normal dormancy rule', async () => { - // Why: outside the 15-minute stranded window there is no active retry - // loop to break; ordinary returns stay pinned until 24h dormancy. - let now = 100 - const store = await setup(() => now) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - await store.setCellEnabled(first.cellId, false) - now += 20 * 60_000 - const pinned = await store.assign(identity) - expect(pinned.cellId).toBe(first.cellId) - }) - - it('reassigns an active assignment from an uncapped stale cell without a fence', async () => { - let now = 100 - const store = await setupWithHeartbeats(() => now) - await heartbeat(store, CELLS[0]!) - await heartbeat(store, CELLS[1]!, { - incarnation: '22222222-2222-4222-8222-222222222222' - }) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - await store.changeActivity(identity, 'invite', 1) - await database!.query( - `INSERT INTO relay_assignment_migrations - (user_id, relay_host_id, source_cell_id, target_cell_id, - previous_epoch, assignment_epoch, source_request_units, - target_reserved_units, expires_at, target_registered_at, - completed_at, aborted_at, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, ?, ?)`, - [identity.userId, identity.relayHostId, 'cell-b', 'cell-a', -1, 0, 0, 1, 90_100, now, now] - ) - await database!.query( - `INSERT INTO relay_post_drain_migration_pins - (user_id, relay_host_id, assignment_epoch, drain_attempt_id, - source_cell_id, source_cell_incarnation, target_cell_id, - target_cell_incarnation, source_request_units, target_reserved_units, - pinned_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - [ - identity.userId, - identity.relayHostId, - 0, - '33333333-3333-4333-8333-333333333333', - 'cell-b', - '22222222-2222-4222-8222-222222222222', - 'cell-a', - '11111111-1111-4111-8111-111111111111', - 0, - 1, - now - ] - ) - - now += 45_001 - await heartbeat(store, CELLS[1]!, { - incarnation: '22222222-2222-4222-8222-222222222222' - }) - expect(await store.evacuateDeadCells()).toBe(1) - const replacement = await store.resolve(identity) - expect(replacement).toMatchObject({ - cellId: 'cell-b', - assignmentEpoch: first.assignmentEpoch + 1 - }) - expect( - await database!.query( - `SELECT activity_kind, cell_id FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ activity_kind: 'control', cell_id: 'cell-b' }]) - }) - - it('skips a host whose row is busy and still evacuates the rest of the dead cell', async () => { - let now = 100 - const cells: RelayCellConfig[] = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const store = await setupWithHeartbeats(() => now, cells) - for (const cell of cells) await heartbeat(store, cell) - await store.setCellEnabled('cell-b', false) - const busy = { userId: 'a-busy', relayHostId: 'host000000000001' } - const later = { userId: 'b-later', relayHostId: 'host000000000002' } - expect(await store.assign(busy)).toMatchObject({ cellId: 'cell-a' }) - expect(await store.assign(later)).toMatchObject({ cellId: 'cell-a' }) - await store.setCellEnabled('cell-b', true) - - now += 45_001 - await heartbeat(store, cells[1]!) - // The sweep reaches the busy host first: its own release holds its row. - const assign = store.assign.bind(store) - vi.spyOn(store, 'assign').mockImplementation(async (identity, ...rest) => { - if (identity.relayHostId === busy.relayHostId) throw new RelayAssignmentRowBusyError() - return await assign(identity, ...rest) - }) - - expect(await store.evacuateDeadCells()).toBe(1) - expect(await store.resolve(later)).toMatchObject({ cellId: 'cell-b' }) - expect( - await database!.query(`SELECT cell_id FROM relay_assignments WHERE user_id = ?`, [ - busy.userId - ]) - ).toEqual([{ cell_id: 'cell-a' }]) - }) - - it('does not let an unfenced capped cell starve eligible legacy recovery', async () => { - let now = 100 - const cells: RelayCellConfig[] = [ - { - id: 'cell-a', - url: 'https://relay-a.example.com', - capacityRequests: 10, - connectionHardCap: 600, - connectionUnobservedBound: 50 - }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 }, - { id: 'cell-c', url: 'https://relay-c.example.com', capacityRequests: 10 } - ] - const store = await setupWithHeartbeats(() => now, cells) - for (const cell of cells) await heartbeat(store, cell) - await store.setCellEnabled('cell-b', false) - await store.setCellEnabled('cell-c', false) - const cappedIdentity = { userId: 'a-capped', relayHostId: 'host000000000001' } - expect(await store.assign(cappedIdentity)).toMatchObject({ cellId: 'cell-a' }) - - await store.setCellEnabled('cell-a', false) - await store.setCellEnabled('cell-b', true) - const legacyIdentity = { userId: 'z-legacy', relayHostId: 'host000000000002' } - expect(await store.assign(legacyIdentity)).toMatchObject({ cellId: 'cell-b' }) - await store.setCellEnabled('cell-c', true) - - now += 45_001 - await heartbeat(store, cells[2]!) - expect(await store.evacuateDeadCells(1)).toBe(1) - expect(await store.resolve(legacyIdentity)).toMatchObject({ cellId: 'cell-c' }) - expect( - await database!.query(`SELECT cell_id FROM relay_assignments WHERE user_id = ?`, [ - cappedIdentity.userId - ]) - ).toEqual([{ cell_id: 'cell-a' }]) - }) - - it('refuses evacuation into a cell without a fresh ready heartbeat', async () => { - const store = await setupWithHeartbeats(() => 100) - await heartbeat(store, CELLS[0]!) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await store.assign(identity) - - await expect(store.startEvacuation(identity, 'cell-b')).rejects.toThrow( - 'target_cell_unavailable' - ) - }) - - it('keeps an active assignment sticky without increasing its epoch or reservation', async () => { - const store = await setup(() => 100) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const second = await store.assign(identity) - - expect(first.placed).toBe(true) - expect(second).toEqual({ ...first, placed: undefined }) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 1, 'cell-b': 0 }) - }) - - it('selects the least-loaded cell with a stable cell-id tie break', async () => { - const store = await setup(() => 100) - const first = await store.assign({ userId: 'user-a', relayHostId: 'host000000000001' }) - const second = await store.assign({ userId: 'user-b', relayHostId: 'host000000000002' }) - - expect([first.cellId, second.cellId]).toEqual(['cell-a', 'cell-b']) - }) - - it('admits exactly through the configured capacity boundary', async () => { - const store = await setup( - () => 100, - [{ id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 2 }] - ) - await store.assign({ userId: 'user-a', relayHostId: 'host000000000001' }) - await store.assign({ userId: 'user-b', relayHostId: 'host000000000002' }) - - await expect( - store.assign({ userId: 'user-c', relayHostId: 'host000000000003' }) - ).rejects.toThrow('relay_capacity_exhausted') - expect(await cellReservations(database!)).toEqual({ 'cell-a': 2 }) - }) - - it('does not oversubscribe when assignments race', async () => { - const store = await setup( - () => 100, - [{ id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 2 }] - ) - const results = await Promise.allSettled( - Array.from({ length: 8 }, (_, index) => - store.assign({ - userId: `user-${index}`, - relayHostId: `host${String(index).padStart(12, '0')}` - }) - ) - ) - - expect(results.filter(({ status }) => status === 'fulfilled')).toHaveLength(2) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 2 }) - }) - - it('reassigns only after all activity expires and the dormant TTL elapses', async () => { - let now = 100 - const store = await setup(() => now) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - await store.changeActivity(identity, 'invite', 1) - await store.changeActivity(identity, 'control', -1) - - now += ASSIGNMENT_LIMITS.activityLeaseMs + 1 - await store.releaseExpiredActivityLeases() - await store.releaseExpiredActivity() - await database!.query(`UPDATE relay_cells SET observed_requests = 2 WHERE cell_id = ?`, [ - first.cellId - ]) - now += ASSIGNMENT_LIMITS.dormantTtlMs - const reassigned = await store.assign(identity) - - expect(reassigned.cellId).not.toBe(first.cellId) - expect(reassigned.assignmentEpoch).toBe(first.assignmentEpoch + 1) - }) - - it('will not normally move an assignment while any durable activity remains', async () => { - let now = 100 - const store = await setup(() => now) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - await store.changeActivity(identity, 'migration', 1) - await store.changeActivity(identity, 'control', -1) - await database!.query(`UPDATE relay_cells SET observed_requests = 2 WHERE cell_id = ?`, [ - first.cellId - ]) - now += ASSIGNMENT_LIMITS.dormantTtlMs + 1 - - expect(await store.assign(identity)).toMatchObject({ - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch - }) - }) - - it('releases every expired activity reservation without going negative', async () => { - let now = 100 - const store = await setup( - () => now, - [{ id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }] - ) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await store.assign(identity) - for (const kind of ['splice', 'invite', 'install', 'confirmation', 'migration'] as const) { - await store.changeActivity(identity, kind, 1) - } - expect(await cellReservations(database!)).toEqual({ 'cell-a': 7 }) - - now += ASSIGNMENT_LIMITS.activityLeaseMs + 1 - expect(await store.releaseExpiredActivityLeases()).toBe(1) - expect(await store.releaseExpiredActivity()).toBe(1) - expect(await store.releaseExpiredActivity()).toBe(0) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 0 }) - }) - - it('isolates assignments by host and verifies both cell and epoch', async () => { - const store = await setup(() => 100) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const assignment = await store.assign(identity) - - await expect( - store.verifyCellAssignment({ ...identity, cellId: assignment.cellId, assignmentEpoch: 1 }) - ).resolves.toBe(true) - await expect( - store.verifyCellAssignment({ ...identity, cellId: 'cell-b', assignmentEpoch: 1 }) - ).resolves.toBe(false) - await expect( - store.verifyCellAssignment({ ...identity, cellId: assignment.cellId, assignmentEpoch: 2 }) - ).resolves.toBe(false) - await expect( - store.verifyCellAssignment({ - ...identity, - userId: 'other', - cellId: assignment.cellId, - assignmentEpoch: 1 - }) - ).resolves.toBe(false) - await expect( - store.verifyCellAssignment({ - ...identity, - relayHostId: 'host000000000002', - cellId: assignment.cellId, - assignmentEpoch: 1 - }) - ).resolves.toBe(false) - await expect( - store.resolve({ userId: 'other', relayHostId: identity.relayHostId }) - ).resolves.toBeNull() - }) - - it('converts the director reservation into an idempotent active-control lease', async () => { - const store = await setup(() => 100) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const assignment = await store.assign(identity) - - const activityId = await store.activateControl(identity, { - cellId: assignment.cellId, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - await store.activateControl(identity, { - cellId: assignment.cellId, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - - expect(activityId).toBe(`control:${assignment.cellId}:1`) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 1, 'cell-b': 0 }) - const leases = await database!.query(`SELECT activity_id FROM relay_assignment_activity_leases`) - expect(leases).toEqual([{ activity_id: activityId }]) - }) - - it('transactionally supersedes older controls on only the same cell', async () => { - const cells = [ - { - id: 'cell-a', - url: 'https://relay-a.example.com', - capacityRequests: 10 - }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const store = await setup(() => 100, cells) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await store.setCellEnabled('cell-b', false) - const assignment = await store.assign(identity) - await store.activateControl(identity, { - cellId: assignment.cellId, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - await store.setCellEnabled('cell-b', true) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await database!.query( - `INSERT INTO relay_assignment_activity_leases - (user_id, relay_host_id, activity_id, activity_kind, cell_id, - request_units, expires_at, updated_at) - VALUES (?, ?, ?, 'control', 'cell-b', 1, 90100, 100), - (?, ?, ?, 'control', 'cell-b', 1, 90100, 100)`, - [ - identity.userId, - identity.relayHostId, - 'control:cell-b:2', - identity.userId, - identity.relayHostId, - 'control:cell-b:3' - ] - ) - // The store reserves a unit per control lease, so a hand-written pair has to - // carry its own reservation or the fixture starts out of balance. - await database!.query( - `UPDATE relay_cells SET reserved_requests = reserved_requests + 2 WHERE cell_id = 'cell-b'` - ) - const latest = await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 4 - }) - - expect( - await database!.query( - `SELECT activity_id, cell_id FROM relay_assignment_activity_leases - WHERE activity_kind = 'control' ORDER BY cell_id` - ) - ).toEqual([ - { activity_id: 'control:cell-a:1', cell_id: 'cell-a' }, - { activity_id: latest, cell_id: 'cell-b' } - ]) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 1, 'cell-b': 2 }) - expect( - await database!.query( - `SELECT reserved_controls FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ reserved_controls: 2 }]) - }) - - it('re-reserves a sticky grant for a host holding no control lease', async () => { - const store = await setup(() => 100) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const assignment = await store.assign(identity) - const control = await store.activateControl(identity, { - cellId: assignment.cellId, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - await store.releaseActivity(identity, control) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 0, 'cell-b': 0 }) - - await expect(store.assign(identity)).resolves.toMatchObject({ - cellId: assignment.cellId, - assignmentEpoch: assignment.assignmentEpoch - }) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 1, 'cell-b': 0 }) - expect( - await database!.query(`SELECT activity_id FROM relay_assignment_activity_leases`) - ).toEqual([{ activity_id: 'control-pending:1' }]) - expect( - await database!.query( - `SELECT reserved_controls FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ reserved_controls: 1 }]) - }) - it('re-pins a host that took control after the sticky lane read it dormant', async () => { const now = 100 const delegate = await openInMemoryRelayDatabase() @@ -1925,532 +222,6 @@ describe('RelayAssignmentStore', () => { ]) }) - it('reserves control on the pinned cell when the only lease sits on another', async () => { - const now = 100 - const store = await setup(() => now) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await database!.query( - `INSERT INTO relay_assignments - (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, - last_activity_at, reserved_controls, reserved_splices, reserved_invites, - pending_installs, pending_confirmations, migration_leases) - VALUES (?, ?, 'cell-b', 2, ?, ?, 1, 0, 0, 0, 0, 0)`, - [identity.userId, identity.relayHostId, now + ASSIGNMENT_LIMITS.activityLeaseMs, now] - ) - await database!.query( - `INSERT INTO relay_assignment_activity_leases - (user_id, relay_host_id, activity_id, activity_kind, cell_id, - request_units, expires_at, updated_at) - VALUES (?, ?, 'control:cell-a:1', 'control', 'cell-a', 1, ?, ?)`, - [identity.userId, identity.relayHostId, now + ASSIGNMENT_LIMITS.activityLeaseMs, now] - ) - await database!.query(`UPDATE relay_cells SET reserved_requests = 1 WHERE cell_id = 'cell-a'`) - - await expect(store.assign(identity)).resolves.toMatchObject({ - cellId: 'cell-b', - assignmentEpoch: 2 - }) - expect( - await database!.query( - `SELECT activity_id, cell_id FROM relay_assignment_activity_leases - ORDER BY activity_id ASC` - ) - ).toEqual([ - { activity_id: 'control-pending:2', cell_id: 'cell-b' }, - { activity_id: 'control:cell-a:1', cell_id: 'cell-a' } - ]) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 1, 'cell-b': 1 }) - expect( - await database!.query( - `SELECT reserved_controls FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ reserved_controls: 2 }]) - }) - - it('mints a pending control when the only lease is an older epoch pending', async () => { - const now = 100 - const store = await setup(() => now) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await database!.query( - `INSERT INTO relay_assignments - (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, - last_activity_at, reserved_controls, reserved_splices, reserved_invites, - pending_installs, pending_confirmations, migration_leases) - VALUES (?, ?, 'cell-a', 3, ?, ?, 1, 0, 0, 0, 0, 0)`, - [identity.userId, identity.relayHostId, now + ASSIGNMENT_LIMITS.activityLeaseMs, now] - ) - await database!.query( - `INSERT INTO relay_assignment_activity_leases - (user_id, relay_host_id, activity_id, activity_kind, cell_id, - request_units, expires_at, updated_at) - VALUES (?, ?, 'control-pending:1', 'control', 'cell-a', 1, ?, ?)`, - [identity.userId, identity.relayHostId, now + ASSIGNMENT_LIMITS.activityLeaseMs, now] - ) - await database!.query(`UPDATE relay_cells SET reserved_requests = 1 WHERE cell_id = 'cell-a'`) - - await expect(store.assign(identity)).resolves.toMatchObject({ - cellId: 'cell-a', - assignmentEpoch: 3 - }) - expect( - await database!.query( - `SELECT activity_id FROM relay_assignment_activity_leases - ORDER BY activity_id ASC` - ) - ).toEqual([{ activity_id: 'control-pending:1' }, { activity_id: 'control-pending:3' }]) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 2, 'cell-b': 0 }) - expect( - await database!.query( - `SELECT reserved_controls FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ reserved_controls: 2 }]) - }) - - it('re-reserves a re-pinned grant for a host holding no control lease', async () => { - const now = 100 - const delegate = await openInMemoryRelayDatabase() - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const seeded = new SeedBetweenAssignmentLanesDatabase(delegate, async () => { - await delegate.query( - `INSERT INTO relay_assignment_activity_leases - (user_id, relay_host_id, activity_id, activity_kind, cell_id, - request_units, expires_at, updated_at) - VALUES (?, ?, 'splice:connection-1', 'splice', 'cell-a', 1, ?, ?)`, - [identity.userId, identity.relayHostId, now + ASSIGNMENT_LIMITS.activityLeaseMs, now] - ) - await delegate.query( - `UPDATE relay_assignments SET reserved_splices = 1 - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - await delegate.query(`UPDATE relay_cells SET reserved_requests = 1 WHERE cell_id = 'cell-a'`) - }) - database = seeded - const store = new RelayAssignmentStore(seeded, () => now) - await store.reconcileCells(CELLS) - await delegate.query( - `INSERT INTO relay_assignments - (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, - last_activity_at, reserved_controls, reserved_splices, reserved_invites, - pending_installs, pending_confirmations, migration_leases) - VALUES (?, ?, 'cell-a', 1, ?, ?, 0, 0, 0, 0, 0, 0)`, - [identity.userId, identity.relayHostId, now, now - ASSIGNMENT_LIMITS.dormantTtlMs] - ) - seeded.arm() - - await expect(store.assign(identity)).resolves.toMatchObject({ - cellId: 'cell-a', - assignmentEpoch: 1 - }) - expect( - await delegate.query( - `SELECT reserved_controls, reserved_splices FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ reserved_controls: 1, reserved_splices: 1 }]) - expect( - await delegate.query( - `SELECT activity_id FROM relay_assignment_activity_leases - ORDER BY activity_id ASC` - ) - ).toEqual([{ activity_id: 'control-pending:1' }, { activity_id: 'splice:connection-1' }]) - expect(await cellReservations(delegate)).toEqual({ 'cell-a': 2, 'cell-b': 0 }) - }) - - it('extends the lease of a control-holding host on a sticky grant', async () => { - let now = 100 - const store = await setup(() => now) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const assignment = await store.assign(identity) - await store.activateControl(identity, { - cellId: assignment.cellId, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - - now = 40_000 - await expect(store.assign(identity)).resolves.toMatchObject({ - cellId: assignment.cellId - }) - expect( - await database!.query( - `SELECT lease_expires_at, last_activity_at FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([ - { lease_expires_at: now + ASSIGNMENT_LIMITS.activityLeaseMs, last_activity_at: now } - ]) - }) - - // The old absolute write shortened a 15-minute migration lease to the 90s - // grant lease; only the touch's monotonic CASE keeps the longer one now. - it('never shortens a migration lease to the grant lease', async () => { - let now = 100 - const store = await setup(() => now) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const assignment = await store.assign(identity) - await store.activateControl(identity, { - cellId: assignment.cellId, - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - const before = await database!.query( - `SELECT lease_expires_at FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - expect(before).toEqual([{ lease_expires_at: 100 + ASSIGNMENT_LIMITS.migrationLeaseMs }]) - - now = 1000 - await expect(store.assign(identity)).resolves.toMatchObject({ cellId: 'cell-b' }) - expect( - await database!.query( - `SELECT lease_expires_at, last_activity_at FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([ - { lease_expires_at: 100 + ASSIGNMENT_LIMITS.migrationLeaseMs, last_activity_at: now } - ]) - }) - - it('moves an origin-scoped activity reservation without double counting', async () => { - const store = await setup( - () => 100, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - ) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await store.assign(identity) - await store.acquireActivity(identity, { - activityId: 'splice:connection-1', - kind: 'splice', - cellId: 'cell-a' - }) - await store.startEvacuation(identity, 'cell-b') - await store.acquireActivity(identity, { - activityId: 'splice:connection-1', - kind: 'splice', - cellId: 'cell-b' - }) - - expect(await cellReservations(database!)).toEqual({ 'cell-a': 1, 'cell-b': 6 }) - await expect(store.releaseActivity(identity, 'splice:connection-1')).resolves.toBe(true) - await expect(store.releaseActivity(identity, 'splice:connection-1')).resolves.toBe(false) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 1, 'cell-b': 4 }) - }) - - it('rejects a durable activity before it can exceed cell capacity', async () => { - const store = await setup( - () => 100, - [{ id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 2 }] - ) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await store.assign(identity) - - await expect( - store.acquireActivity(identity, { - activityId: 'splice:connection-1', - kind: 'splice', - cellId: 'cell-a' - }) - ).rejects.toThrow('relay_capacity_exhausted') - expect(await cellReservations(database!)).toEqual({ 'cell-a': 1 }) - }) - - it('moves active assignments target-first and completes only after source drain', async () => { - const store = await setup( - () => 100, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - ) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - - const migration = await store.startEvacuation(identity, 'cell-b') - expect(await store.startEvacuation(identity, 'cell-b')).toEqual(migration) - expect(migration).toMatchObject({ - sourceCellId: 'cell-a', - targetCellId: 'cell-b', - previousEpoch: 1, - assignmentEpoch: 2 - }) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 1, 'cell-b': 2 }) - - const targetControl = await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: 2, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { cellId: 'cell-b', assignmentEpoch: 2 }) - await expect(store.completeEvacuation(identity, 2)).rejects.toThrow( - 'migration_source_still_active' - ) - await store.releaseActivity(identity, sourceControl) - await store.completeEvacuation(identity, 2) - - expect(await cellReservations(database!)).toEqual({ 'cell-a': 0, 'cell-b': 1 }) - expect(await store.resolve(identity)).toMatchObject({ cellId: 'cell-b', assignmentEpoch: 2 }) - expect( - await database!.query( - `SELECT activity_id FROM relay_assignment_activity_leases ORDER BY activity_id` - ) - ).toEqual([{ activity_id: targetControl }]) - await expect( - store.acquireActivity(identity, { - activityId: 'splice:late-source', - kind: 'splice', - cellId: 'cell-a' - }) - ).rejects.toThrow('activity_cell_not_authoritative') - }) - - it('automatically completes only after the source runtime is freshly quiescent', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const store = await setupWithHeartbeats(() => now, cells) - await heartbeat(store, cells[0]!) - await heartbeat(store, cells[1]!) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - await store.releaseActivity(identity, sourceControl) - await store.setCellEnabled('cell-a', false) - await heartbeat(store, cells[0]!, { observedRequests: 1 }) - - expect(await store.completeReadyEvacuations()).toBe(0) - await heartbeat(store, cells[0]!, { observedRequests: 0 }) - now = 150 - await heartbeat(store, cells[1]!, { - incarnation: '22222222-2222-4222-8222-222222222222', - startedAt: 125 - }) - expect(await store.completeReadyEvacuations()).toBe(0) - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 2 - }) - expect(await store.completeReadyEvacuations()).toBe(1) - }) - - it('completes a fenced migration only after the source heartbeat is stale', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const store = await setupWithHeartbeats(() => now, cells) - await heartbeat(store, cells[0]!, { observedRequests: 1 }) - await heartbeat(store, cells[1]!) - await store.setCellEnabled('cell-b', false) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.setCellEnabled('cell-b', true) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - await store.releaseActivity(identity, sourceControl) - await store.setCellEnabled('cell-a', false) - - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', true)).toMatchObject({ - inProgress: 1, - blocked: 1 - }) - now += 45_001 - await heartbeat(store, cells[1]!) - await store.attestCellFence('cell-a', '11111111-1111-4111-8111-111111111111') - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', true)).toMatchObject({ - inProgress: 0, - completed: 1 - }) - }) - - it('blocks aggregate fenced completion on assignment accounting mismatch', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const store = await setupWithHeartbeats(() => now, cells) - await heartbeat(store, cells[0]!) - await heartbeat(store, cells[1]!) - await store.setCellEnabled('cell-b', false) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.setCellEnabled('cell-b', true) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - await store.releaseActivity(identity, sourceControl) - await store.setCellEnabled('cell-a', false) - await database!.query( - `UPDATE relay_assignments SET reserved_splices = reserved_splices + 1 - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - now += 45_001 - await heartbeat(store, cells[1]!) - await store.attestCellFence('cell-a', '11111111-1111-4111-8111-111111111111') - - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', true)).toMatchObject({ - inProgress: 1, - blocked: 1 - }) - }) - - it('blocks aggregate fenced completion on an unexpected third-cell lease', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 }, - { id: 'cell-c', url: 'https://relay-c.example.com', capacityRequests: 10 } - ] - const store = await setupWithHeartbeats(() => now, cells) - for (const cell of cells) await heartbeat(store, cell) - await store.setCellEnabled('cell-b', false) - await store.setCellEnabled('cell-c', false) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.setCellEnabled('cell-b', true) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - await store.releaseActivity(identity, sourceControl) - await store.setCellEnabled('cell-a', false) - await database!.query( - `INSERT INTO relay_assignment_activity_leases - (user_id, relay_host_id, activity_id, activity_kind, cell_id, - request_units, expires_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, - [ - identity.userId, - identity.relayHostId, - 'splice:unexpected-cell', - 'splice', - 'cell-c', - 2, - now + ASSIGNMENT_LIMITS.activityLeaseMs, - now - ] - ) - await database!.query( - `UPDATE relay_assignments SET reserved_splices = reserved_splices + 1 - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - await database!.query( - `UPDATE relay_cells SET reserved_requests = reserved_requests + 2 WHERE cell_id = ?`, - ['cell-c'] - ) - now += 45_001 - await heartbeat(store, cells[1]!) - await store.attestCellFence('cell-a', '11111111-1111-4111-8111-111111111111') - - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', true)).toMatchObject({ - inProgress: 1, - blocked: 1 - }) - }) - - it('rolls back an unregistered expired evacuation with a strictly newer epoch', async () => { - let now = 100 - const store = await setup( - () => now, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - ) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.startEvacuation(identity, 'cell-b') - - now += ASSIGNMENT_LIMITS.migrationLeaseMs + 1 - expect(await store.abortExpiredEvacuations()).toBe(1) - expect(await store.resolve(identity)).toMatchObject({ cellId: 'cell-a', assignmentEpoch: 3 }) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 1, 'cell-b': 0 }) - }) - // Disabled registered targets satisfy neither completion nor expiry rollback, stranding migration rows. async function wedgeRegisteredMigration( now: () => number, @@ -2482,238 +253,20 @@ describe('RelayAssignmentStore', () => { cellId: 'cell-b', assignmentEpoch: migration.assignmentEpoch }) - if (releaseSourceControl) await store.releaseActivity(identity, sourceControl) - if (disableSource) await store.setCellEnabled('cell-a', false) + if (releaseSourceControl) { + await store.releaseActivity(identity, sourceControl) + } + if (disableSource) { + await store.setCellEnabled('cell-a', false) + } // The desktop leaves the half-migrated target, then an operator disables that cell. await store.releaseActivity(identity, targetControl) - if (disableTarget) await store.setCellEnabled('cell-b', false) + if (disableTarget) { + await store.setCellEnabled('cell-b', false) + } return { store, identity } } - async function insertReservedControlConnection( - identity: { userId: string; relayHostId: string }, - cellId: string, - assignmentEpoch: number, - now: number - ): Promise { - await database!.query( - `INSERT INTO relay_control_connection_reservations - (reservation_id, idempotency_key, user_id, relay_host_id, assignment_epoch, - cell_id, state, created_at, timeout_at, updated_at) - VALUES ('abandoned-reservation', 'abandoned-key', ?, ?, ?, ?, 'reserved', ?, ?, ?)`, - [identity.userId, identity.relayHostId, assignmentEpoch, cellId, now, now + 60_000, now] - ) - } - - it('reaps an expired migration whose registered target cell was disabled', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const { store, identity } = await wedgeRegisteredMigration(() => now, cells) - - now += ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - // A disabled target can never satisfy completion, so waiting cannot help. - expect(await store.completeReadyEvacuations()).toBe(0) - expect(await store.abortExpiredEvacuations()).toBe(1) - // Rollback to disabled source resolves empty for evacuateDeadCells to re-place; retire the row rather than revisit every tick. - expect(await store.resolve(identity)).toBeNull() - expect(await store.abortExpiredEvacuations()).toBe(0) - }) - - it('leaves a freshly disabled target for supersede-target to recover', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const { store } = await wedgeRegisteredMigration(() => now, cells) - - // Expired, but a disabled target is what supersede-target itself creates, so the operator - // window must stay open; aborting here would fail their run with migration_already_superseded. - now += ASSIGNMENT_LIMITS.migrationLeaseMs + 1 - expect(await store.abortExpiredEvacuations()).toBe(0) - - now += STRANDED_MIGRATION_ABANDON_MS - expect(await store.abortExpiredEvacuations()).toBe(1) - }) - - it('rolls an abandoned disabled target back while its source remains active', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const { store, identity } = await wedgeRegisteredMigration(() => now, cells, true, false, false) - - now += ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - expect(await store.abortExpiredEvacuations()).toBe(1) - expect( - await database!.query( - `SELECT cell_id, assignment_epoch FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ cell_id: 'cell-a', assignment_epoch: 3 }]) - expect( - await database!.query( - `SELECT completed_at, aborted_at FROM relay_assignment_migrations - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ completed_at: null, aborted_at: now }]) - }) - - it('starts the abandon window when an old migration target is disabled', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const { store } = await wedgeRegisteredMigration(() => now, cells, false, false) - now += ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - - await store.setCellEnabled('cell-b', false) - expect(await store.abortExpiredEvacuations()).toBe(0) - - now += STRANDED_MIGRATION_ABANDON_MS + 1 - expect(await store.abortExpiredEvacuations()).toBe(1) - }) - - it('reaps an expired migration from a retired source when its target control is gone', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const { store, identity } = await wedgeRegisteredMigration(() => now, cells, false) - await applyGenerationZeroSelector(store, { - attemptId: 'retired_source_migration_target', - membership: { - existingOnly: ['cell-a'], - migrationOnly: ['cell-b'], - general: [] - } - }) - await insertReservedControlConnection(identity, 'cell-b', 2, now) - - now += ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - expect(await store.abortExpiredEvacuations()).toBe(1) - expect( - await database!.query( - `SELECT assignment.cell_id, assignment.assignment_epoch, - migration.completed_at, migration.aborted_at - FROM relay_assignments assignment - JOIN relay_assignment_migrations migration - ON migration.user_id = assignment.user_id - AND migration.relay_host_id = assignment.relay_host_id - WHERE assignment.user_id = ? AND assignment.relay_host_id = ? - AND migration.assignment_epoch = ?`, - [identity.userId, identity.relayHostId, 2] - ) - ).toEqual([ - { - cell_id: 'cell-b', - assignment_epoch: 2, - completed_at: now, - aborted_at: null - } - ]) - expect( - await database!.query( - `SELECT reserved_controls, migration_leases FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ reserved_controls: 0, migration_leases: 0 }]) - expect( - await database!.query( - `SELECT activity_id FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([]) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 0, 'cell-b': 0 }) - expect( - await database!.query( - `SELECT state FROM relay_control_connection_reservations - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ state: 'released' }]) - }) - - it('reaps a retired-side migration with only a pending target control', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const store = await setupWithHeartbeats(() => now, cells) - await heartbeat(store, cells[0]!) - await heartbeat(store, cells[1]!) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - await store.releaseActivity(identity, sourceControl) - await applyGenerationZeroSelector(store, { - attemptId: 'retired_source_pending_target', - membership: { - existingOnly: ['cell-a'], - migrationOnly: ['cell-b'], - general: [] - } - }) - await insertReservedControlConnection(identity, 'cell-b', migration.assignmentEpoch, now) - - now += ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - await database!.query( - `UPDATE relay_assignment_activity_leases SET expires_at = ? - WHERE user_id = ? AND relay_host_id = ? AND activity_id = ?`, - [now, identity.userId, identity.relayHostId, `control-pending:${migration.assignmentEpoch}`] - ) - expect(await store.abortExpiredEvacuations()).toBe(1) - expect( - await database!.query( - `SELECT cell_id, assignment_epoch FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ cell_id: 'cell-b', assignment_epoch: migration.assignmentEpoch }]) - expect( - await database!.query( - `SELECT reserved_controls, migration_leases FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ reserved_controls: 0, migration_leases: 0 }]) - expect( - await database!.query( - `SELECT activity_id FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([]) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 0, 'cell-b': 0 }) - expect( - await database!.query( - `SELECT state FROM relay_control_connection_reservations - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ state: 'released' }]) - }) - it('preserves a fresh target grant created after abandoned migration selection', async () => { let now = 100 const cells: RelayCellConfig[] = [ @@ -2794,1470 +347,6 @@ describe('RelayAssignmentStore', () => { ) ).toEqual([{ completed_at: null }]) }) - - it('keeps an abandoned target migration open while its source is still active', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const { store, identity } = await wedgeRegisteredMigration(() => now, cells, false, true, false) - await applyGenerationZeroSelector(store, { - attemptId: 'retired_source_active', - membership: { - existingOnly: ['cell-a'], - migrationOnly: ['cell-b'], - general: [] - } - }) - - now += ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - expect(await store.abortExpiredEvacuations()).toBe(0) - expect( - await database!.query( - `SELECT completed_at, aborted_at FROM relay_assignment_migrations - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ completed_at: null, aborted_at: null }]) - }) - - it('starts the abandon window when an old migration source is retired', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const { store } = await wedgeRegisteredMigration(() => now, cells, false, false) - now += ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - - await store.setCellEnabled('cell-a', false) - expect(await store.abortExpiredEvacuations()).toBe(0) - - now += STRANDED_MIGRATION_ABANDON_MS + 1 - expect(await store.abortExpiredEvacuations()).toBe(1) - }) - - it('reaps after an old source migration lease is refreshed and expires', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const { store } = await wedgeRegisteredMigration(() => now, cells, false) - await applyGenerationZeroSelector(store, { - attemptId: 'retired_source_refreshed_lease', - membership: { - existingOnly: ['cell-a'], - migrationOnly: ['cell-b'], - general: [] - } - }) - now += STRANDED_MIGRATION_ABANDON_MS + ASSIGNMENT_LIMITS.migrationLeaseMs + 1 - await database!.query(`UPDATE relay_assignment_migrations SET expires_at = ?`, [now - 1]) - - expect(await store.abortExpiredEvacuations()).toBe(1) - }) - - it('keeps a freshly retired target open despite an old retired source', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const { store } = await wedgeRegisteredMigration(() => now, cells, false) - now += ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - - await store.setCellEnabled('cell-b', false) - expect(await store.abortExpiredEvacuations()).toBe(0) - - now += STRANDED_MIGRATION_ABANDON_MS + 1 - expect(await store.abortExpiredEvacuations()).toBe(1) - }) - - it('fails supersession closed when reaping wins after selection', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 }, - { id: 'cell-c', url: 'https://relay-c.example.com', capacityRequests: 10 } - ] - const { store } = await wedgeRegisteredMigration(() => now, cells) - now += ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - const query = database!.query.bind(database) - vi.spyOn(database!, 'query').mockImplementationOnce(async (sql, params) => { - const rows = await query(sql, params) - expect(await store.abortExpiredEvacuations()).toBe(1) - return rows - }) - - await expect( - store.supersedeRegisteredCellEvacuations('cell-a', 'cell-b', 'cell-c', 100) - ).rejects.toThrow('migration_already_superseded') - }) - - it('fails supersession closed when reaping wins after preparation', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 }, - { id: 'cell-c', url: 'https://relay-c.example.com', capacityRequests: 10 } - ] - const { store } = await wedgeRegisteredMigration(() => now, cells) - now += ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - await store.attestCellFence('cell-b', '11111111-1111-4111-8111-111111111111') - const supersede = store.supersedeRegisteredEvacuation.bind(store) - vi.spyOn(store, 'supersedeRegisteredEvacuation').mockImplementationOnce(async (...args) => { - expect(await store.abortExpiredEvacuations()).toBe(1) - return await supersede(...args) - }) - - await expect( - store.supersedeRegisteredCellEvacuations('cell-a', 'cell-b', 'cell-c', 100) - ).rejects.toThrow('migration_already_superseded') - }) - - it('fails supersession closed when reaping wins before an accounting retry', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 }, - { id: 'cell-c', url: 'https://relay-c.example.com', capacityRequests: 10 } - ] - const { store } = await wedgeRegisteredMigration(() => now, cells) - now += ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - await heartbeat(store, cells[0]!) - await heartbeat(store, cells[2]!) - await store.attestCellFence('cell-b', '11111111-1111-4111-8111-111111111111') - await database!.query(`UPDATE relay_cells SET reserved_requests = 1 WHERE cell_id = ?`, [ - 'cell-c' - ]) - const supersede = store.supersedeRegisteredEvacuation.bind(store) - let attempts = 0 - vi.spyOn(store, 'supersedeRegisteredEvacuation').mockImplementation(async (...args) => { - attempts++ - if (attempts === 2) expect(await store.abortExpiredEvacuations()).toBe(1) - return await supersede(...args) - }) - - await expect( - store.supersedeRegisteredCellEvacuations('cell-a', 'cell-b', 'cell-c', 100) - ).rejects.toThrow('migration_already_superseded') - expect(attempts).toBe(2) - }) - - it('reaps a pinned expired migration once its target cell is disabled', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - const { store, identity } = await wedgeRegisteredMigration(() => now, cells) - // Drains pin their migrations and nothing ever deletes a pin, so the pin outlives the drain. - await database!.query( - `INSERT INTO relay_post_drain_migration_pins - (user_id, relay_host_id, assignment_epoch, drain_attempt_id, source_cell_id, - source_cell_incarnation, target_cell_id, target_cell_incarnation, - source_request_units, target_reserved_units, pinned_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - [ - identity.userId, - identity.relayHostId, - 2, - 'attempt-0000', - 'cell-a', - '11111111-1111-4111-8111-111111111111', - 'cell-b', - '11111111-1111-4111-8111-111111111111', - 1, - 1, - now - ] - ) - - now += ASSIGNMENT_LIMITS.migrationLeaseMs + STRANDED_MIGRATION_ABANDON_MS + 1 - expect(await store.completeReadyEvacuations()).toBe(0) - expect(await store.abortExpiredEvacuations()).toBe(1) - expect(await store.abortExpiredEvacuations()).toBe(0) - }) - - it('repairs an expired migration marker from its exact active target control', async () => { - let now = 100 - const store = await setup( - () => now, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - ) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: 2, - generation: 1 - }) - - now += ASSIGNMENT_LIMITS.migrationLeaseMs + 1 - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: 2, - generation: 1 - }) - expect(await store.abortExpiredEvacuations()).toBe(0) - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', false)).toEqual({ - inProgress: 1, - oldestExpiresAt: 100 + ASSIGNMENT_LIMITS.migrationLeaseMs, - oldestRemainingMs: -1, - targetRegistered: 1, - registeredSourceActive: 1, - registeredCompletable: 0, - registeredTargetInactive: 0, - completed: 0, - blocked: 0, - ...NO_EXPIRED_EVACUATION_DIAGNOSTICS - }) - await store.releaseActivity(identity, sourceControl) - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', true)).toEqual({ - inProgress: 0, - ...NO_ACTIVE_MIGRATION_LEASE, - targetRegistered: 0, - ...NO_REGISTERED_EVACUATION_DIAGNOSTICS, - completed: 1, - blocked: 0, - ...NO_EXPIRED_EVACUATION_DIAGNOSTICS - }) - expect(await store.resolve(identity)).toMatchObject({ cellId: 'cell-b', assignmentEpoch: 2 }) - }) - - it('keeps a registered migration pending while its proven target control is offline', async () => { - let now = 100 - const store = await setup( - () => now, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - ) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - const migration = await store.startEvacuation(identity, 'cell-b') - const targetControl = await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 2 - }) - expect( - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - ).toBe(true) - expect(await store.completeReadyEvacuations()).toBe(0) - await store.releaseActivity(identity, sourceControl) - now += ASSIGNMENT_LIMITS.activityLeaseMs + 1 - expect(await store.completeReadyEvacuations()).toBe(0) - await expect(store.completeEvacuation(identity, migration.assignmentEpoch)).rejects.toThrow( - 'migration_target_not_active' - ) - await store.releaseActivity(identity, targetControl) - expect(await store.completeReadyEvacuations()).toBe(0) - - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', true)).toEqual({ - inProgress: 1, - oldestExpiresAt: 100 + ASSIGNMENT_LIMITS.migrationLeaseMs, - oldestRemainingMs: ASSIGNMENT_LIMITS.migrationLeaseMs - ASSIGNMENT_LIMITS.activityLeaseMs - 1, - targetRegistered: 1, - registeredSourceActive: 0, - registeredCompletable: 0, - registeredTargetInactive: 1, - completed: 0, - blocked: 1, - ...NO_EXPIRED_EVACUATION_DIAGNOSTICS - }) - - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 3 - }) - expect(await store.completeReadyEvacuations()).toBe(1) - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', false)).toEqual({ - inProgress: 0, - ...NO_ACTIVE_MIGRATION_LEASE, - targetRegistered: 0, - ...NO_REGISTERED_EVACUATION_DIAGNOSTICS, - completed: 0, - blocked: 0, - ...NO_EXPIRED_EVACUATION_DIAGNOSTICS - }) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 0, 'cell-b': 1 }) - }) - - it('completes a registered migration after its disabled source is proven dead', async () => { - let now = 100 - const store = await setupWithHeartbeats( - () => now, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - ) - await heartbeat(store, { - id: 'cell-a', - url: 'https://relay-a.example.com', - capacityRequests: 10 - }) - await heartbeat(store, { - id: 'cell-b', - url: 'https://relay-b.example.com', - capacityRequests: 10 - }) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.setCellEnabled('cell-a', false) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - await store.releaseActivity(identity, sourceControl) - now += 45_001 - await heartbeat( - store, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 }, - { startedAt: 50 } - ) - await store.attestCellFence('cell-a', '11111111-1111-4111-8111-111111111111') - - const input = { - assignmentEpoch: migration.assignmentEpoch, - sourceCellId: 'cell-a', - targetCellId: 'cell-b' - } - await expect(store.completeEvacuationFromDeadSource(identity, input)).resolves.toEqual({ - changed: true, - assignmentEpoch: 2, - sourceCellId: 'cell-a', - targetCellId: 'cell-b' - }) - await expect(store.completeEvacuationFromDeadSource(identity, input)).resolves.toEqual({ - changed: false, - assignmentEpoch: 2, - sourceCellId: 'cell-a', - targetCellId: 'cell-b' - }) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 0, 'cell-b': 1 }) - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', false)).toMatchObject({ - inProgress: 0 - }) - }) - - it('retires an inactive registered migration after its source is proven dead', async () => { - let now = 100 - const cells = [ - { - id: 'cell-a', - url: 'https://relay-a.example.com', - capacityRequests: 10, - connectionHardCap: 600 as const, - connectionUnobservedBound: 50 - }, - { - id: 'cell-b', - url: 'https://relay-b.example.com', - capacityRequests: 10, - connectionHardCap: 600 as const, - connectionUnobservedBound: 50 - } - ] - const store = await setupWithHeartbeats(() => now, cells) - await heartbeat(store, cells[0]!) - await heartbeat(store, cells[1]!) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.setCellEnabled('cell-a', false) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - await store.releaseActivity(identity, sourceControl) - now += 45_001 - await heartbeat(store, cells[1]!, { startedAt: 50 }) - await store.attestCellFence('cell-a', '11111111-1111-4111-8111-111111111111') - - await expect(store.cellEvacuationStatus('cell-a', 'cell-b', true)).resolves.toMatchObject({ - inProgress: 0, - completed: 1, - blocked: 0 - }) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 0, 'cell-b': 0 }) - expect( - await database!.query( - `SELECT activity_id FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([]) - expect( - await database!.query( - `SELECT state FROM relay_control_connection_reservations - WHERE user_id = ? AND relay_host_id = ? AND cell_id = ? AND assignment_epoch = ?`, - [identity.userId, identity.relayHostId, 'cell-b', migration.assignmentEpoch] - ) - ).toEqual([{ state: 'released' }]) - expect( - await database!.query( - `SELECT cell_id, assignment_epoch, reserved_controls, migration_leases - FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([ - { - cell_id: 'cell-b', - assignment_epoch: 2, - reserved_controls: 0, - migration_leases: 0 - } - ]) - }) - - it.each(['expired', 'previous-incarnation'] as const)( - 'retires a registered migration and its %s target control after the source dies', - async (targetControlState) => { - let now = 100 - const cells = [ - { - id: 'cell-a', - url: 'https://relay-a.example.com', - capacityRequests: 10, - connectionHardCap: 600 as const, - connectionUnobservedBound: 50 - }, - { - id: 'cell-b', - url: 'https://relay-b.example.com', - capacityRequests: 10, - connectionHardCap: 600 as const, - connectionUnobservedBound: 50 - } - ] - const store = await setupWithHeartbeats(() => now, cells) - await heartbeat(store, cells[0]!) - await heartbeat(store, cells[1]!) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.setCellEnabled('cell-a', false) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - await store.releaseActivity(identity, sourceControl) - now += targetControlState === 'expired' ? ASSIGNMENT_LIMITS.activityLeaseMs + 1 : 45_001 - await heartbeat(store, cells[1]!, { - startedAt: targetControlState === 'previous-incarnation' ? now - 1 : 50, - incarnation: - targetControlState === 'previous-incarnation' - ? '22222222-2222-4222-8222-222222222222' - : '11111111-1111-4111-8111-111111111111' - }) - await store.attestCellFence('cell-a', '11111111-1111-4111-8111-111111111111') - - await expect(store.cellEvacuationStatus('cell-a', 'cell-b', false)).resolves.toMatchObject({ - inProgress: 1, - registeredCompletable: 0, - registeredTargetInactive: 1 - }) - await expect(store.cellEvacuationStatus('cell-a', 'cell-b', true)).resolves.toMatchObject({ - inProgress: 0, - completed: 1, - blocked: 0 - }) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 0, 'cell-b': 0 }) - expect( - await database!.query( - `SELECT activity_id FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([]) - expect( - await database!.query( - `SELECT cell_id, assignment_epoch, reserved_controls, migration_leases - FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([ - { - cell_id: 'cell-b', - assignment_epoch: migration.assignmentEpoch, - reserved_controls: 0, - migration_leases: 0 - } - ]) - } - ) - - it('refuses dead-source completion while the source heartbeat is fresh', async () => { - const store = await setupWithHeartbeats( - () => 100, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - ) - await heartbeat(store, { - id: 'cell-a', - url: 'https://relay-a.example.com', - capacityRequests: 10 - }) - await heartbeat(store, { - id: 'cell-b', - url: 'https://relay-b.example.com', - capacityRequests: 10 - }) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.setCellEnabled('cell-a', false) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - await store.releaseActivity(identity, sourceControl) - - await expect( - store.attestCellFence('cell-a', '11111111-1111-4111-8111-111111111111') - ).rejects.toThrow('cell_fence_runtime_not_stale') - await expect( - store.completeEvacuationFromDeadSource(identity, { - assignmentEpoch: migration.assignmentEpoch, - sourceCellId: 'cell-a', - targetCellId: 'cell-b' - }) - ).rejects.toThrow('cell_fence_attestation_missing') - expect(await cellReservations(database!)).toEqual({ 'cell-a': 0, 'cell-b': 2 }) - }) - - it('supersedes a registered migration after its disabled target is proven unavailable', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 }, - { id: 'cell-c', url: 'https://relay-c.example.com', capacityRequests: 10 } - ] - const store = await setupWithHeartbeats(() => now, cells) - for (const cell of cells) await heartbeat(store, cell) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.setCellEnabled('cell-a', false) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - await database!.query( - `INSERT INTO relay_control_connection_reservations - (reservation_id, idempotency_key, user_id, relay_host_id, - assignment_epoch, cell_id, state, inclusion_watermark, - claim_activity_id, created_at, timeout_at, claimed_at, released_at, - updated_at) - VALUES (?, ?, ?, ?, ?, ?, 'late-arrival-debt', NULL, NULL, ?, ?, NULL, NULL, ?)`, - [ - 'superseded-reservation', - 'superseded-reservation', - identity.userId, - identity.relayHostId, - migration.assignmentEpoch, - 'cell-b', - 100, - 100, - 100 - ] - ) - await store.setCellEnabled('cell-b', false) - now += 45_001 - await heartbeat(store, cells[0]!, { startedAt: 50 }) - await heartbeat(store, cells[2]!, { startedAt: 50 }) - await store.attestCellFence('cell-b', '11111111-1111-4111-8111-111111111111') - const input = { - assignmentEpoch: migration.assignmentEpoch, - sourceCellId: 'cell-a', - currentTargetCellId: 'cell-b', - replacementTargetCellId: 'cell-c' - } - - const replacement = await store.supersedeRegisteredEvacuation(identity, input) - expect(replacement).toMatchObject({ - sourceCellId: 'cell-a', - targetCellId: 'cell-c', - previousEpoch: 2, - assignmentEpoch: 3 - }) - await expect(store.supersedeRegisteredEvacuation(identity, input)).resolves.toEqual(replacement) - expect(await store.resolve(identity)).toMatchObject({ cellId: 'cell-c', assignmentEpoch: 3 }) - expect( - await database!.query( - `SELECT state FROM relay_control_connection_reservations - WHERE reservation_id = ?`, - ['superseded-reservation'] - ) - ).toEqual([{ state: 'released' }]) - expect(await cellReservations(database!)).toEqual({ - 'cell-a': 1, - 'cell-b': 0, - 'cell-c': 2 - }) - expect( - await database!.query( - `SELECT activity_kind, cell_id FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ? ORDER BY cell_id, activity_id`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([ - { activity_kind: 'control', cell_id: 'cell-a' }, - { activity_kind: 'control', cell_id: 'cell-c' }, - { activity_kind: 'migration', cell_id: 'cell-c' } - ]) - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', false)).toMatchObject({ - inProgress: 0 - }) - expect(await store.cellEvacuationStatus('cell-a', 'cell-c', false)).toMatchObject({ - inProgress: 1 - }) - }) - - it('reconciles durable cell accounting once before aggregate supersession', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 }, - { id: 'cell-c', url: 'https://relay-c.example.com', capacityRequests: 10 } - ] - const store = await setupWithHeartbeats(() => now, cells) - for (const cell of cells) await heartbeat(store, cell) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.setCellEnabled('cell-a', false) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - await store.setCellEnabled('cell-b', false) - now += 45_001 - await heartbeat(store, cells[0]!, { startedAt: 50 }) - await heartbeat(store, cells[2]!, { startedAt: 50 }) - await store.attestCellFence('cell-b', '11111111-1111-4111-8111-111111111111') - await database!.query( - `UPDATE relay_cells - SET reserved_requests = CASE WHEN cell_id = ? THEN 1 ELSE 0 END - WHERE cell_id IN (?, ?)`, - ['cell-c', 'cell-a', 'cell-c'] - ) - - await expect( - store.supersedeRegisteredCellEvacuations('cell-a', 'cell-b', 'cell-c', 100) - ).resolves.toBe(1) - expect(await cellReservations(database!)).toEqual({ - 'cell-a': 1, - 'cell-b': 0, - 'cell-c': 2 - }) - expect( - await database!.query( - `SELECT assignment_epoch, target_cell_id, aborted_at - FROM relay_assignment_migrations - WHERE user_id = ? ORDER BY assignment_epoch`, - [identity.userId] - ) - ).toEqual([ - { assignment_epoch: 2, target_cell_id: 'cell-b', aborted_at: 45_101 }, - { assignment_epoch: 3, target_cell_id: 'cell-c', aborted_at: null } - ]) - }) - - it('preserves healthy third-cell activity during aggregate supersession', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 }, - { id: 'cell-c', url: 'https://relay-c.example.com', capacityRequests: 10 }, - { id: 'cell-d', url: 'https://relay-d.example.com', capacityRequests: 10 } - ] - const store = await setupWithHeartbeats(() => now, cells) - for (const cell of cells) await heartbeat(store, cell) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.setCellEnabled('cell-a', false) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - await database!.query( - `UPDATE relay_assignment_activity_leases SET cell_id = ? - WHERE user_id = ? AND relay_host_id = ? AND activity_id = ?`, - ['cell-d', identity.userId, identity.relayHostId, sourceControl] - ) - await database!.query(`UPDATE relay_cells SET reserved_requests = ? WHERE cell_id = ?`, [ - 5, - 'cell-c' - ]) - await store.setCellEnabled('cell-b', false) - now += 45_001 - await heartbeat(store, cells[0]!, { startedAt: 50 }) - await heartbeat(store, cells[2]!, { startedAt: 50 }) - await heartbeat(store, cells[3]!, { startedAt: 50 }) - await store.attestCellFence('cell-b', '11111111-1111-4111-8111-111111111111') - - await expect( - store.supersedeRegisteredCellEvacuations('cell-a', 'cell-b', 'cell-c', 100) - ).resolves.toBe(1) - expect(await cellReservations(database!)).toEqual({ - 'cell-a': 0, - 'cell-b': 0, - 'cell-c': 1, - 'cell-d': 1 - }) - expect( - await database!.query( - `SELECT activity_kind, cell_id FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ? ORDER BY cell_id, activity_id`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([ - { activity_kind: 'control', cell_id: 'cell-c' }, - { activity_kind: 'migration', cell_id: 'cell-c' }, - { activity_kind: 'control', cell_id: 'cell-d' } - ]) - }) - - it('refuses supersession while the registered target remains available', async () => { - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 }, - { id: 'cell-c', url: 'https://relay-c.example.com', capacityRequests: 10 } - ] - const store = await setupWithHeartbeats(() => 100, cells) - for (const cell of cells) await heartbeat(store, cell) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.setCellEnabled('cell-a', false) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - await store.setCellEnabled('cell-b', false) - - await expect( - store.attestCellFence('cell-b', '11111111-1111-4111-8111-111111111111') - ).rejects.toThrow('cell_fence_runtime_not_stale') - await expect( - store.supersedeRegisteredEvacuation(identity, { - assignmentEpoch: migration.assignmentEpoch, - sourceCellId: 'cell-a', - currentTargetCellId: 'cell-b', - replacementTargetCellId: 'cell-c' - }) - ).rejects.toThrow('cell_fence_attestation_missing') - expect( - await database!.query( - `SELECT cell_id, assignment_epoch FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ cell_id: 'cell-b', assignment_epoch: 2 }]) - }) - - it('serializes concurrent retries of registered migration supersession', async () => { - let now = 100 - const cells = [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 }, - { id: 'cell-c', url: 'https://relay-c.example.com', capacityRequests: 10 } - ] - const store = await setupWithHeartbeats(() => now, cells) - for (const cell of cells) await heartbeat(store, cell) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.setCellEnabled('cell-a', false) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - await store.setCellEnabled('cell-b', false) - now += 45_001 - await heartbeat(store, cells[0]!, { startedAt: 50 }) - await heartbeat(store, cells[2]!, { startedAt: 50 }) - await store.attestCellFence('cell-b', '11111111-1111-4111-8111-111111111111') - const input = { - assignmentEpoch: migration.assignmentEpoch, - sourceCellId: 'cell-a', - currentTargetCellId: 'cell-b', - replacementTargetCellId: 'cell-c' - } - - const results = await Promise.all([ - store.supersedeRegisteredEvacuation(identity, input), - store.supersedeRegisteredEvacuation(identity, input) - ]) - expect(results[0]).toEqual(results[1]) - expect( - await database!.query( - `SELECT assignment_epoch FROM relay_assignment_migrations - WHERE user_id = ? AND relay_host_id = ? ORDER BY assignment_epoch`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ assignment_epoch: 2 }, { assignment_epoch: 3 }]) - expect(await cellReservations(database!)).toEqual({ - 'cell-a': 1, - 'cell-b': 0, - 'cell-c': 2 - }) - }) - - it('does not complete a registered migration after the assignment epoch advances', async () => { - const store = await setup( - () => 100, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 20 } - ] - ) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - const migration = await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: migration.assignmentEpoch - }) - await store.releaseActivity(identity, sourceControl) - await database!.query( - `UPDATE relay_assignments SET assignment_epoch = ? - WHERE user_id = ? AND relay_host_id = ?`, - [migration.assignmentEpoch + 1, identity.userId, identity.relayHostId] - ) - - expect(await store.completeReadyEvacuations()).toBe(0) - await expect(store.completeEvacuation(identity, migration.assignmentEpoch)).rejects.toThrow( - 'migration_assignment_mismatch' - ) - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', false)).toMatchObject({ - inProgress: 1, - targetRegistered: 1 - }) - }) - - it('retires an expired migration without rewriting its newer target assignment', async () => { - let now = 100 - const store = await setup( - () => now, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 20 } - ] - ) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: 2, - generation: 1 - }) - await database!.query( - `UPDATE relay_assignments SET assignment_epoch = ? - WHERE user_id = ? AND relay_host_id = ?`, - [3, identity.userId, identity.relayHostId] - ) - - now += ASSIGNMENT_LIMITS.migrationLeaseMs + 1 - expect(await store.abortExpiredEvacuations()).toBe(1) - expect(await store.resolve(identity)).toMatchObject({ - cellId: 'cell-b', - assignmentEpoch: 3 - }) - expect( - await database!.query( - `SELECT activity_id FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ? ORDER BY activity_id`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([{ activity_id: 'control:cell-a:1' }, { activity_id: 'control:cell-b:1' }]) - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', false)).toMatchObject({ - inProgress: 0 - }) - }) - - it.each([ - { assignmentEpoch: 1, removeAssignment: false, expected: 'migration_assignment_mismatch' }, - { assignmentEpoch: 2, removeAssignment: true, expected: 'migration_assignment_missing' } - ])( - 'fails closed when expired migration assignment state is not superseding: $expected', - async ({ assignmentEpoch, removeAssignment, expected }) => { - let now = 100 - const store = await setup( - () => now, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 20 } - ] - ) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await store.assign(identity) - await store.startEvacuation(identity, 'cell-b') - if (removeAssignment) { - await database!.query( - `DELETE FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - } else { - await database!.query( - `UPDATE relay_assignments SET assignment_epoch = ? - WHERE user_id = ? AND relay_host_id = ?`, - [assignmentEpoch, identity.userId, identity.relayHostId] - ) - } - - now += ASSIGNMENT_LIMITS.migrationLeaseMs + 1 - await expect(store.abortExpiredEvacuations()).rejects.toThrow(expected) - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', false)).toMatchObject({ - inProgress: 1, - targetRegistered: 0 - }) - } - ) - - it('reconciles duplicated assignment counters and cell reservations after evacuation', async () => { - const store = await setup( - () => 100, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 20 } - ] - ) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const sourceControl = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await store.startEvacuation(identity, 'cell-b') - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: 2, - generation: 1 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: 2 - }) - await store.releaseActivity(identity, sourceControl) - await database!.query( - `UPDATE relay_assignments SET reserved_controls = 9, reserved_splices = 4, - reserved_invites = 3, pending_installs = 2, pending_confirmations = 2, - migration_leases = 7 WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - await database!.query( - `UPDATE relay_cells SET reserved_requests = - CASE WHEN cell_id = ? THEN 11 ELSE 3 END`, - ['cell-a'] - ) - - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', true)).toEqual({ - inProgress: 0, - ...NO_ACTIVE_MIGRATION_LEASE, - targetRegistered: 0, - ...NO_REGISTERED_EVACUATION_DIAGNOSTICS, - completed: 1, - blocked: 0, - ...NO_EXPIRED_EVACUATION_DIAGNOSTICS - }) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 0, 'cell-b': 1 }) - expect( - await database!.query( - `SELECT reserved_controls, reserved_splices, reserved_invites, - pending_installs, pending_confirmations, migration_leases - FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - ) - ).toEqual([ - { - reserved_controls: 1, - reserved_splices: 0, - reserved_invites: 0, - pending_installs: 0, - pending_confirmations: 0, - migration_leases: 0 - } - ]) - }) - - it('refuses reservation reconciliation when an activity lease has no assignment', async () => { - const store = await setup( - () => 100, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 20 } - ] - ) - await database!.query( - `INSERT INTO relay_assignment_activity_leases - (user_id, relay_host_id, activity_id, activity_kind, cell_id, - request_units, expires_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, - ['orphan-user', 'orphanhost000001', 'control:orphan', 'control', 'cell-a', 1, 200, 100] - ) - - await expect(store.cellEvacuationStatus('cell-a', 'cell-b', true)).rejects.toThrow( - 'activity_lease_assignment_missing' - ) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 0, 'cell-b': 0 }) - }) - - it('refuses reservation reconciliation when an activity lease names no cell', async () => { - const store = await setup( - () => 100, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 20 } - ] - ) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - await store.assign(identity) - await database!.query( - `INSERT INTO relay_assignment_activity_leases - (user_id, relay_host_id, activity_id, activity_kind, cell_id, - request_units, expires_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, - [ - identity.userId, - identity.relayHostId, - 'splice:missing-cell', - 'splice', - 'missing-cell', - 2, - 200, - 100 - ] - ) - - await expect(store.cellEvacuationStatus('cell-a', 'cell-b', true)).rejects.toThrow( - 'activity_lease_cell_missing' - ) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 1, 'cell-b': 0 }) - }) - - it('leaves accounting for cells outside the selected evacuation pair unchanged', async () => { - const store = await setup( - () => 100, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 20 }, - { id: 'cell-c', url: 'https://relay-c.example.com', capacityRequests: 20 } - ] - ) - await database!.query( - `INSERT INTO relay_assignments - (user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, - last_activity_at, reserved_controls, reserved_splices, reserved_invites, - pending_installs, pending_confirmations, migration_leases) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, - ['unrelated-user', 'unrelatedhost001', 'cell-c', 1, 200, 100, 9, 0, 0, 0, 0, 0] - ) - await database!.query( - `INSERT INTO relay_assignment_activity_leases - (user_id, relay_host_id, activity_id, activity_kind, cell_id, - request_units, expires_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, - ['unrelated-user', 'unrelatedhost001', 'control:unrelated', 'control', 'cell-c', 1, 200, 100] - ) - await database!.query(`UPDATE relay_cells SET reserved_requests = 9 WHERE cell_id = ?`, [ - 'cell-c' - ]) - - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', true)).toMatchObject({ - inProgress: 0 - }) - expect(await cellReservations(database!)).toEqual({ - 'cell-a': 0, - 'cell-b': 0, - 'cell-c': 9 - }) - expect( - await database!.query( - `SELECT reserved_controls FROM relay_assignments - WHERE user_id = ? AND relay_host_id = ?`, - ['unrelated-user', 'unrelatedhost001'] - ) - ).toEqual([{ reserved_controls: 9 }]) - }) - - it('rebalances only a fully inactive assignment after the dormant TTL', async () => { - let now = 100 - const store = await setup( - () => now, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - ) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const first = await store.assign(identity) - const control = await store.activateControl(identity, { - cellId: first.cellId, - assignmentEpoch: first.assignmentEpoch, - generation: 1 - }) - await expect(store.rebalanceDormant(identity, 'cell-b')).rejects.toThrow('assignment_active') - await store.releaseActivity(identity, control) - now += ASSIGNMENT_LIMITS.dormantTtlMs + 1 - - await expect(store.rebalanceDormant(identity, 'cell-b')).resolves.toMatchObject({ - cellId: 'cell-b', - assignmentEpoch: 2 - }) - expect(await cellReservations(database!)).toEqual({ 'cell-a': 0, 'cell-b': 1 }) - }) - - it('durably removes an unhealthy cell from new assignment without moving existing hosts', async () => { - const store = await setup( - () => 100, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ] - ) - const existing = { userId: 'user-a', relayHostId: 'host000000000001' } - expect(await store.assign(existing)).toMatchObject({ cellId: 'cell-a' }) - await store.setCellEnabled('cell-a', false) - await store.reconcileCells([ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 10 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 10 } - ]) - expect(await store.resolve(existing)).toMatchObject({ cellId: 'cell-a' }) - await expect( - store.assign({ userId: 'user-b', relayHostId: 'host000000000002' }) - ).resolves.toMatchObject({ cellId: 'cell-b' }) - await store.setCellEnabled('cell-a', true) - await expect(store.setCellEnabled('missing', false)).rejects.toThrow('cell_not_found') - }) - - it('bulk-migrates active controls without exposing assignment identities', async () => { - const store = await setup( - () => 100, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 20 } - ] - ) - await store.setCellEnabled('cell-b', false) - const identities = [1, 2, 3].map((index) => ({ - userId: `user-${index}`, - relayHostId: `host${String(index).padStart(12, '0')}` - })) - const sourceControls: string[] = [] - for (const identity of identities) { - const assignment = await store.assign(identity) - sourceControls.push( - await store.activateControl(identity, { - cellId: 'cell-a', - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - ) - } - await store.setCellEnabled('cell-b', true) - expect(await store.cellEvacuationCapacity('cell-a', 'cell-b')).toEqual({ - sourceAssignments: 3, - requiredTargetUnits: 6, - availableTargetUnits: 20 - }) - expect(await store.startActiveCellEvacuations('cell-a', 'cell-b', 2)).toBe(2) - expect(await store.startActiveCellEvacuations('cell-a', 'cell-b', 2)).toBe(1) - expect(await store.startActiveCellEvacuations('cell-a', 'cell-b', 2)).toBe(0) - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', false)).toEqual({ - inProgress: 3, - oldestExpiresAt: 100 + ASSIGNMENT_LIMITS.migrationLeaseMs, - oldestRemainingMs: ASSIGNMENT_LIMITS.migrationLeaseMs, - targetRegistered: 0, - ...NO_REGISTERED_EVACUATION_DIAGNOSTICS, - completed: 0, - blocked: 0, - ...NO_EXPIRED_EVACUATION_DIAGNOSTICS - }) - for (const identity of identities) { - const assignment = await store.resolve(identity) - await store.activateControl(identity, { - cellId: 'cell-b', - assignmentEpoch: assignment!.assignmentEpoch, - generation: 2 - }) - await store.markMigrationTargetRegistered(identity, { - cellId: 'cell-b', - assignmentEpoch: assignment!.assignmentEpoch - }) - } - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', true)).toEqual({ - inProgress: 3, - oldestExpiresAt: 100 + ASSIGNMENT_LIMITS.migrationLeaseMs, - oldestRemainingMs: ASSIGNMENT_LIMITS.migrationLeaseMs, - targetRegistered: 3, - registeredSourceActive: 3, - registeredCompletable: 0, - registeredTargetInactive: 0, - completed: 0, - blocked: 3, - ...NO_EXPIRED_EVACUATION_DIAGNOSTICS - }) - for (let index = 0; index < identities.length; index++) { - await store.releaseActivity(identities[index]!, sourceControls[index]!) - } - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', true)).toEqual({ - inProgress: 0, - ...NO_ACTIVE_MIGRATION_LEASE, - targetRegistered: 0, - ...NO_REGISTERED_EVACUATION_DIAGNOSTICS, - completed: 3, - blocked: 0, - ...NO_EXPIRED_EVACUATION_DIAGNOSTICS - }) - }) - - it.each(['cell-b', 'cell-c'])( - 'skips a batch row that concurrently moved from the selected source to %s', - async (movedCellId) => { - const store = await setup( - () => 100, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 20 }, - { id: 'cell-c', url: 'https://relay-c.example.com', capacityRequests: 20 } - ] - ) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const assignment = await store.assign(identity) - await store.activateControl(identity, { - cellId: 'cell-a', - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - const startEvacuation = store.startEvacuation.bind(store) - vi.spyOn(store, 'startEvacuation').mockImplementationOnce(async (...args) => { - await database!.query( - `UPDATE relay_assignments SET cell_id = ? WHERE user_id = ? AND relay_host_id = ?`, - [movedCellId, identity.userId, identity.relayHostId] - ) - return await startEvacuation(...args) - }) - - expect(await store.startActiveCellEvacuations('cell-a', 'cell-b', 10)).toBe(0) - expect(await store.resolve(identity)).toMatchObject({ cellId: movedCellId }) - expect(await database!.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) - } - ) - - it('does not count an existing migration after a stale batch row moves to its target', async () => { - const store = await setup( - () => 100, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 20 } - ] - ) - const identity = { userId: 'user-a', relayHostId: 'host000000000001' } - const assignment = await store.assign(identity) - await store.activateControl(identity, { - cellId: 'cell-a', - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - const startEvacuation = store.startEvacuation.bind(store) - vi.spyOn(store, 'startEvacuation').mockImplementationOnce(async (...args) => { - await startEvacuation(identity, 'cell-b') - return await startEvacuation(...args) - }) - - expect(await store.startActiveCellEvacuations('cell-a', 'cell-b', 10)).toBe(0) - expect(await store.resolve(identity)).toMatchObject({ cellId: 'cell-b' }) - expect(await store.cellEvacuationStatus('cell-a', 'cell-b', false)).toMatchObject({ - inProgress: 1 - }) - }) - - it('preserves operator-owned tagged URLs and admission state across reconciliation', async () => { - const store = await setup( - () => 100, - [{ id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }] - ) - await store.configureCell( - { id: 'cell-a', url: 'https://old---relay-a.example.com', capacityRequests: 20 }, - false - ) - await store.reconcileCells([ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 } - ]) - const rows = await database!.query( - `SELECT cell_url, enabled, capacity_requests FROM relay_cells WHERE cell_id = ?`, - ['cell-a'] - ) - expect(rows).toEqual([ - { - cell_url: 'https://old---relay-a.example.com', - enabled: 0, - capacity_requests: 20 - } - ]) - }) - - it('bulk-migrates activity even when its source control is temporarily absent', async () => { - const store = await setup( - () => 100, - [ - { id: 'cell-a', url: 'https://relay-a.example.com', capacityRequests: 20 }, - { id: 'cell-b', url: 'https://relay-b.example.com', capacityRequests: 20 } - ] - ) - const identity = { userId: 'user-1', relayHostId: 'host000000000001' } - const assignment = await store.assign(identity) - const control = await store.activateControl(identity, { - cellId: 'cell-a', - assignmentEpoch: assignment.assignmentEpoch, - generation: 1 - }) - await store.acquireActivity(identity, { - activityId: 'splice-without-control', - kind: 'splice', - cellId: 'cell-a' - }) - await store.releaseActivity(identity, control) - expect(await store.cellEvacuationCapacity('cell-a', 'cell-b')).toEqual({ - sourceAssignments: 1, - requiredTargetUnits: 3, - availableTargetUnits: 20 - }) - expect(await store.startActiveCellEvacuations('cell-a', 'cell-b', 10)).toBe(1) - expect(await store.resolve(identity)).toMatchObject({ cellId: 'cell-b', assignmentEpoch: 2 }) - }) }) async function cellReservations(database: RelayDatabase): Promise> { diff --git a/cloud/apps/relay/src/relay.blackbox.test.ts b/cloud/apps/relay/src/relay.blackbox.test.ts index e4c71f4dd54..95cd508f587 100644 --- a/cloud/apps/relay/src/relay.blackbox.test.ts +++ b/cloud/apps/relay/src/relay.blackbox.test.ts @@ -1,20 +1,23 @@ import type { ChildProcess } from 'node:child_process' import { spawnProcess } from '@orca/process-host' import { createHash, createHmac } from 'node:crypto' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, rmSync } from 'node:fs' import { createServer, type Server } from 'node:http' import { createServer as createNetServer } from 'node:net' import { dirname, resolve } from 'node:path' import { tmpdir } from 'node:os' import { fileURLToPath } from 'node:url' -import { exportJWK, generateKeyPair, jwtVerify, SignJWT } from 'jose' -import { ASSIGNMENT_LIMITS } from '@orca-cloud/relay-contract/assignment-invariants' -import { buildHostProofMacInput, HOST_CHALLENGE_PLAINTEXT_DOMAIN } from '@orca-cloud/relay-contract/host-proof-transcript' +import { exportJWK, generateKeyPair, SignJWT } from 'jose' + +import { + buildHostProofMacInput, + HOST_CHALLENGE_PLAINTEXT_DOMAIN +} from '@orca-cloud/relay-contract/host-proof-transcript' import nacl from 'tweetnacl' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import WebSocket from 'ws' import type { RawData } from 'ws' -import { assignmentLeaseKeyId } from './assignment/assignment-lease.js' + import { RelayAssignmentStore } from './assignment/assignment-store.js' import { encodeMembership, @@ -94,47 +97,6 @@ async function waitForRelay(child: ChildProcess): Promise { }) } -async function withClockRelay( - operation: (clockFile: string, dataDirectory: string) => Promise -): Promise { - const originalUrl = relayUrl - const clockPort = await unusedPort() - const clockUrl = `http://127.0.0.1:${clockPort}` - const clockData = mkdtempSync(resolve(tmpdir(), 'orca-relay-clock-')) - const clockFile = resolve(clockData, 'offset-ms') - writeFileSync(clockFile, '0') - const clockProcess = spawnProcess({ - program: process.execPath, - args: ['--import', 'tsx', 'src/fault-injection-test-entry.ts'], - cwd: appDirectory, - env: { - ...process.env, - NODE_ENV: 'test', - PORT: String(clockPort), - ORCA_RELAY_PUBLIC_URL: clockUrl, - ORCA_RELAY_CELL_URL: clockUrl, - ORCA_RELAY_AUTH_ISSUER: issuer, - ORCA_RELAY_JWKS_URL: `${issuer}/jwks`, - ORCA_RELAY_ASSIGNMENT_SIGNING_KEY: assignmentKey, - ORCA_RELAY_DATA_DIR: clockData, - ORCA_RELAY_ADMIN_AUDIENCE: adminAudience, - ORCA_RELAY_DEPLOY_SERVICE_ACCOUNT: 'deploy@example.com', - ORCA_RELAY_ADMIN_JWKS_URL: `${issuer}/jwks`, - ORCA_RELAY_TEST_CLOCK_FILE: clockFile - }, - stdio: ['ignore', 'pipe', 'pipe'] - }) - relayUrl = clockUrl - try { - await waitForRelay(clockProcess) - await operation(clockFile, clockData) - } finally { - await stopRelay(clockProcess) - relayUrl = originalUrl - rmSync(clockData, { recursive: true, force: true }) - } -} - async function relayToken(audience: string, relayHostId = 'abcdefghijklmnop'): Promise { return await new SignJWT({ prof: 'profile-1', @@ -282,26 +244,6 @@ function collectMessages(socket: WebSocket, count: number): Promise> { - const response = nextMessage(input.host) - input.host.send( - JSON.stringify({ - type: 'device-credential-install', - v: 1, - reqId: input.reqId, - relayDeviceId: input.relayDeviceId, - newResumeTokenHash: createHash('sha256').update(input.resumeToken).digest('base64url'), - authorization: { mode: 'authenticated-direct', directAuthId: `direct-${input.reqId}` } - }) - ) - return await response -} - async function attachPhone(input: { host: WebSocket hostAck: Record @@ -322,7 +264,9 @@ async function attachPhone(input: { phone.once('error', reject) }) const connOpenPromise = nextMessage(input.host) - phone.send(JSON.stringify({ type: 'relay-auth', v: 1, mode: 'connect', credential: input.credential })) + phone.send( + JSON.stringify({ type: 'relay-auth', v: 1, mode: 'connect', credential: input.credential }) + ) const connOpen = await connOpenPromise expect(connOpen.type).toBe('conn-open') const connId = String(connOpen.connId) @@ -413,47 +357,6 @@ async function openHostControl(input?: { return { socket, ack: await nextMessage(socket), keyPair } } -async function seedDurableAssignment( - keyPair: nacl.BoxKeyPair, - epoch: number, - wrongCell = false -): Promise { - const identity = { - userId: 'user-1', - relayHostId: createHash('sha256').update(keyPair.publicKey).digest('base64url').slice(0, 16) - } - const database = await openRelayDatabase({ dataDir: relayDataDirectory }) - let now = - Date.now() - - (epoch - 1) * (2 * ASSIGNMENT_LIMITS.dormantTtlMs + ASSIGNMENT_LIMITS.activityLeaseMs + 2) - const assignments = new RelayAssignmentStore(database, () => now) - try { - await assignments.reconcileCells([{ id: 'combined', url: relayUrl, capacityRequests: 4_000 }]) - await assignments.assign(identity) - for (let nextEpoch = 2; nextEpoch <= epoch; nextEpoch++) { - now += ASSIGNMENT_LIMITS.dormantTtlMs + ASSIGNMENT_LIMITS.activityLeaseMs + 1 - await assignments.releaseExpiredActivityLeases() - await assignments.releaseExpiredActivity() - now += ASSIGNMENT_LIMITS.dormantTtlMs + 1 - expect(await assignments.assign(identity)).toMatchObject({ - cellId: 'combined', - assignmentEpoch: nextEpoch - }) - } - if (wrongCell) { - const otherCellId = `other-${identity.relayHostId}` - await assignments.reconcileCells([ - { id: 'combined', url: relayUrl, capacityRequests: 4_000 }, - { id: otherCellId, url: `https://${otherCellId}.example.test`, capacityRequests: 4_000 } - ]) - await assignments.startEvacuation(identity, otherCellId) - await assignments.reconcileCells([{ id: 'combined', url: relayUrl, capacityRequests: 4_000 }]) - } - } finally { - await database.close() - } -} - beforeAll(async () => { const keys = await generateKeyPair('ES256') privateKey = keys.privateKey @@ -512,301 +415,6 @@ afterAll(async () => { }) describe('served relay URL', () => { - it('keeps liveness healthy when dependency readiness fails', async () => { - const port = await unusedPort() - const url = `http://127.0.0.1:${port}` - const dataDirectory = mkdtempSync(resolve(tmpdir(), 'orca-relay-unready-')) - const processUnderTest = spawnProcess({ - program: process.execPath, - args: ['--import', 'tsx', 'src/index.ts'], - cwd: appDirectory, - env: { - ...process.env, - PORT: String(port), - ORCA_RELAY_PUBLIC_URL: url, - ORCA_RELAY_CELL_URL: url, - ORCA_RELAY_AUTH_ISSUER: issuer, - ORCA_RELAY_JWKS_URL: 'http://127.0.0.1:1/jwks', - ORCA_RELAY_ASSIGNMENT_SIGNING_KEY: assignmentKey, - ORCA_RELAY_DATA_DIR: dataDirectory, - ORCA_RELAY_ADMIN_AUDIENCE: adminAudience, - ORCA_RELAY_DEPLOY_SERVICE_ACCOUNT: 'deploy@example.com', - ORCA_RELAY_IMAGE_DIGEST: `sha256:${'a'.repeat(64)}`, - ORCA_RELAY_ADMIN_JWKS_URL: `${issuer}/jwks` - }, - stdio: ['ignore', 'pipe', 'pipe'] - }) - try { - await waitForRelay(processUnderTest) - expect((await fetch(`${url}/health`)).status).toBe(200) - expect((await fetch(`${url}/ready`)).status).toBe(503) - } finally { - await stopRelay(processUnderTest, 'SIGTERM') - rmSync(dataDirectory, { recursive: true, force: true }) - } - }) - - it('rejects missing and broad-audience bearer tokens', async () => { - const body = JSON.stringify({ v: 1, relayHostId: 'abcdefghijklmnop' }) - expect((await fetch(`${relayUrl}/v1/assign`, { method: 'POST', body })).status).toBe(401) - expect( - ( - await fetch(`${relayUrl}/v1/assign`, { - method: 'POST', - headers: { authorization: `Bearer ${await relayToken('orca-cloud')}` }, - body - }) - ).status - ).toBe(401) - }) - - it('bounds slow first-frame admission and rejects URL credentials before upgrade', async () => { - const slow: WebSocket[] = [] - for (let index = 0; index < 4; index++) { - const socket = new WebSocket( - `${relayUrl.replace('http:', 'ws:')}/v1/connect/abcdefghijklmnop` - ) - await new Promise((resolveOpen, reject) => { - socket.once('open', resolveOpen) - socket.once('error', reject) - }) - slow.push(socket) - } - const limited = new WebSocket( - `${relayUrl.replace('http:', 'ws:')}/v1/connect/abcdefghijklmnop` - ) - const limitedStatus = await new Promise((resolveStatus) => { - limited.once('unexpected-response', (_request, response) => - resolveStatus(response.statusCode ?? 0) - ) - limited.once('error', () => {}) - }) - expect(limitedStatus).toBe(429) - const isolated = new WebSocket( - `${relayUrl.replace('http:', 'ws:')}/v1/connect/abcdefghijklmnop`, - { headers: { 'x-forwarded-for': 'spoofed, 198.51.100.9, 35.191.0.1' } } - ) - await new Promise((resolveOpen, reject) => { - isolated.once('open', resolveOpen) - isolated.once('error', reject) - }) - isolated.close() - for (const socket of slow) socket.close() - - const leaked = new WebSocket( - `${relayUrl.replace('http:', 'ws:')}/v1/connect/abcdefghijklmnop?credential=secret` - ) - const leakedStatus = await new Promise((resolveStatus) => { - leaked.once('unexpected-response', (_request, response) => - resolveStatus(response.statusCode ?? 0) - ) - leaked.once('error', () => {}) - }) - expect(leakedStatus).toBe(400) - }) - - it('enforces process-wide slow-auth and per-source rate budgets', async () => { - const slow: WebSocket[] = [] - for (let index = 0; index < 45; index++) { - const socket = new WebSocket( - `${relayUrl.replace('http:', 'ws:')}/v1/connect/abcdefghijklmnop`, - { headers: { 'x-forwarded-for': `spoofed, 198.51.100.${index + 1}, 35.191.0.1` } } - ) - await new Promise((resolveOpen, reject) => { - socket.once('open', resolveOpen) - socket.once('error', reject) - }) - slow.push(socket) - } - const globallyLimited = new WebSocket( - `${relayUrl.replace('http:', 'ws:')}/v1/connect/abcdefghijklmnop`, - { headers: { 'x-forwarded-for': 'spoofed, 203.0.113.1, 35.191.0.1' } } - ) - const globalStatus = await new Promise((resolveStatus) => { - globallyLimited.once('unexpected-response', (_request, response) => - resolveStatus(response.statusCode ?? 0) - ) - globallyLimited.once('error', () => {}) - }) - expect(globalStatus).toBe(429) - await Promise.all( - slow.map( - (socket) => - new Promise((resolveClose) => { - socket.once('close', () => resolveClose()) - socket.close() - }) - ) - ) - - for (let index = 0; index < 30; index++) { - const socket = new WebSocket( - `${relayUrl.replace('http:', 'ws:')}/v1/connect/abcdefghijklmnop`, - { headers: { 'x-forwarded-for': 'spoofed, 203.0.113.2, 35.191.0.1' } } - ) - await new Promise((resolveOpen, reject) => { - socket.once('open', resolveOpen) - socket.once('error', reject) - }) - const closed = new Promise((resolveClose) => socket.once('close', () => resolveClose())) - socket.send('{}') - await closed - } - const rateLimited = new WebSocket( - `${relayUrl.replace('http:', 'ws:')}/v1/connect/abcdefghijklmnop`, - { headers: { 'x-forwarded-for': 'spoofed, 203.0.113.2, 35.191.0.1' } } - ) - const rateStatus = await new Promise((resolveStatus) => { - rateLimited.once('unexpected-response', (_request, response) => - resolveStatus(response.statusCode ?? 0) - ) - rateLimited.once('error', () => {}) - }) - expect(rateStatus).toBe(429) - }) - - it('returns a signed combined-service assignment for the bound host', async () => { - const response = await fetch(`${relayUrl}/v1/assign`, { - method: 'POST', - headers: { - authorization: `Bearer ${await relayToken('orca-relay')}`, - 'content-type': 'application/json' - }, - body: JSON.stringify({ v: 1, relayHostId: 'abcdefghijklmnop' }) - }) - expect(response.status).toBe(200) - const assignment = (await response.json()) as { - v: number - cellUrl: string - assignmentEpoch: number - lease: string - } - expect(assignment).toMatchObject({ v: 1, cellUrl: relayUrl, assignmentEpoch: 1 }) - const verified = await jwtVerify(assignment.lease, new TextEncoder().encode(assignmentKey), { - issuer: relayUrl, - audience: 'orca-relay-cell', - algorithms: ['HS256'] - }) - expect(verified.payload).toMatchObject({ relayHostId: 'abcdefghijklmnop' }) - expect(verified.protectedHeader.kid).toBe( - assignmentLeaseKeyId(new TextEncoder().encode(assignmentKey)) - ) - }) - - it('requires canonical host key possession and supports same-generation rebind', async () => { - const first = await openHostControl() - expect(first.ack).toMatchObject({ type: 'host-hello-ack', v: 1, generation: 1 }) - const firstClose = new Promise((resolveClose) => - first.socket.once('close', (code) => resolveClose(code)) - ) - const rebound = await openHostControl({ - keyPair: first.keyPair, - controlResumeSecret: String(first.ack.controlResumeSecret), - previousGeneration: 1 - }) - expect(rebound.ack).toMatchObject({ type: 'host-hello-ack', v: 1, generation: 1 }) - expect(await firstClose).toBe(4408) - rebound.socket.close() - }) - - it('rejects a scoped token presented by a different host key', async () => { - const claimedKey = nacl.box.keyPair() - const wrongKey = nacl.box.keyPair() - const hostId = createHash('sha256').update(claimedKey.publicKey).digest('base64url').slice(0, 16) - const socket = new WebSocket(`${relayUrl.replace('http:', 'ws:')}/v1/host/control`, { - headers: { authorization: `Bearer ${await relayToken('orca-relay', hostId)}` } - }) - await new Promise((resolveOpen) => socket.once('open', resolveOpen)) - const closed = new Promise((resolveClose) => - socket.once('close', (code) => resolveClose(code)) - ) - socket.send( - JSON.stringify({ - type: 'host-hello', - v: 1, - relayHostId: hostId, - assignmentEpoch: 1, - hostPublicKeyB64: Buffer.from(wrongKey.publicKey).toString('base64'), - appVersion: 'test' - }) - ) - expect(await closed).toBe(4401) - }) - - it.each([1, 2, 7])('accepts combined control and pairing at durable epoch %i', async (epoch) => { - const keyPair = nacl.box.keyPair() - await seedDurableAssignment(keyPair, epoch) - const first = await openHostControl({ keyPair, assignmentEpoch: epoch }) - expect(first.ack).toMatchObject({ type: 'host-hello-ack', v: 1 }) - first.socket.close() - const reconnected = await openHostControl({ keyPair, assignmentEpoch: epoch }) - try { - expect(reconnected.ack).toMatchObject({ type: 'host-hello-ack', v: 1 }) - const invite = nextMessage(reconnected.socket) - reconnected.socket.send( - JSON.stringify({ - type: 'invite-create', - reqId: 'reassigned-invite', - relayDeviceId: 'reassigned-device' - }) - ) - expect(await invite).toMatchObject({ type: 'invite-created', reqId: 'reassigned-invite' }) - } finally { - reconnected.socket.close() - } - }) - - it('preserves combined epoch-one bootstrap without a durable assignment', async () => { - const host = await openHostControl() - try { - expect(host.ack).toMatchObject({ type: 'host-hello-ack', v: 1 }) - } finally { - host.socket.close() - } - }) - - it.each([ - { storedEpoch: undefined, helloEpoch: 2, wrongCell: false }, - { storedEpoch: 2, helloEpoch: 1, wrongCell: false }, - { storedEpoch: 2, helloEpoch: 3, wrongCell: false }, - { storedEpoch: 1, helloEpoch: 1, wrongCell: true }, - { storedEpoch: 1, helloEpoch: 2, wrongCell: true } - ])('refuses invalid combined admission: %j', async ({ storedEpoch, helloEpoch, wrongCell }) => { - const keyPair = nacl.box.keyPair() - if (storedEpoch !== undefined) { - await seedDurableAssignment(keyPair, storedEpoch, wrongCell) - } - const hostId = createHash('sha256').update(keyPair.publicKey).digest('base64url').slice(0, 16) - const socket = new WebSocket(`${relayUrl.replace('http:', 'ws:')}/v1/host/control`, { - headers: { authorization: `Bearer ${await relayToken('orca-relay', hostId)}` } - }) - await new Promise((resolveOpen, reject) => { - socket.once('open', resolveOpen) - socket.once('error', reject) - }) - const closed = new Promise<{ code: number; reason: string }>((resolveClose) => { - socket.once('message', () => resolveClose({ code: 0, reason: 'unexpected host challenge' })) - socket.once('close', (code, reason) => resolveClose({ code, reason: reason.toString() })) - }) - socket.send( - JSON.stringify({ - type: 'host-hello', - v: 1, - relayHostId: hostId, - assignmentEpoch: helloEpoch, - hostPublicKeyB64: Buffer.from(keyPair.publicKey).toString('base64'), - appVersion: 'test' - }) - ) - try { - const result = await closed - expect(result.code).toBe(4409) - expect(result.reason).not.toContain('http') - } finally { - socket.close() - } - }) - it('restates a pending connection to the rebound control, detailed only when advertised', async () => { // Real upgrade must carry x-orca-host-capabilities into acceptControl; unit tests cannot catch a misspelled header here. const host = await openHostControl() @@ -875,7 +483,11 @@ describe('served relay URL', () => { .slice(0, 16) const inviteResponse = nextMessage(host.socket) host.socket.send( - JSON.stringify({ type: 'invite-create', reqId: 'ticket-invite', relayDeviceId: 'ticket-device' }) + JSON.stringify({ + type: 'invite-create', + reqId: 'ticket-invite', + relayDeviceId: 'ticket-device' + }) ) const invite = await inviteResponse const phone = new WebSocket(`${relayUrl.replace('http:', 'ws:')}/v1/connect/${hostId}`, { @@ -1026,168 +638,6 @@ describe('served relay URL', () => { host.socket.close() }) - it('does not renew outer-only or injected confirmations and reports offline/peer loss', async () => { - const host = await openHostControl() - const hostId = createHash('sha256') - .update(host.keyPair.publicKey) - .digest('base64url') - .slice(0, 16) - const resumeToken = Buffer.alloc(32, 11).toString('base64url') - expect( - await installDirectCredential({ - host: host.socket, - relayDeviceId: 'outer-device', - reqId: 'outer-install', - resumeToken - }) - ).toMatchObject({ type: 'device-credential-installed', currentVersion: 1 }) - - const first = await attachPhone({ - host: host.socket, - hostAck: host.ack, - hostId, - credential: resumeToken - }) - const originalExpiry = first.hello.resumeExpiresAt - // Only the relay's close of the data leg proves it saw the phone leave; a client-side close can race the confirm. - const firstDataClosed = new Promise((resolveClose) => - first.data.once('close', (code) => resolveClose(code)) - ) - first.phone.close() - expect(await firstDataClosed).toBe(4408) - const closedBasis = nextMessage(host.socket) - host.socket.send( - JSON.stringify({ - type: 'device-resume-confirm', - v: 1, - reqId: 'closed-basis-confirm', - basisConnId: first.connId - }) - ) - expect(await closedBasis).toMatchObject({ - type: 'control-error', - reqId: 'closed-basis-confirm', - code: 'confirmation_not_active' - }) - const second = await attachPhone({ - host: host.socket, - hostAck: host.ack, - hostId, - credential: resumeToken - }) - expect(second.hello.resumeExpiresAt).toBe(originalExpiry) - const injectedResult = nextMessage(host.socket) - host.socket.send( - JSON.stringify({ - type: 'device-resume-confirm', - v: 1, - reqId: 'injected-confirm', - basisConnId: second.connId, - relayDeviceId: 'injected', - acceptedCredentialVersion: 99 - }) - ) - expect(await injectedResult).toMatchObject({ type: 'control-error', reqId: 'injected-confirm' }) - const phoneClosed = new Promise((resolveClose) => - second.phone.once('close', (code) => resolveClose(code)) - ) - second.data.close() - expect(await phoneClosed).toBe(4408) - - await new Promise((resolveClose) => { - host.socket.once('close', () => resolveClose()) - host.socket.close() - }) - const offline = new WebSocket(`${relayUrl.replace('http:', 'ws:')}/v1/connect/${hostId}`, { - headers: forwardedHeaders() - }) - await new Promise((resolveOpen) => offline.once('open', resolveOpen)) - const offlineHello = nextMessage(offline) - offline.send( - JSON.stringify({ type: 'relay-auth', v: 1, mode: 'connect', credential: resumeToken }) - ) - expect(await offlineHello).toEqual({ type: 'relay-hello', ok: false, code: 4404 }) - }) - - it('rejects the first post-E2EE confirmation after its server-owned deadline', async () => { - await withClockRelay(async (clockFile) => { - const host = await openHostControl() - const hostId = createHash('sha256') - .update(host.keyPair.publicKey) - .digest('base64url') - .slice(0, 16) - const resumeToken = Buffer.alloc(32, 25).toString('base64url') - await installDirectCredential({ - host: host.socket, - relayDeviceId: 'late-confirm-device', - reqId: 'late-confirm-install', - resumeToken - }) - const splice = await attachPhone({ - host: host.socket, - hostAck: host.ack, - hostId, - credential: resumeToken - }) - writeFileSync(clockFile, '31000') - const rejected = nextMessage(host.socket) - host.socket.send( - JSON.stringify({ - type: 'device-resume-confirm', - v: 1, - reqId: 'late-first-confirm', - basisConnId: splice.connId - }) - ) - expect(await rejected).toMatchObject({ - type: 'control-error', - reqId: 'late-first-confirm', - code: 'confirmation_not_active' - }) - splice.phone.close() - splice.data.close() - host.socket.close() - }) - }) - - it('fences a competing generation and rejects its old immutable basis', async () => { - const firstHost = await openHostControl() - const hostId = createHash('sha256') - .update(firstHost.keyPair.publicKey) - .digest('base64url') - .slice(0, 16) - const resumeToken = Buffer.alloc(32, 12).toString('base64url') - await installDirectCredential({ - host: firstHost.socket, - relayDeviceId: 'fenced-device', - reqId: 'fenced-install', - resumeToken - }) - const splice = await attachPhone({ - host: firstHost.socket, - hostAck: firstHost.ack, - hostId, - credential: resumeToken - }) - const replacement = await openHostControl({ keyPair: firstHost.keyPair, previousGeneration: 1 }) - expect(replacement.ack.generation).toBe(2) - const rejected = nextMessage(replacement.socket) - replacement.socket.send( - JSON.stringify({ - type: 'device-resume-confirm', - v: 1, - reqId: 'wrong-generation-confirm', - basisConnId: splice.connId - }) - ) - expect(await rejected).toMatchObject({ - type: 'control-error', - reqId: 'wrong-generation-confirm', - code: 'confirmation_not_active' - }) - replacement.socket.close() - }) - it('serializes late direct and invite authorization modes into one served result', async () => { const host = await openHostControl() const hostId = createHash('sha256') @@ -1234,713 +684,6 @@ describe('served relay URL', () => { host.socket.close() }) - it('reconciles a direct commit after its response is ignored and rejects bad authorization', async () => { - const firstHost = await openHostControl() - const hostId = createHash('sha256') - .update(firstHost.keyPair.publicKey) - .digest('base64url') - .slice(0, 16) - const inviteResponse = nextMessage(firstHost.socket) - firstHost.socket.send( - JSON.stringify({ - type: 'invite-create', - reqId: 'lost-response-invite', - relayDeviceId: 'lost-response-device' - }) - ) - const invite = await inviteResponse - const resumeToken = Buffer.alloc(32, 26).toString('base64url') - const committed = nextMessage(firstHost.socket) - firstHost.socket.send( - JSON.stringify({ - type: 'device-credential-install', - v: 1, - reqId: 'lost-response-install', - relayDeviceId: 'lost-response-device', - newResumeTokenHash: createHash('sha256').update(resumeToken).digest('base64url'), - authorization: { mode: 'authenticated-direct', directAuthId: 'lost-response-direct' } - }) - ) - // Observe the commit boundary; recovery below uses only the durable status. - expect(await committed).toMatchObject({ - type: 'device-credential-installed', - currentVersion: 1 - }) - firstHost.socket.terminate() - const rebound = await openHostControl({ - keyPair: firstHost.keyPair, - controlResumeSecret: String(firstHost.ack.controlResumeSecret), - previousGeneration: Number(firstHost.ack.generation) - }) - const status = nextMessage(rebound.socket) - rebound.socket.send( - JSON.stringify({ - type: 'device-credential-install-status', - v: 1, - reqId: 'lost-response-install', - relayDeviceId: 'lost-response-device' - }) - ) - expect(await status).toMatchObject({ - type: 'device-credential-install-status-result', - state: 'committed', - result: { authorizationMode: 'authenticated-direct', currentVersion: 1 } - }) - - const invalidatedInvite = new WebSocket( - `${relayUrl.replace('http:', 'ws:')}/v1/connect/${hostId}`, - { headers: forwardedHeaders() } - ) - await new Promise((resolveOpen, reject) => { - invalidatedInvite.once('open', resolveOpen) - invalidatedInvite.once('error', reject) - }) - const rejectedInvite = nextMessage(invalidatedInvite) - invalidatedInvite.send( - JSON.stringify({ type: 'relay-auth', v: 1, mode: 'connect', credential: invite.inviteToken }) - ) - expect(await rejectedInvite).toEqual({ type: 'relay-hello', ok: false, code: 4401 }) - - const unauthorized = nextMessage(rebound.socket) - rebound.socket.send( - JSON.stringify({ - type: 'device-credential-install', - v: 1, - reqId: 'unauthorized-install', - relayDeviceId: 'unauthorized-device', - newResumeTokenHash: createHash('sha256').update('unauthorized').digest('base64url'), - authorization: { mode: 'relay-basis', basisConnId: 'unknown-basis' } - }) - ) - expect(await unauthorized).toMatchObject({ - type: 'control-error', - reqId: 'unauthorized-install', - code: 'invalid_relay_basis' - }) - const missing = nextMessage(rebound.socket) - rebound.socket.send( - JSON.stringify({ - type: 'device-credential-install-status', - v: 1, - reqId: 'unauthorized-install', - relayDeviceId: 'unauthorized-device' - }) - ) - expect(await missing).toMatchObject({ - type: 'device-credential-install-status-result', - state: 'not-found' - }) - rebound.socket.close() - }) - - it('serializes confirmation against direct rotation, relay rotation, and revoke', async () => { - const host = await openHostControl() - const hostId = createHash('sha256') - .update(host.keyPair.publicKey) - .digest('base64url') - .slice(0, 16) - const firstToken = Buffer.alloc(32, 21).toString('base64url') - await installDirectCredential({ - host: host.socket, - relayDeviceId: 'confirm-race-device', - reqId: 'confirm-race-initial', - resumeToken: firstToken - }) - - const firstResume = await attachPhone({ - host: host.socket, - hostAck: host.ack, - hostId, - credential: firstToken - }) - const secondToken = Buffer.alloc(32, 22).toString('base64url') - const directResponses = collectMessages(host.socket, 2) - host.socket.send( - JSON.stringify({ - type: 'device-resume-confirm', - v: 1, - reqId: 'confirm-before-direct', - basisConnId: firstResume.connId - }) - ) - host.socket.send( - JSON.stringify({ - type: 'device-credential-install', - v: 1, - reqId: 'direct-after-confirm', - relayDeviceId: 'confirm-race-device', - newResumeTokenHash: createHash('sha256').update(secondToken).digest('base64url'), - expectedCurrentHash: createHash('sha256').update(firstToken).digest('base64url'), - authorization: { mode: 'authenticated-direct', directAuthId: 'direct-after-confirm' } - }) - ) - const directResults = await directResponses - expect(directResults.find((result) => result.type === 'device-resume-confirmed')).toMatchObject({ - reqId: 'confirm-before-direct', - currentVersion: 1, - renewed: true - }) - expect(directResults.find((result) => result.type === 'device-credential-installed')).toMatchObject({ - reqId: 'direct-after-confirm', - currentVersion: 2 - }) - const replayPromise = nextMessage(host.socket) - host.socket.send( - JSON.stringify({ - type: 'device-resume-confirm', - v: 1, - reqId: 'confirm-before-direct', - basisConnId: firstResume.connId - }) - ) - expect(await replayPromise).toEqual( - directResults.find((result) => result.type === 'device-resume-confirmed') - ) - - const secondResume = await attachPhone({ - host: host.socket, - hostAck: host.ack, - hostId, - credential: secondToken - }) - const inviteResponse = nextMessage(host.socket) - host.socket.send( - JSON.stringify({ - type: 'invite-create', - reqId: 'relay-rotation-invite', - relayDeviceId: 'confirm-race-device' - }) - ) - const invite = await inviteResponse - const inviteSplice = await attachPhone({ - host: host.socket, - hostAck: host.ack, - hostId, - credential: String(invite.inviteToken) - }) - const thirdToken = Buffer.alloc(32, 23).toString('base64url') - const relayResponses = collectMessages(host.socket, 2) - host.socket.send( - JSON.stringify({ - type: 'device-credential-install', - v: 1, - reqId: 'relay-before-confirm', - relayDeviceId: 'confirm-race-device', - newResumeTokenHash: createHash('sha256').update(thirdToken).digest('base64url'), - expectedCurrentHash: createHash('sha256').update(secondToken).digest('base64url'), - authorization: { mode: 'relay-basis', basisConnId: inviteSplice.connId } - }) - ) - host.socket.send( - JSON.stringify({ - type: 'device-resume-confirm', - v: 1, - reqId: 'confirm-after-relay', - basisConnId: secondResume.connId - }) - ) - const relayResults = await relayResponses - expect(relayResults.find((result) => result.type === 'device-credential-installed')).toMatchObject({ - reqId: 'relay-before-confirm', - currentVersion: 3 - }) - expect(relayResults.find((result) => result.type === 'device-resume-confirmed')).toMatchObject({ - reqId: 'confirm-after-relay', - currentVersion: 3, - renewed: false - }) - - const retiredResume = await attachPhone({ - host: host.socket, - hostAck: host.ack, - hostId, - credential: secondToken - }) - const fourthToken = Buffer.alloc(32, 24).toString('base64url') - expect( - await installDirectCredential({ - host: host.socket, - relayDeviceId: 'confirm-race-device', - reqId: 'retire-before-confirm', - resumeToken: fourthToken - }) - ).toMatchObject({ type: 'device-credential-installed', currentVersion: 4 }) - const retiredResult = nextMessage(host.socket) - host.socket.send( - JSON.stringify({ - type: 'device-resume-confirm', - v: 1, - reqId: 'confirm-retired', - basisConnId: retiredResume.connId - }) - ) - expect(await retiredResult).toMatchObject({ - type: 'control-error', - reqId: 'confirm-retired', - code: 'reject-retired' - }) - - const currentResume = await attachPhone({ - host: host.socket, - hostAck: host.ack, - hostId, - credential: fourthToken - }) - const revokeResponses = collectMessages(host.socket, 2) - host.socket.send( - JSON.stringify({ - type: 'device-revoke', - reqId: 'revoke-before-confirm', - relayDeviceId: 'confirm-race-device' - }) - ) - host.socket.send( - JSON.stringify({ - type: 'device-resume-confirm', - v: 1, - reqId: 'confirm-after-revoke', - basisConnId: currentResume.connId - }) - ) - const revokeResults = await revokeResponses - expect(revokeResults.find((result) => result.type === 'device-revoked')).toMatchObject({ - reqId: 'revoke-before-confirm' - }) - expect(revokeResults.find((result) => result.type === 'control-error')).toMatchObject({ - reqId: 'confirm-after-revoke', - code: 'reject-revoked' - }) - - for (const splice of [firstResume, secondResume, inviteSplice, retiredResume, currentResume]) { - splice.phone.close() - splice.data.close() - } - host.socket.close() - }) - - it('enforces the eight-splice host limit with typed 4429 recovery', async () => { - const host = await openHostControl() - const hostId = createHash('sha256') - .update(host.keyPair.publicKey) - .digest('base64url') - .slice(0, 16) - const resumeToken = Buffer.alloc(32, 13).toString('base64url') - await installDirectCredential({ - host: host.socket, - relayDeviceId: 'limit-device', - reqId: 'limit-install', - resumeToken - }) - const splices = [] - for (let index = 0; index < 8; index++) { - splices.push( - await attachPhone({ host: host.socket, hostAck: host.ack, hostId, credential: resumeToken }) - ) - } - const ninth = new WebSocket(`${relayUrl.replace('http:', 'ws:')}/v1/connect/${hostId}`, { - headers: forwardedHeaders() - }) - await new Promise((resolveOpen) => ninth.once('open', resolveOpen)) - const rejected = nextMessage(ninth) - ninth.send( - JSON.stringify({ type: 'relay-auth', v: 1, mode: 'connect', credential: resumeToken }) - ) - expect(await rejected).toEqual({ type: 'relay-hello', ok: false, code: 4429 }) - for (const splice of splices) { - splice.phone.close() - splice.data.close() - } - host.socket.close() - }) - - it('rolls an aborted invite reservation into bounded cooldown before retry', async () => { - await withClockRelay(async (clockFile, dataDirectory) => { - const host = await openHostControl() - const hostId = createHash('sha256') - .update(host.keyPair.publicKey) - .digest('base64url') - .slice(0, 16) - const inviteResponse = nextMessage(host.socket) - host.socket.send( - JSON.stringify({ - type: 'invite-create', - reqId: 'cooldown-invite', - relayDeviceId: 'cooldown-device' - }) - ) - const invite = await inviteResponse - const first = new WebSocket(`${relayUrl.replace('http:', 'ws:')}/v1/connect/${hostId}`, { - headers: forwardedHeaders() - }) - await new Promise((resolveOpen) => first.once('open', resolveOpen)) - const firstOpen = nextMessage(host.socket) - first.send( - JSON.stringify({ - type: 'relay-auth', - v: 1, - mode: 'connect', - credential: invite.inviteToken - }) - ) - await firstOpen - const database = await openRelayDatabase({ dataDir: dataDirectory }) - try { - first.close() - await expect - .poll( - async () => - ( - await database.query(`SELECT state FROM relay_invites WHERE relay_device_id = ?`, [ - 'cooldown-device' - ]) - )[0]?.state - ) - .toBe('cooldown') - - const cooldown = new WebSocket(`${relayUrl.replace('http:', 'ws:')}/v1/connect/${hostId}`, { - headers: forwardedHeaders() - }) - await new Promise((resolveOpen) => cooldown.once('open', resolveOpen)) - const cooldownHello = nextMessage(cooldown) - cooldown.send( - JSON.stringify({ - type: 'relay-auth', - v: 1, - mode: 'connect', - credential: invite.inviteToken - }) - ) - expect(await cooldownHello).toEqual({ type: 'relay-hello', ok: false, code: 4401 }) - - writeFileSync(clockFile, '2050') - const retry = new WebSocket(`${relayUrl.replace('http:', 'ws:')}/v1/connect/${hostId}`, { - headers: forwardedHeaders() - }) - await new Promise((resolveOpen) => retry.once('open', resolveOpen)) - const retriedOpen = nextMessage(host.socket) - retry.send( - JSON.stringify({ - type: 'relay-auth', - v: 1, - mode: 'connect', - credential: invite.inviteToken - }) - ) - expect(await retriedOpen).toMatchObject({ type: 'conn-open', kind: 'invite' }) - retry.close() - host.socket.close() - } finally { - await database.close() - host.socket.close() - } - }) - }) - - it('keeps install status and every effect not-found after injected SQL failure', async () => { - const originalUrl = relayUrl - const faultPort = await unusedPort() - const faultUrl = `http://127.0.0.1:${faultPort}` - const faultData = mkdtempSync(resolve(tmpdir(), 'orca-relay-fault-')) - const faultProcess = spawnProcess({ - program: process.execPath, - args: ['--import', 'tsx', 'src/fault-injection-test-entry.ts'], - cwd: appDirectory, - env: { - ...process.env, - NODE_ENV: 'test', - PORT: String(faultPort), - ORCA_RELAY_PUBLIC_URL: faultUrl, - ORCA_RELAY_CELL_URL: faultUrl, - ORCA_RELAY_AUTH_ISSUER: issuer, - ORCA_RELAY_JWKS_URL: `${issuer}/jwks`, - ORCA_RELAY_ASSIGNMENT_SIGNING_KEY: assignmentKey, - ORCA_RELAY_DATA_DIR: faultData, - ORCA_RELAY_ADMIN_AUDIENCE: adminAudience, - ORCA_RELAY_DEPLOY_SERVICE_ACCOUNT: 'deploy@example.com', - ORCA_RELAY_ADMIN_JWKS_URL: `${issuer}/jwks`, - ORCA_RELAY_TEST_FAULT_SQL: 'INSERT INTO relay_install_results' - }, - stdio: ['ignore', 'pipe', 'pipe'] - }) - relayUrl = faultUrl - try { - await waitForRelay(faultProcess) - const host = await openHostControl() - const hostId = createHash('sha256') - .update(host.keyPair.publicKey) - .digest('base64url') - .slice(0, 16) - const inviteResponse = nextMessage(host.socket) - host.socket.send( - JSON.stringify({ - type: 'invite-create', - reqId: 'fault-invite', - relayDeviceId: 'fault-device' - }) - ) - const invite = await inviteResponse - const splice = await attachPhone({ - host: host.socket, - hostAck: host.ack, - hostId, - credential: String(invite.inviteToken) - }) - const install = { - type: 'device-credential-install', - v: 1, - reqId: 'fault-install', - relayDeviceId: 'fault-device', - newResumeTokenHash: createHash('sha256').update('fault-resume').digest('base64url'), - authorization: { mode: 'relay-basis', basisConnId: splice.connId } - } - const failed = nextMessage(host.socket) - host.socket.send(JSON.stringify(install)) - expect(await failed).toMatchObject({ - type: 'control-error', - reqId: 'fault-install', - code: 'control_operation_failed' - }) - const status = nextMessage(host.socket) - host.socket.send( - JSON.stringify({ - type: 'device-credential-install-status', - v: 1, - reqId: 'fault-install', - relayDeviceId: 'fault-device' - }) - ) - expect(await status).toMatchObject({ - type: 'device-credential-install-status-result', - state: 'not-found' - }) - const retried = nextMessage(host.socket) - host.socket.send(JSON.stringify(install)) - expect(await retried).toMatchObject({ - type: 'device-credential-installed', - currentVersion: 1 - }) - splice.phone.close() - splice.data.close() - host.socket.close() - } finally { - await stopRelay(faultProcess, 'SIGKILL') - relayUrl = originalUrl - rmSync(faultData, { recursive: true, force: true }) - } - }) - - it('falls back to an invite only after a failed direct attempt is authoritatively not-found', async () => { - const originalUrl = relayUrl - const faultPort = await unusedPort() - const faultUrl = `http://127.0.0.1:${faultPort}` - const faultData = mkdtempSync(resolve(tmpdir(), 'orca-relay-direct-fault-')) - const faultProcess = spawnProcess({ - program: process.execPath, - args: ['--import', 'tsx', 'src/fault-injection-test-entry.ts'], - cwd: appDirectory, - env: { - ...process.env, - NODE_ENV: 'test', - PORT: String(faultPort), - ORCA_RELAY_PUBLIC_URL: faultUrl, - ORCA_RELAY_CELL_URL: faultUrl, - ORCA_RELAY_AUTH_ISSUER: issuer, - ORCA_RELAY_JWKS_URL: `${issuer}/jwks`, - ORCA_RELAY_ASSIGNMENT_SIGNING_KEY: assignmentKey, - ORCA_RELAY_DATA_DIR: faultData, - ORCA_RELAY_ADMIN_AUDIENCE: adminAudience, - ORCA_RELAY_DEPLOY_SERVICE_ACCOUNT: 'deploy@example.com', - ORCA_RELAY_ADMIN_JWKS_URL: `${issuer}/jwks`, - ORCA_RELAY_TEST_FAULT_SQL: 'INSERT INTO relay_direct_authorizations' - }, - stdio: ['ignore', 'pipe', 'pipe'] - }) - relayUrl = faultUrl - try { - await waitForRelay(faultProcess) - const host = await openHostControl() - const hostId = createHash('sha256') - .update(host.keyPair.publicKey) - .digest('base64url') - .slice(0, 16) - const inviteResponse = nextMessage(host.socket) - host.socket.send( - JSON.stringify({ - type: 'invite-create', - reqId: 'fallback-invite', - relayDeviceId: 'fallback-device' - }) - ) - const invite = await inviteResponse - const splice = await attachPhone({ - host: host.socket, - hostAck: host.ack, - hostId, - credential: String(invite.inviteToken) - }) - const installBase = { - type: 'device-credential-install', - v: 1, - reqId: 'fallback-install', - relayDeviceId: 'fallback-device', - newResumeTokenHash: createHash('sha256').update('fallback-resume').digest('base64url') - } - const directFailure = nextMessage(host.socket) - host.socket.send( - JSON.stringify({ - ...installBase, - authorization: { mode: 'authenticated-direct', directAuthId: 'failed-direct' } - }) - ) - expect(await directFailure).toMatchObject({ - type: 'control-error', - reqId: 'fallback-install', - code: 'control_operation_failed' - }) - const status = nextMessage(host.socket) - host.socket.send( - JSON.stringify({ - type: 'device-credential-install-status', - v: 1, - reqId: 'fallback-install', - relayDeviceId: 'fallback-device' - }) - ) - expect(await status).toMatchObject({ - type: 'device-credential-install-status-result', - state: 'not-found' - }) - const fallback = nextMessage(host.socket) - host.socket.send( - JSON.stringify({ - ...installBase, - authorization: { mode: 'relay-basis', basisConnId: splice.connId } - }) - ) - expect(await fallback).toMatchObject({ - type: 'device-credential-installed', - authorizationMode: 'relay-basis', - currentVersion: 1 - }) - splice.phone.close() - splice.data.close() - host.socket.close() - } finally { - await stopRelay(faultProcess, 'SIGKILL') - relayUrl = originalUrl - rmSync(faultData, { recursive: true, force: true }) - } - }) - - it('keeps director HTTP routes off cells and enforces the durable cell epoch', async () => { - const originalUrl = relayUrl - const cellPort = await unusedPort() - const cellUrl = `http://127.0.0.1:${cellPort}` - const cellData = mkdtempSync(resolve(tmpdir(), 'orca-relay-cell-')) - const keyPair = nacl.box.keyPair() - const hostId = createHash('sha256').update(keyPair.publicKey).digest('base64url').slice(0, 16) - const database = await openRelayDatabase({ dataDir: cellData }) - const assignments = new RelayAssignmentStore(database, () => 100) - await assignments.reconcileCells([{ id: 'cell-a', url: cellUrl, capacityRequests: 10 }]) - await assignments.assign({ userId: 'user-1', relayHostId: hostId }) - await database.close() - const cellProcess = spawnProcess({ - program: process.execPath, - args: ['--import', 'tsx', 'src/index.ts'], - cwd: appDirectory, - env: { - ...process.env, - PORT: String(cellPort), - ORCA_RELAY_PUBLIC_URL: cellUrl, - ORCA_RELAY_CELL_URL: cellUrl, - ORCA_RELAY_CELL_ID: 'cell-a', - ORCA_RELAY_CELL_CAPACITY: '10', - ORCA_RELAY_ROLE: 'cell', - ORCA_RELAY_AUTH_ISSUER: issuer, - ORCA_RELAY_JWKS_URL: `${issuer}/jwks`, - ORCA_RELAY_ASSIGNMENT_SIGNING_KEY: assignmentKey, - ORCA_RELAY_DATA_DIR: cellData, - ORCA_RELAY_ADMIN_AUDIENCE: adminAudience, - ORCA_RELAY_DEPLOY_SERVICE_ACCOUNT: 'deploy@example.com', - ORCA_RELAY_ADMIN_JWKS_URL: `${issuer}/jwks` - }, - stdio: ['ignore', 'pipe', 'pipe'] - }) - relayUrl = cellUrl - try { - await waitForRelay(cellProcess) - const token = await relayToken('orca-relay', hostId) - const assignmentResponse = await fetch(`${cellUrl}/v1/assign`, { - method: 'POST', - headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, - body: JSON.stringify({ v: 1, relayHostId: hostId }) - }) - expect(assignmentResponse.status).toBe(404) - const cellStatusResponse = await fetch(`${cellUrl}/v1/admin/cell-status`, { - method: 'POST', - headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, - body: JSON.stringify({ v: 1, cellId: 'cell-a' }) - }) - expect(cellStatusResponse.status).toBe(404) - - const stale = new WebSocket(`${cellUrl.replace('http:', 'ws:')}/v1/host/control`, { - headers: { authorization: `Bearer ${token}` } - }) - await new Promise((resolveOpen) => stale.once('open', resolveOpen)) - const staleClosed = new Promise((resolveClose) => - stale.once('close', (code) => resolveClose(code)) - ) - stale.send( - JSON.stringify({ - type: 'host-hello', - v: 1, - relayHostId: hostId, - assignmentEpoch: 2, - hostPublicKeyB64: Buffer.from(keyPair.publicKey).toString('base64'), - appVersion: 'test' - }) - ) - expect(await staleClosed).toBe(4409) - - const assigned = await openHostControl({ keyPair }) - expect(assigned.ack).toMatchObject({ type: 'host-hello-ack', generation: 1 }) - const invitePromise = nextMessage(assigned.socket) - assigned.socket.send( - JSON.stringify({ - type: 'invite-create', - reqId: 'cell-invite', - relayDeviceId: 'cell-device' - }) - ) - const invite = await invitePromise - const splice = await attachPhone({ - host: assigned.socket, - hostAck: assigned.ack, - hostId, - credential: String(invite.inviteToken) - }) - const observedDatabase = await openRelayDatabase({ dataDir: cellData }) - const activities = await observedDatabase.query( - `SELECT activity_kind, request_units FROM relay_assignment_activity_leases - ORDER BY activity_kind, activity_id` - ) - await observedDatabase.close() - expect(activities).toEqual([ - { activity_kind: 'control', request_units: 1 }, - { activity_kind: 'invite', request_units: 1 }, - { activity_kind: 'invite', request_units: 1 }, - { activity_kind: 'splice', request_units: 2 } - ]) - splice.phone.close() - splice.data.close() - assigned.socket.close() - } finally { - await stopRelay(cellProcess, 'SIGTERM') - relayUrl = originalUrl - rmSync(cellData, { recursive: true, force: true }) - } - }) - it('runs target-first dual-cell evacuation before releasing the source control', async () => { const originalUrl = relayUrl const dataDirectory = mkdtempSync(resolve(tmpdir(), 'orca-relay-topology-')) @@ -2627,236 +1370,4 @@ describe('served relay URL', () => { rmSync(signalData, { recursive: true, force: true }) } }) - - it('authenticates admin drain with exact Google audience and deploy identity', async () => { - const host = await openHostControl() - const drainMessage = nextMessage(host.socket) - const closed = new Promise((resolveClose) => - host.socket.once('close', (code) => resolveClose(code)) - ) - const token = await new SignJWT({ email: 'deploy@example.com', email_verified: true }) - .setProtectedHeader({ alg: 'RS256', kid: 'admin-key' }) - .setIssuer('https://accounts.google.com') - .setAudience(adminAudience) - .setSubject('deploy-subject') - .setIssuedAt() - .setExpirationTime('5m') - .sign(adminPrivateKey) - for (const invalid of [ - await googleServiceToken(`${adminAudience}/other`), - await googleServiceToken(adminAudience, 'other@example.com') - ]) { - expect( - ( - await fetch(`${relayUrl}/v1/admin/drain`, { - method: 'POST', - headers: { authorization: `Bearer ${invalid}`, 'content-type': 'application/json' }, - body: JSON.stringify({ v: 1, graceMs: 0 }) - }) - ).status - ).toBe(401) - } - const response = await fetch(`${relayUrl}/v1/admin/drain`, { - method: 'POST', - headers: { - authorization: `Bearer ${token}`, - 'content-type': 'application/json' - }, - body: JSON.stringify({ v: 1, graceMs: 0 }) - }) - expect(response.status).toBe(200) - expect(await drainMessage).toEqual({ - type: 'drain', - graceMs: 0, - recovery: 'resolve-director' - }) - expect(await closed).toBe(4503) - }) - - it('keeps dedicated capacity, monitor, and fence identities on exact routes', async () => { - const capacity = await googleServiceToken(adminAudience, 'capacity@example.com') - const monitor = await googleServiceToken(adminAudience, 'monitor@example.com') - const fence = await googleServiceToken(adminAudience, 'fence@example.com') - const broker = await googleServiceToken(adminAudience, 'broker@example.com') - const post = async (path: string, token: string, body: unknown): Promise => - await fetch(`${relayUrl}${path}`, { - method: 'POST', - headers: { - authorization: `Bearer ${token}`, - 'content-type': 'application/json' - }, - body: JSON.stringify(body) - }) - - expect((await post('/v1/admin/runtime-status', capacity, { v: 1 })).status).toBe(200) - expect( - ( - await post('/v1/admin/evacuation-status', capacity, { - v: 1, - sourceCellId: 'source', - targetCellId: 'target', - completeReady: false - }) - ).status - ).toBe(401) - expect( - ( - await post('/v1/admin/cell-fence-attempt-status', capacity, { - v: 1, - cellId: 'production-gce-c1' - }) - ).status - ).toBe(401) - - expect((await post('/v1/admin/runtime-status', monitor, { v: 1 })).status).toBe(200) - expect((await post('/v1/admin/drain', monitor, { v: 1, graceMs: 0 })).status).toBe(401) - expect( - ( - await post('/v1/admin/cell-fence-attempt-status', monitor, { - v: 1, - cellId: 'production-gce-c1' - }) - ).status - ).toBe(401) - - expect((await post('/v1/admin/runtime-status', fence, { v: 1 })).status).toBe(200) - expect((await post('/v1/admin/drain', fence, { v: 1, graceMs: 0 })).status).toBe(401) - expect( - ( - await post('/v1/admin/cell-fence-attempt-status', fence, { - v: 1, - cellId: 'production-gce-c1' - }) - ).status - ).toBe(404) - expect( - ( - await post('/v1/admin/cell-fence-attest', fence, { - v: 1 - }) - ).status - ).toBe(401) - - const directorPort = await unusedPort() - const directorUrl = `http://127.0.0.1:${directorPort}` - const directorData = mkdtempSync(resolve(tmpdir(), 'orca-relay-monitor-auth-')) - const director = spawnTopologyRelay({ - url: directorUrl, - dataDirectory: directorData, - role: 'director', - cellId: 'director', - cells: [{ id: 'cell-a', url: 'https://cell-a.example.com', capacityRequests: 10 }] - }) - try { - await waitForRelay(director) - const adoption = { - v: 1, - cellId: 'cell-a', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - confirmation: 'ADOPT_LEGACY_TERRAFORM_CELL_FENCE' - } - const postDirector = async (token: string): Promise => - await fetch(`${directorUrl}/v1/admin/cell-fence-adopt-legacy`, { - method: 'POST', - headers: { - authorization: `Bearer ${token}`, - 'content-type': 'application/json' - }, - body: JSON.stringify(adoption) - }) - expect((await postDirector(fence)).status).toBe(401) - expect((await postDirector(broker)).status).toBe(409) - const commitAdoption = { - v: 1, - cellId: 'cell-a', - cellIncarnation: '11111111-1111-4111-8111-111111111111', - confirmation: 'COMMIT_LEGACY_TERRAFORM_CELL_FENCE_ADOPTION' - } - const postCommit = async (token: string): Promise => - await fetch(`${directorUrl}/v1/admin/cell-fence-commit-legacy-adoption`, { - method: 'POST', - headers: { - authorization: `Bearer ${token}`, - 'content-type': 'application/json' - }, - body: JSON.stringify(commitAdoption) - }) - expect((await postCommit(fence)).status).toBe(401) - expect((await postCommit(broker)).status).toBe(409) - const response = await fetch(`${directorUrl}/v1/admin/evacuation-status`, { - method: 'POST', - headers: { - authorization: `Bearer ${monitor}`, - 'content-type': 'application/json' - }, - body: JSON.stringify({ - v: 1, - sourceCellId: 'cell-a', - targetCellId: 'cell-b', - completeReady: true - }) - }) - expect(response.status).toBe(403) - const fenceResponse = await fetch(`${directorUrl}/v1/admin/evacuation-status`, { - method: 'POST', - headers: { - authorization: `Bearer ${fence}`, - 'content-type': 'application/json' - }, - body: JSON.stringify({ - v: 1, - sourceCellId: 'cell-a', - targetCellId: 'cell-b', - completeReady: true - }) - }) - expect(fenceResponse.status).toBe(403) - } finally { - await stopRelay(director) - rmSync(directorData, { recursive: true, force: true }) - } - }) - - it('reports only authenticated aggregate runtime identity and the served digest', async () => { - const token = await adminToken() - expect( - await fetch(`${relayUrl}/v1/admin/runtime-status`, { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ v: 1 }) - }) - ).toMatchObject({ status: 401 }) - expect( - await fetch(`${relayUrl}/v1/admin/runtime-status`, { - method: 'POST', - headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, - body: JSON.stringify({ v: 1, hostId: 'must-not-be-accepted' }) - }) - ).toMatchObject({ status: 400 }) - const response = await fetch(`${relayUrl}/v1/admin/runtime-status`, { - method: 'POST', - headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, - body: JSON.stringify({ v: 1 }) - }) - expect(response.status).toBe(200) - expect(await response.json()).toEqual({ - v: 1, - role: 'combined', - cellId: 'combined', - cellUrl: relayUrl, - region: 'us-central1', - imageDigest: `sha256:${'a'.repeat(64)}`, - draining: true, - regionalRehomeProtocol: 0, - connectionCapacity: null, - runtime: { - totalConnections: 0, - preAuthConnections: 0, - controls: 0, - splices: 0, - pendingSplices: 0, - queuedBytes: 0 - } - }) - }) }) diff --git a/config/build-plugins/main-build-entry-points.ts b/config/build-plugins/main-build-entry-points.ts index 819c08e1680..fa07be54928 100644 --- a/config/build-plugins/main-build-entry-points.ts +++ b/config/build-plugins/main-build-entry-points.ts @@ -19,7 +19,9 @@ export const MAIN_BUILD_ENTRY_POINTS: Record = { ), 'stt-worker': resolve('src/main/speech/stt-worker.ts'), 'warp-theme-parser-worker': resolve('src/main/warp-themes/warp-theme-parser-worker.ts'), - 'session-search-worker-entry': resolve('src/main/ai-vault-search/session-search-worker-entry.ts'), + 'session-search-worker-entry': resolve( + 'src/main/ai-vault-search/worker/session-search-worker-entry.ts' + ), 'foreign-sqlite-reader-entry': resolve( 'src/main/foreign-sqlite-readers/foreign-sqlite-reader-entry.ts' ), @@ -39,7 +41,7 @@ export const MAIN_BUILD_ENTRY_POINTS: Record = { 'src/main/worker-thread-child-process/worker-thread-child-process-entry.ts' ), // Usage scans synchronously walk histories/SQLite; keep them off the main loop. - 'usage-scan-worker-entry': resolve('src/main/usage/usage-scan-worker-entry.ts'), + 'usage-scan-worker-entry': resolve('src/main/usage/scan-worker/usage-scan-worker-entry.ts'), 'workspace-space-scan-worker-entry': resolve( 'src/main/workspaces/space-analysis/workspace-space-scan-worker-entry.ts' ), diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 6a9080e53e8..50807f17ed6 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -291,7 +291,6 @@ 1 test-no-real-time-wait:tests/e2e/codex-ctrl-c-status.spec.ts 4 test-no-real-time-wait:tests/e2e/combined-diff-scroll-restore.spec.ts 1 test-no-real-time-wait:tests/e2e/computer-windows.e2e.ts -1 test-no-real-time-wait:tests/e2e/cross-version-wire/cross-version-agent-session-wire.unit.test.ts 3 test-no-real-time-wait:tests/e2e/cross-version-wire/host-model-catalog-released-phone.unit.test.ts 1 test-no-real-time-wait:tests/e2e/cross-version-wire/legacy-relay-bridge.unit.test.ts 1 test-no-real-time-wait:tests/e2e/cross-version-wire/released-relay-daemon.ts @@ -453,9 +452,8 @@ 4 test-no-wall-clock:src/main/agent-hooks/server/testing/identity/server-launch-resume-identity.test.ts 5 test-no-wall-clock:src/main/agent-hooks/server/testing/replay/spool.test.ts 2 test-no-wall-clock:src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts -2 test-no-wall-clock:src/main/ai-vault-search/session-search-indexer.test.ts +1 test-no-wall-clock:src/main/ai-vault-search/indexing/session-search-indexer.test.ts 1 test-no-wall-clock:src/main/ai-vault/parse-cache/session-parse-cache-preview-upgrade.test.ts -1 test-no-wall-clock:src/main/ai-vault/scanners/copilot/session-scanner-copilot-cache-upgrade.test.ts 2 test-no-wall-clock:src/main/ai-vault/scanners/copilot/session-scanner-copilot-parser.test.ts 2 test-no-wall-clock:src/main/ai-vault/scanners/cursor/session-scanner-cursor-chat-meta.test.ts 1 test-no-wall-clock:src/main/ai-vault/scanners/devin/session-scanner-devin-db.test.ts @@ -507,7 +505,6 @@ 3 test-no-wall-clock:src/main/github/pr-refresh-coordinator-active-visible-priority.test.ts 8 test-no-wall-clock:src/main/github/pr-refresh-coordinator-alias-coalescing.test.ts 5 test-no-wall-clock:src/main/github/pr-refresh-coordinator-completion-order.test.ts -1 test-no-wall-clock:src/main/github/pr-refresh-coordinator-error-cadence.test.ts 3 test-no-wall-clock:src/main/github/pr-refresh-coordinator-foreground-pacing.test.ts 3 test-no-wall-clock:src/main/github/pr-refresh-coordinator-refresh-events.test.ts 4 test-no-wall-clock:src/main/github/pr-refresh-coordinator-visibility-policy.test.ts @@ -526,8 +523,8 @@ 1 test-no-wall-clock:src/main/observability/bundle.test.ts 1 test-no-wall-clock:src/main/opencode/opencode-launch-model-context-supervision.test.ts 1 test-no-wall-clock:src/main/opencode/overlay-dir-gc.test.ts -2 test-no-wall-clock:src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts -2 test-no-wall-clock:src/main/orca-profiles/profile-cloud-service-sign-out-connect-race.test.ts +2 test-no-wall-clock:src/main/orca-profiles/cloud-auth/profile-cloud-service-connect-overlap.test.ts +2 test-no-wall-clock:src/main/orca-profiles/cloud-auth/profile-cloud-service-sign-out-connect-race.test.ts 2 test-no-wall-clock:src/main/orcad/orcad-artifact-cache-retention.test.ts 1 test-no-wall-clock:src/main/orcad/orcad-artifact-materializer.test.ts 6 test-no-wall-clock:src/main/orcad/orcad-serve-parity.integration.test.ts @@ -614,7 +611,6 @@ 3 test-no-wall-clock:src/main/windows/windows-msys-job.win32.test.ts 1 test-no-wall-clock:src/main/windows/windows-process-table-native-addon.win32.test.ts 2 test-no-wall-clock:src/main/windows/windows-pty-job.win32.test.ts -2 test-no-wall-clock:src/main/workspace-hooks/hook-archive-timeout-observation.test.ts 2 test-no-wall-clock:src/main/workspaces/removal/local-worktree-removal-recovery-live.test.ts 1 test-no-wall-clock:src/main/workspaces/removal/worktree-removal-close-records.test.ts 2 test-no-wall-clock:src/main/wsl/execution/wsl-runner.wsl.test.ts @@ -627,7 +623,6 @@ 2 test-no-wall-clock:src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx 1 test-no-wall-clock:src/renderer/src/components/sidebar/workspace-card/review/use-workspace-reference-details.test.tsx 1 test-no-wall-clock:src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-agent-expansion-coupling.test.tsx -2 test-no-wall-clock:src/renderer/src/components/task-page/jira/task-page-jira-cache-selectors.test.ts 2 test-no-wall-clock:src/renderer/src/components/terminal-pane/pty-connection/emulation/fish-color-scheme-child-stdin.node-pty.test.ts 2 test-no-wall-clock:src/renderer/src/components/terminal-pane/snapshots/remote-snapshot-alt-screen-host-chain.test.ts 1 test-no-wall-clock:src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx @@ -750,7 +745,7 @@ 1 test-timeout-needs-reason:src/main/windows/windows-msys-job.win32.test.ts 2 test-timeout-needs-reason:src/main/windows/windows-pty-job.win32.test.ts 5 test-timeout-needs-reason:src/main/worker-thread-child-process/worker-thread-child-process.test.ts -2 test-timeout-needs-reason:src/main/workspace-hooks/hook-archive-timeout-observation.test.ts +1 test-timeout-needs-reason:src/main/workspace-hooks/hook-archive-timeout-observation.test.ts 2 test-timeout-needs-reason:src/main/workspace-hooks/hook-termination-real-process.test.ts 2 test-timeout-needs-reason:src/main/workspaces/removal/local-worktree-filesystem-wsl-banner.wsl.test.ts 4 test-timeout-needs-reason:src/main/wsl/execution/wsl-runner.wsl.test.ts diff --git a/config/knip.json b/config/knip.json index c9fe794f998..ff61d06a755 100644 --- a/config/knip.json +++ b/config/knip.json @@ -41,7 +41,7 @@ "src/main/plugins/testing/plugin-test-register.ts", "src/main/ai-vault/scan-service/session-scanner-service-entry.ts", "src/main/native-chat/wsl-transcript-fs-process-entry.ts", - "src/main/usage/usage-scan-worker-entry.ts", + "src/main/usage/scan-worker/usage-scan-worker-entry.ts", "src/main/workspaces/space-analysis/workspace-space-scan-worker-entry.ts", "src/main/claude-accounts/claude-profile-setup-worker-entry.ts", "src/main/persistence/profile-state/profile-state-backup-worker-entry.ts", diff --git a/config/legacy-relay-importers-baseline.txt b/config/legacy-relay-importers-baseline.txt index c48864aa1ed..8696af1340b 100644 --- a/config/legacy-relay-importers-baseline.txt +++ b/config/legacy-relay-importers-baseline.txt @@ -2,7 +2,6 @@ # The relay retirement (2027-01-15) deletes the folder and edits exactly these files. # Prune: pnpm check:legacy-relay-fence-ratchet --prune src/main/ipc/runtime-environments/orcad-delta-move-handlers.ts -src/main/ipc/pty/runtime/kill-legacy-relay-bridged.test.ts src/main/ipc/pty/runtime/kill.ts src/main/ipc/ssh/ssh-connect-decision-cancellation.test.ts src/main/ipc/ssh/ssh-connect-flow.ts diff --git a/config/main-layout-writer-baseline.txt b/config/main-layout-writer-baseline.txt index 54fb801ea75..0cd1bcfbaae 100644 --- a/config/main-layout-writer-baseline.txt +++ b/config/main-layout-writer-baseline.txt @@ -11,12 +11,12 @@ 1 src/main/ipc/runtime-environments/runtime-environment-removal-cleanup.ts 1 src/main/ipc/runtime-environments/runtime-environment-session-reconcile.ts 2 src/main/ipc/session.ts -6 src/main/orca-profiles/profile-project-session-state.ts -4 src/main/orca-profiles/profile-project-source-removal.ts -2 src/main/orca-profiles/profile-project-state-file.ts -4 src/main/orca-profiles/profile-project-transfer-payload.ts -2 src/main/orca-profiles/profile-project-transfer.ts -9 src/main/orca-profiles/profile-session-owner-transfer.ts +6 src/main/orca-profiles/project-transfer/profile-project-session-state.ts +4 src/main/orca-profiles/project-transfer/profile-project-source-removal.ts +2 src/main/orca-profiles/project-transfer/profile-project-state-file.ts +4 src/main/orca-profiles/project-transfer/profile-project-transfer-payload.ts +2 src/main/orca-profiles/project-transfer/profile-project-transfer.ts +9 src/main/orca-profiles/project-transfer/profile-session-owner-transfer.ts 3 src/main/persistence/leasing-ssh-ptys/ssh-pty-binding-cleanup.ts 1 src/main/persistence/loading-store/loaded-state-parsing.ts 1 src/main/persistence/loading-store/metadata-lineage-operations.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 16885fe4f6e..001dbe65eaa 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -14,7 +14,7 @@ 14 src/main/agent-launch/trust/agent-trust-presets.ts 2 src/main/agent-launch/trust/antigravity-workspace-trust-ownership.ts 1 src/main/agent-launch/trust/execution-host-workspace-trust.ts -1 src/main/ai-vault-search/session-search-worker-client.ts +1 src/main/ai-vault-search/worker/session-search-worker-client.ts 4 src/main/ai-vault/parse-cache/session-parse-cache-legacy-json.ts 2 src/main/ai-vault/scan-service/session-scanner-service-entry-path.ts 1 src/main/ai-vault/scan-service/session-scanner-service-spawn.ts @@ -329,16 +329,16 @@ 1 src/main/opencode/opencode-plugin-config-writer.ts 1 src/main/opencode/opencode-private-server.ts 1 src/main/opencode/opencode-wsl-text-task.ts -2 src/main/orca-profiles/new-profile-state.ts -3 src/main/orca-profiles/other-profile-workspace-catalog.ts -3 src/main/orca-profiles/profile-artifact-cloud-cleanup.ts -1 src/main/orca-profiles/profile-cloud-index.ts -4 src/main/orca-profiles/profile-cloud-session-store.ts +2 src/main/orca-profiles/storage/new-profile-state.ts +3 src/main/orca-profiles/catalog/other-profile-workspace-catalog.ts +3 src/main/orca-profiles/cloud-auth/profile-artifact-cloud-cleanup.ts +1 src/main/orca-profiles/cloud-auth/profile-cloud-index.ts +4 src/main/orca-profiles/cloud-session/profile-cloud-session-store.ts 12 src/main/orca-profiles/profile-index-store.ts -5 src/main/orca-profiles/profile-legacy-state-import.ts -4 src/main/orca-profiles/profile-project-move-intent.ts -3 src/main/orca-profiles/profile-project-move-record.ts -4 src/main/orca-profiles/profile-project-state-file.ts +5 src/main/orca-profiles/storage/profile-legacy-state-import.ts +4 src/main/orca-profiles/project-transfer/profile-project-move-intent.ts +3 src/main/orca-profiles/project-transfer/profile-project-move-record.ts +4 src/main/orca-profiles/project-transfer/profile-project-state-file.ts 2 src/main/orcad/launcher.ts 7 src/main/orcad/node-pty-prebuilt-slot.ts 2 src/main/orcad/node-pty-precondition.ts @@ -493,9 +493,9 @@ 1 src/main/runtime/workspaces/persisted-surfaces/crew-operations.ts 1 src/main/server/serve-pairing-output.ts 2 src/main/speech/model-cache-path.ts -9 src/main/speech/model-manager.ts +7 src/main/speech/model-manager.ts 10 src/main/speech/openai-api-key-store.ts -2 src/main/speech/speech-model-download-cleanup.ts +1 src/main/speech/speech-model-download-cleanup.ts 1 src/main/speech/speech-model-download-transport.ts 1 src/main/speech/speech-model-files.ts 2 src/main/speech/speech-model-http-download.ts @@ -539,8 +539,8 @@ 1 src/main/updater/linux-package/linux-package-install-command.ts 1 src/main/updater/linux-package/linux-update-package-type.ts 6 src/main/updater/serve-update-handoff.ts -2 src/main/usage/usage-provider-store-lifecycle.ts -1 src/main/usage/usage-scan-worker-spawn.ts +2 src/main/usage/provider-lifecycle/usage-provider-store-lifecycle.ts +1 src/main/usage/scan-worker/usage-scan-worker-spawn.ts 1 src/main/warp-themes/discovery.ts 1 src/main/window/desktop-integration/custom-app-icon.ts 3 src/main/window/desktop-integration/macos-press-and-hold-default.ts diff --git a/config/react-compiler-bailout-baseline.txt b/config/react-compiler-bailout-baseline.txt index 12aa339d614..dfecf68829a 100644 --- a/config/react-compiler-bailout-baseline.txt +++ b/config/react-compiler-bailout-baseline.txt @@ -99,11 +99,11 @@ 1 src/renderer/src/components/editor/combined-diff/resolve-changes/use-combined-diff-section-row-keys.ts 1 src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-notes-actions.ts 1 src/renderer/src/components/editor/combined-diff/scroll-viewport/use-combined-diff-virtualizer.ts -1 src/renderer/src/components/editor/csv/CsvGrid.tsx +1 src/renderer/src/components/editor/csv/grid/CsvGrid.tsx 1 src/renderer/src/components/editor/csv/CsvViewer.tsx -1 src/renderer/src/components/editor/csv/useCsvClipboard.ts -1 src/renderer/src/components/editor/csv/useCsvPagedPreview.ts -3 src/renderer/src/components/editor/csv/useCsvTableEditor.ts +1 src/renderer/src/components/editor/csv/editing/clipboard/useCsvClipboard.ts +1 src/renderer/src/components/editor/csv/preview/useCsvPagedPreview.ts +3 src/renderer/src/components/editor/csv/editing/useCsvTableEditor.ts 1 src/renderer/src/components/editor/diff/large-files/useDiffViewerLargeDiffLifecycle.ts 3 src/renderer/src/components/editor/diff/monaco-view/DiffViewer.tsx 1 src/renderer/src/components/editor/diff/review/DiffNotesSendMenu.tsx @@ -145,7 +145,7 @@ 3 src/renderer/src/components/editor/useEditorPanelFileContentLoader.ts 4 src/renderer/src/components/editor/useLocalLogTail.ts 1 src/renderer/src/components/editor/usePreserveSectionDuringExternalEdit.ts -7 src/renderer/src/components/emulator-pane/emulator-screen-stream-content.tsx +1 src/renderer/src/components/emulator-pane/emulator-screen-stream-content.tsx 3 src/renderer/src/components/emulator-pane/use-emulator-pane-session.ts 1 src/renderer/src/components/emulator-pane/use-emulator-pane-shutdown.ts 1 src/renderer/src/components/emulator-pane/use-emulator-video-stream.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index b8a6a7c0c5a..6a0dbdbba30 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -454,16 +454,16 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime", "mobile-relay"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Affected sources: mobile/src/session/mobile-prompt-controller.test.ts, tests/e2e/native-chat-ssh-delivery.unit.test.ts, mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-cancel-ask.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Historical scope: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1471 removes the entire interactive-send hook suite. Its mock-writer routing, cancellation-handle, option-digit, interrupt, supplied settlement and inference-argument alarms are retired. No actual PTY bytes, replacement question lifetime or agent delivery were exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Audit1468 removes the entire runtime-send suite. Its mock PTY clear/body/Enter byte-order, nominal timing, queue cancellation/serialization, attachment escaping, key-group pacing and deferred acceptance callback alarms are intentionally retired. No actual receiving agent or physical terminal delivery was exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/lib/agent-paste-draft-submit-retry.test.ts: Loses configured retry gap and single-Enter agent selection alarms alongside forbidden timer-count checks. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1383 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audits1340 and1348 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1316 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Production mobile controller, parser, presentation, overlay, view, question, permission and composer run with native surfaces mocked on macOS. Desktop selector groups traverse the real observed-write queue, verified helper, IPC chunker, SSH provider and transport callbacks; paired sends traverse the real dispatcher and runtime writer into that provider. Local/daemon contracts and released-version terminal codecs are covered. Provider labels describe contracts, not physical deployments; physical WSL/Linux/Windows remain gaps. Audit885 removes the isolated observed-send mock-call suite; no replacement-equivalence claim is made. Audit1107 removes the small healthy ordinary SSH-send byte/callback sample. Its exact clear/body/Enter sample alarm is lost; retained slow-answer, cancellation and simulated older-host sequence checks are not claimed as equivalent replacement coverage. The SSH delivery fixture uses controlled fake provider settlement, and its paired path uses the real runtime/dispatcher without a physical SSH or paired wire transport. Audit1278 removes the mobile Stop display/disabled/placeholder suite; its local Stop presentation, repeat-stop and dispatch-visibility alarms are intentionally lost. No equivalent replacement or runtime stopping proof is claimed. Audit1292: The blind OpenCode readiness warning and late launch success/failure content-plus-submit write samples are removed. Their mocked readiness/inspection/delivery alarms are lost; no real PTY delivery or equivalent replacement coverage is claimed. Audit1294 removes mobile/src/session/native-chat/input/mobile-native-chat-permission-send.test.ts. Its mock-only request/capability/private-state/copy alarms are intentionally lost. Remaining tests are not equivalent replacement coverage. Narrowed commands require fresh parent-owned validation; no new runtime, platform or physical mobile evidence is claimed. Audit1302: src/main/ipc/pty/ipc/write-input-acceptance.test.ts: Provider registry and write acceptance/refusal/unverifiable receipts are supplied by fixture; local/daemon/WSL/SSH labels use the same fake provider. Chunking/settlement/remount cases inspect delegated calls or canned receipts without actual provider acceptance/acknowledgement. Lose chunk/refusal/pending/remount and raw-pane routing alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1303 intentionally removes supplied-state/mock-callback component and hook examples in mobile/src/session/native-chat/input/use-mobile-native-chat-ask-dismiss.test.ts, mobile/src/session/native-chat/input/MobileNativeChatPromptCard.test.tsx. Their exact retired alarms are not equivalent to retained coverage; no new runtime, physical phone or deployed mixed-version evidence is claimed. Audit1310 removes the supplied-geometry/direct-callback chat history-paging suite. Its prepend/scroll-position examples are intentionally lost; no real rendered anchoring, equivalent replacement or physical phone proof is claimed. Narrowed commands need fresh validation. Audit1315 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.composer-lock.test.ts, mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1316: src/renderer/src/lib/agent-followup-delivery.test.ts removed. Interpreter wrapper/live child/shell readiness and final readiness recheck delivery mock samples lose alarms. No equivalent replacement coverage is claimed. Audit1322 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.tail-follow.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1334 removes/narrows mobile/src/session/native-chat/mobile-native-chat-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1335 removes/narrows mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/mobile-prompt-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1340: src/main/daemon/daemon-pty-write-settlement-recovery.test.ts removed. Ambiguous handoff settlement remains unverifiable when listener throws. No equivalent replacement coverage is claimed. Audit1348: src/main/ipc/pty/ipc/write-input-chunk-yield.test.ts removed. Check-phase yielding and no-yield single-chunk scheduling work. No equivalent replacement coverage is claimed. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Lose admission provenance spy, direct local Escape write outcome matrix and separate client-side SSH no-evidence control. Provider writes mocked; retained tests protect observation order/facts only. No equivalent replacement coverage is claimed. Audit1401: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Loses local-only post-accept observation and refused/unverifiable settlement delivery alarms. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/native-chat/native-chat-runtime-send-launch-draft.test.ts removed. Intentionally loses clear-confirmation/body/submit and maximal-clear ordering, queued text/image send ordering, ordinary cursor-spanning draft replacement and oversized refusal/queue settlement alarms. No equivalent replacement or real terminal delivery claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1426 removes NativeChatComposer.test.tsx. Local pane-remount, draft/cancel/confirmation sequencing and manual IME callback alarms are lost. No equivalent replacement coverage or provider delivery is claimed; historical receipts retain their original scope and the reduced selector has no new execution result. Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim.", + "coverageNotes": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The entire mocked mobile failure-banner suite and its sole send/previous-banner/new-notice ordering alarm are retired. Its filenames are removed from active selectors. Desktop prompt roots and the independent unchanged terminal wire-codec receipt remain at their stated scopes; no mobile send/recovery proof is claimed. Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Affected sources: mobile/src/session/mobile-prompt-controller.test.ts, tests/e2e/native-chat-ssh-delivery.unit.test.ts, mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-cancel-ask.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Historical scope: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1471 removes the entire interactive-send hook suite. Its mock-writer routing, cancellation-handle, option-digit, interrupt, supplied settlement and inference-argument alarms are retired. No actual PTY bytes, replacement question lifetime or agent delivery were exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Audit1468 removes the entire runtime-send suite. Its mock PTY clear/body/Enter byte-order, nominal timing, queue cancellation/serialization, attachment escaping, key-group pacing and deferred acceptance callback alarms are intentionally retired. No actual receiving agent or physical terminal delivery was exercised. No equivalent replacement or fresh execution of the reduced reliability selector is claimed; historical receipts retain their original scope. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/lib/agent-paste-draft-submit-retry.test.ts: Loses configured retry gap and single-Enter agent selection alarms alongside forbidden timer-count checks. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1383 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audits1340 and1348 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1316 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Production mobile controller, parser, presentation, overlay, view, question, permission and composer run with native surfaces mocked on macOS. Desktop selector groups traverse the real observed-write queue, verified helper, IPC chunker, SSH provider and transport callbacks; paired sends traverse the real dispatcher and runtime writer into that provider. Local/daemon contracts and released-version terminal codecs are covered. Provider labels describe contracts, not physical deployments; physical WSL/Linux/Windows remain gaps. Audit885 removes the isolated observed-send mock-call suite; no replacement-equivalence claim is made. Audit1107 removes the small healthy ordinary SSH-send byte/callback sample. Its exact clear/body/Enter sample alarm is lost; retained slow-answer, cancellation and simulated older-host sequence checks are not claimed as equivalent replacement coverage. The SSH delivery fixture uses controlled fake provider settlement, and its paired path uses the real runtime/dispatcher without a physical SSH or paired wire transport. Audit1278 removes the mobile Stop display/disabled/placeholder suite; its local Stop presentation, repeat-stop and dispatch-visibility alarms are intentionally lost. No equivalent replacement or runtime stopping proof is claimed. Audit1292: The blind OpenCode readiness warning and late launch success/failure content-plus-submit write samples are removed. Their mocked readiness/inspection/delivery alarms are lost; no real PTY delivery or equivalent replacement coverage is claimed. Audit1294 removes mobile/src/session/native-chat/input/mobile-native-chat-permission-send.test.ts. Its mock-only request/capability/private-state/copy alarms are intentionally lost. Remaining tests are not equivalent replacement coverage. Narrowed commands require fresh parent-owned validation; no new runtime, platform or physical mobile evidence is claimed. Audit1302: src/main/ipc/pty/ipc/write-input-acceptance.test.ts: Provider registry and write acceptance/refusal/unverifiable receipts are supplied by fixture; local/daemon/WSL/SSH labels use the same fake provider. Chunking/settlement/remount cases inspect delegated calls or canned receipts without actual provider acceptance/acknowledgement. Lose chunk/refusal/pending/remount and raw-pane routing alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1303 intentionally removes supplied-state/mock-callback component and hook examples in mobile/src/session/native-chat/input/use-mobile-native-chat-ask-dismiss.test.ts, mobile/src/session/native-chat/input/MobileNativeChatPromptCard.test.tsx. Their exact retired alarms are not equivalent to retained coverage; no new runtime, physical phone or deployed mixed-version evidence is claimed. Audit1310 removes the supplied-geometry/direct-callback chat history-paging suite. Its prepend/scroll-position examples are intentionally lost; no real rendered anchoring, equivalent replacement or physical phone proof is claimed. Narrowed commands need fresh validation. Audit1315 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.composer-lock.test.ts, mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1316: src/renderer/src/lib/agent-followup-delivery.test.ts removed. Interpreter wrapper/live child/shell readiness and final readiness recheck delivery mock samples lose alarms. No equivalent replacement coverage is claimed. Audit1322 removes/narrows mobile/src/session/native-chat/MobileNativeChatView.tail-follow.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1334 removes/narrows mobile/src/session/native-chat/mobile-native-chat-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1341 scope1335 removes/narrows mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/mobile-prompt-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts. Exact retired scenarios are intentionally lost; surviving assertions are limited to unchanged retained authored cases. No equivalent replacement, physical phone or deployed mixed-host claim. Fresh validation is required for narrowed commands. Audit1340: src/main/daemon/daemon-pty-write-settlement-recovery.test.ts removed. Ambiguous handoff settlement remains unverifiable when listener throws. No equivalent replacement coverage is claimed. Audit1348: src/main/ipc/pty/ipc/write-input-chunk-yield.test.ts removed. Check-phase yielding and no-yield single-chunk scheduling work. No equivalent replacement coverage is claimed. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Lose admission provenance spy, direct local Escape write outcome matrix and separate client-side SSH no-evidence control. Provider writes mocked; retained tests protect observation order/facts only. No equivalent replacement coverage is claimed. Audit1401: src/main/ipc/pty/ipc/write-input-user-input.test.ts reduced. Loses local-only post-accept observation and refused/unverifiable settlement delivery alarms. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/native-chat/native-chat-runtime-send-launch-draft.test.ts removed. Intentionally loses clear-confirmation/body/submit and maximal-clear ordering, queued text/image send ordering, ordinary cursor-spanning draft replacement and oversized refusal/queue settlement alarms. No equivalent replacement or real terminal delivery claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1426 removes NativeChatComposer.test.tsx. Local pane-remount, draft/cancel/confirmation sequencing and manual IME callback alarms are lost. No equivalent replacement coverage or provider delivery is claimed; historical receipts retain their original scope and the reduced selector has no new execution result. Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim.", "motivatingLinks": ["https://github.com/stablyai/orca/pull/25761"], "invariant": "A prompt occurrence leaves the input region only when an accepted reply answers it (a current host's provider acknowledgment, or an older host's whole-write acceptance as before) or the user collapses it to a strip above the composer, which writes nothing and keeps the card mounted with its partial answer; status-backed occurrences are told apart by the host wait's start, so view toggles and remounts preserve them while real clear/replacement supersedes them, and a transcript-only one is dropped when the view stops observing it; obsolete results cannot change replacements; selector groups wait for complete writes before pacing; refusal or unknown handoff never causes replay; a card retires an unsubmitted composer send without writing under it or losing its text, and the hidden composer cannot send or interrupt; Collapse or Escape folds a card without writing, never during an in-flight answer, and a new occurrence shows expanded again; the phone blocks only Send while a card is expanded and shows one card per occurrence; cancellation stops unsent groups and active dictation can stop.", - "oracle": "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Historical oracle: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): After acknowledged phone replies with stale host status, the exact card disappears and Send is enabled; unknown, refused or unverifiable-settlement replies retain enabled choices, while an older host's accepted reply dismisses like an acknowledged one; a same-occurrence view toggle retains pending acknowledgment and real replacements discard it. A slow 32 KiB SSH answer completes all chunks before Enter; cancellation preserves issued bytes but omits remaining groups. Paired settlement invokes the actual provider and lost callbacks remain unknown; older hosts deliver ordinary messages, launch and selector groups once and their accepted answers dismiss as before. An answered card stays hidden across a view remount; a collapsed card is a strip that frees the composer and expands back; an identical question in a new wait shows again; a composer send caught by a new card keeps its bubble without submitting or clearing the line under it. Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim.", + "oracle": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The entire mocked mobile failure-banner suite and its sole send/previous-banner/new-notice ordering alarm are retired. Its filenames are removed from active selectors. Desktop prompt roots and the independent unchanged terminal wire-codec receipt remain at their stated scopes; no mobile send/recovery proof is claimed. Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Historical oracle: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): After acknowledged phone replies with stale host status, the exact card disappears and Send is enabled; unknown, refused or unverifiable-settlement replies retain enabled choices, while an older host's accepted reply dismisses like an acknowledged one; a same-occurrence view toggle retains pending acknowledgment and real replacements discard it. A slow 32 KiB SSH answer completes all chunks before Enter; cancellation preserves issued bytes but omits remaining groups. Paired settlement invokes the actual provider and lost callbacks remain unknown; older hosts deliver ordinary messages, launch and selector groups once and their accepted answers dismiss as before. An answered card stays hidden across a view remount; a collapsed card is a strip that frees the composer and expands back; an identical question in a new wait shows again; a composer send caught by a new card keeps its bubble without submitting or clearing the line under it. Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim.", "commands": [ "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts src/main/runtime/terminal/input/runtime-terminal-writer.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/runtime/terminal/input/terminal-send-stale-leaf-liveness.test.ts --maxWorkers=2", - "ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts mobile/src/session/native-chat/input/mobile-prompt-controller.test.ts --maxWorkers=2", + "ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts mobile/src/session/native-chat/input/mobile-prompt-controller.test.ts --maxWorkers=2", "ORCA_BACKGROUND_LAUNCH=1 pnpm test tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts --maxWorkers=1", "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts --maxWorkers=2", - "ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts --maxWorkers=2" + "ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts --maxWorkers=2" ], "testFiles": [ "src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx", @@ -478,8 +478,6 @@ "src/main/runtime/terminal/input/runtime-terminal-writer.test.ts", "src/main/runtime/rpc/terminal-send.test.ts", "src/main/runtime/terminal/input/terminal-send-stale-leaf-liveness.test.ts", - - "mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts", "mobile/src/session/native-chat/input/mobile-prompt-controller.test.ts", "tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts" ], @@ -601,7 +599,8 @@ "Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Affected sources: mobile/src/session/mobile-prompt-controller.test.ts, tests/e2e/native-chat-ssh-delivery.unit.test.ts, mobile/src/session/native-chat/use-mobile-native-chat-controller.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-cancel-ask.test.ts, mobile/src/session/native-chat/input/use-mobile-native-chat-answer-send.test.ts, mobile/src/session/native-chat/transcript/use-mobile-native-chat-message-send.test.ts.", "Historical assertion references before mobile owner-layout policy; removed references have no replacement claim: [{\"file\":\"src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx\",\"assertions\":[\"ignores a raw acknowledgment from a rebound PTY\",\"sends only one cancellation, can cancel an answer, and permits retry after unknown\"]},{\"file\":\"mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts\",\"assertions\":[\"a late answer cannot reshow an answered replacement occurrence\",\"a late answer cannot dismiss a replacement session\"]},{\"file\":\"mobile/src/session/mobile-prompt-controller.test.ts\",\"assertions\":[\"finishes an older-host selector once and dismisses it like an acknowledged answer\",\"dismisses older-host approval choice %i like an acknowledged answer and restores Send\",\"retains permission choices on %s\",\"acknowledges the same pending %s after a view-only toggle\",\"shows a collapsed prompt again as a new wait\",\"keeps an acknowledged Deny hidden after the chat screen remounts on a lingering status\",\"drops an accepted result after real %s replacement\",\"keeps an agent notice answerable and retires only human input through the %s view\",\"retains exact cancelled calls through edits, prefix/ID replay, paging and new equal rows (%s)\",\"keeps structured %s admission separate from captured Cancel and delivered rows\",\"settles the terminal answer for Q1 after Q2 arrives without hiding Q2\",\"fences a late captured structured answer after %s replacement\",\"does not turn real %s host-result conversion into an answered question\",\"keeps later same-ID Cancel after eviction/reentry and old answer settlement\",\"keeps structured answer controls after a thrown send\",\"isolates equal portable IDs on two hosts and rejects the old host callback\"]},{\"file\":\"tests/e2e/native-chat-ssh-delivery.unit.test.ts\",\"assertions\":[\"serializes every chunk of a healthy large SSH answer before Enter and dismissal\",\"cancels remaining paced groups while an already-issued body still settles\",\"paired terminal.send uses provider settlement for accepted and lost acknowledgment\",\"older paired hosts keep their whole-write verdict for answers and ordinary sequences\",\"older paired hosts confirm ordinary chat sends and pasted answers as before\",\"finishes every older-host selector group once and settles the answer as delivered\"]},{\"file\":\"src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx\",\"assertions\":[\"keeps an in-flight message visible and never submits it into the approval\",\"routes no typing to the hidden composer until the card is answered\"]},{\"file\":\"src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx\",\"assertions\":[\"keeps an answered approval hidden across a chat view remount and a PTY rebind\"]},{\"file\":\"src/main/runtime/terminal/input/runtime-terminal-writer.test.ts\",\"assertions\":[\"waits for complete body settlement before Enter\",\"does not send the suffix after refusal or unknown settlement\",\"returns unknown after an acknowledged prefix followed by refusal or bookkeeping failure\",\"preserves legacy raw body and Enter writes\"]}]", "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed.", - "Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim." + "Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim.", + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The entire mocked mobile failure-banner suite and its sole send/previous-banner/new-notice ordering alarm are retired. Its filenames are removed from active selectors. Desktop prompt roots and the independent unchanged terminal wire-codec receipt remain at their stated scopes; no mobile send/recovery proof is claimed. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged. Original active selector fields (historical complete raw JSON values, not current coverage): commands: [\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts src/main/runtime/terminal/input/runtime-terminal-writer.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/runtime/terminal/input/terminal-send-stale-leaf-liveness.test.ts --maxWorkers=2\",\n \"ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts mobile/src/session/native-chat/input/mobile-prompt-controller.test.ts --maxWorkers=2\",\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm test tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts --maxWorkers=1\",\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts --maxWorkers=2\",\n \"ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts --maxWorkers=2\"\n ]\ntestFiles: [\n \"src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx\",\n \"src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx\",\n \"src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx\",\n \"src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx\",\n \"src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts\",\n \"src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts\",\n \"src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts\",\n \"src/main/ipc/pty/ipc/write-input-user-input.test.ts\",\n \"src/main/ipc/pty/pty-write-ipc-validation.test.ts\",\n \"src/main/runtime/terminal/input/runtime-terminal-writer.test.ts\",\n \"src/main/runtime/rpc/terminal-send.test.ts\",\n \"src/main/runtime/terminal/input/terminal-send-stale-leaf-liveness.test.ts\",\n\n \"mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts\",\n \"mobile/src/session/native-chat/input/mobile-prompt-controller.test.ts\",\n \"tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx\",\n \"assertions\": [\n \"ignores a raw acknowledgment from a rebound PTY\",\n \"sends only one cancellation, can cancel an answer, and permits retry after unknown\"\n ]\n },\n\n {\n \"file\": \"mobile/src/session/native-chat/input/mobile-prompt-controller.test.ts\",\n \"assertions\": [\n \"retains permission choices on %s\",\n\n \"keeps an acknowledged Deny hidden after the chat screen remounts on a lingering status\",\n \"settles the terminal answer for Q1 after Q2 arrives without hiding Q2\",\n \"keeps structured answer controls after a thrown send\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx\",\n \"assertions\": [\n \"keeps an in-flight message visible and never submits it into the approval\",\n \"routes no typing to the hidden composer until the card is answered\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx\",\n \"assertions\": [\n \"keeps an answered approval hidden across a chat view remount and a PTY rebind\"\n ]\n },\n {\n \"file\": \"src/main/runtime/terminal/input/runtime-terminal-writer.test.ts\",\n \"assertions\": [\n \"waits for complete body settlement before Enter\",\n \"does not send the suffix after refusal or unknown settlement\",\n \"returns unknown after an acknowledged prefix followed by refusal or bookkeeping failure\",\n \"preserves legacy raw body and Enter writes\"\n ]\n }\n ]" ], "promotionCriteria": [ "Record change-reverted red/green evidence and repeatable remote rendered approval/question/dictation journeys.", @@ -1755,7 +1754,8 @@ "Audit1400 historical assertion inventory for deleted/reduced sources; not current validated assertions:\n[\n {\n \"file\": \"src/renderer/src/lib/ai-vault-tab-title-sync-inputs.test.ts\",\n \"assertions\": [\n \"does not enumerate unchanged retained and sleeping maps during live status writes\",\n \"still detects provider changes in %s with other maps reused\",\n \"still checks workspace ownership after unchanged record collections\",\n \"still checks active panes and stored titles after unchanged record collections\"\n ]\n }\n]", "Audit1400 archived original active assertionRefs verbatim after retirement of all passed receipts:\n[\n {\n \"file\": \"src/renderer/src/lib/ai-vault-tab-title-sync-inputs.test.ts\",\n \"assertions\": [\n \"does not enumerate unchanged retained and sleeping maps during live status writes\",\n \"still detects provider changes in %s with other maps reused\",\n \"still checks workspace ownership after unchanged record collections\",\n \"still checks active panes and stored titles after unchanged record collections\"\n ]\n }\n ]", "Audit1400 archived active selectors after retirement of all passed receipts: {\"commands\":[\"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/lib/ai-vault-tab-title-sync-inputs.test.ts src/renderer/src/lib/ai-vault-tab-title-sync.test.ts src/renderer/src/store/slices/agent-status/agent-status-batch.test.ts src/renderer/src/store/slices/agent-status/agent-status-provider-session.test.ts src/renderer/src/store/slices/agent-status/agent-status.test.ts src/renderer/src/store/slices/agent-status/agent-status-manual-sleep-capture.test.ts\"],\"testFiles\":[\"src/renderer/src/lib/ai-vault-tab-title-sync-inputs.test.ts\",\"src/renderer/src/lib/ai-vault-tab-title-sync.test.ts\",\"src/renderer/src/store/slices/agent-status/agent-status-batch.test.ts\",\"src/renderer/src/store/slices/agent-status/agent-status-provider-session.test.ts\",\"src/renderer/src/store/slices/agent-status/agent-status.test.ts\",\"src/renderer/src/store/slices/agent-status/agent-status-manual-sleep-capture.test.ts\"]}", - "Audit2365 further reduces the supporting renderer agent-status suites. It removes the title-batch publication bound and generated-title sample, ordered acceptance/publication and nested/reentrant scheduling ledgers, Jcode manually assembled session-start sample, freshness-tick epoch example, repeated quit-capture identity and batched-clear examples, and sequential/batch retained-cap examples. Those alarms are no longer present; the following historical account must not be read as current coverage for them. No equivalent replacement or fresh execution evidence is claimed." + "Audit2365 further reduces the supporting renderer agent-status suites. It removes the title-batch publication bound and generated-title sample, ordered acceptance/publication and nested/reentrant scheduling ledgers, Jcode manually assembled session-start sample, freshness-tick epoch example, repeated quit-capture identity and batched-clear examples, and sequential/batch retained-cap examples. Those alarms are no longer present; the following historical account must not be read as current coverage for them. No equivalent replacement or fresh execution evidence is claimed.", + "Renderer direct-owner cleanup retires the complete ai-vault-tab-title-sync suite (seven registrations), already referenced only by dormant historical metadata in this gate. Lost alarms: recovered sleeping-title retention, legacy title-kind precedence, host-name versus late-client precedence, provider identity invalidation, per-host batching concurrency/serialization, transcript-path retry, and failed-refresh pacing/name preservation. Real-clock polling or exact internal timer scheduling caused whole-case cuts. Freshness retains its complete queued closed-tab admission case at the public batch callback boundary; its hardcoded delivered-request count is not an internal work budget. No replacement, fresh execution, transport/native UI, provider, measured performance or cross-platform claim. Existing historical entries remain unchanged." ] }, { @@ -2092,7 +2092,7 @@ "id": "terminal-output.prestarted-shell-snapshot-adoption", "title": "Prestarted shell adoption paints covered output once", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-runtime", "layer": "renderer-transport-and-live-electron", "surfaces": [ @@ -2102,46 +2102,19 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "wsl", "ssh", "remote-runtime"], - "coveredPlatforms": ["linux"], + "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Audit3086: the transport filename selector loses IPC suspension/input/reattach cases and the entire spawn-errors suite. Unique classification, ownership, fallback retirement, reply-limit, write-failure and teardown-branch alarms are intentionally retired without replacement. Remaining registrations are unchanged; no fresh execution or real provider result is claimed. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The retained directory-level discovery command continues to discover the reduced family; historical wrapper mentions are not fresh import-closure or execution evidence. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-startup-cwd-fallback-notice.spec.ts: prints a terminal notice when the startup cwd fell back to the workspace root. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-coalesce.test.ts: surfaces working frames when many spinner frames arrive in one chunk. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-spinner.test.ts: surfaces normalized working and idle labels across a spinner cycle; surfaces working even when a single chunk contains multiple spinner frames. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionStartupCwdFallbackNoticeTests } from '../startup/pty-connection-startup-cwd-fallback-notice.spec'; registerPtyConnectionStartupCwdFallbackNoticeTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-agent-trust-hold.test.ts: spawns only after the answer, carrying \"let agents ask\" to main for this launch; reattaches a section terminal without asking or changing trust; spawns with today's default when the prompt is released without an answer. src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-ssh-hook-status-authority.spec.ts: leaves SSH IPC OSC 9999 status ownership in the main runtime. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionSshHookStatusAuthorityTests } from '../host-ownership/pty-connection-ssh-hook-status-authority.spec'; registerPtyConnectionSshHookStatusAuthorityTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-intent.test.ts: declares the intent only when the spawn resumes an agent; reports a deferral to the pane instead of an error toast. src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold.test.ts: owns the record while the start runs, through a nested start, and releases on settle; holds nothing for a start not resuming a record, or once the pane is disposed. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): The existing directory-level pnpm test selector includes eleven changed source files and automatically omits the three whole deletions. Keep this nonempty discovery command unchanged; no dated receipt uses this broad path. Removed agent admission fields, mock transport routing and terminal-id projection alarms are lost. Retained foreground state, actual headless xterm, redraw, abort/rebind reader and bridge claim progression remain scoped to their unchanged callbacks. No current-source execution, independent replacement, native transport or physical provider result is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/components/terminal-pane/pty-connection/main-pane-start-wait.test.ts: Loses joined waiter invocation/failure notification and raw terminal error/paired-host readable sentence alarms; survivors preserve hold detection and card clearing. deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/pty-connection-pi-synchronized-input.test.ts: Loses typed-input forced synchronized-frame presentation alarm; setup implements the parser behavior it claims to exercise. deletes src/renderer/src/components/terminal-pane/pty-connection-unserved-ssh-pane.test.ts: Loses automatic SSH dial deduplication, passphrase gating, stale pane exclusion, and disposal cancellation alarms. deletes src/renderer/src/components/terminal-pane/pty-connection-remote-snapshot-source-grid.test.ts: Loses source grid before frame and destination grid restoration ordering alarm. deletes src/renderer/src/components/terminal-pane/pty-connection-restart-replacement.spec.ts: Loses wrapper-level hidden/visible restart resume, dispose/rebind suppression and finished-turn replay alarms; manual pipeline and mock-implemented binding invalidate the whole callbacks. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1391 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1361 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): macOS daemon-backed Electron journey verifies same PID and terminal identity plus rendered output. Focused renderer contracts pass on Linux, Windows and WSL. Neighboring SSH model and replay contracts pass locally; no new live SSH or paired-runtime journey. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-unanswered-command-finish.spec.ts removed. Unanswered SSH shell finish keeps/drops mocked agent row matrix disappears. src/renderer/src/components/terminal-pane/pty-connection-split-cwd-resolution.test.ts reduced. Happy inherited-cwd wait and transport-option forwarding sample loses its individual alarm. src/renderer/src/components/terminal-pane/pty-connection-command-input-agent-identity.spec.ts removed. Typed Droid versus process/launch identity and SSH/runtime process-evidence matrices disappear. src/renderer/src/components/terminal-pane/pty-connection/reattach-success-settle.test.ts removed. Success/no-ID/expired/superseded attach-settlement bag alarms disappear. src/renderer/src/components/terminal-pane/pty-transport-user-input.test.ts reduced. Every-write kind forwarding and synchronous driving-attempt observer/rejection/ACK call counts disappear. src/renderer/src/components/terminal-pane/pty-connection-codex-restart-input-lookup.spec.ts removed. No global tab enumeration on ordinary/stale input and known restart notice input-block mock-call alarms. src/renderer/src/components/terminal-pane/pty-connection-layout-owner-wake.test.ts removed. Hidden-to-visible single-pane start request, attach-only argument and negative local wake-record alarms are intentionally dropped; no real server wake/ack occurs. src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. src/renderer/src/components/terminal-pane/pty-connection-command-finished-cleanup.spec.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. src/renderer/src/components/terminal-pane/pty-connection-terminal-input-gating.spec.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Audit1361: src/renderer/src/components/terminal-pane/pty-connection/foreground-output-scan.test.ts reduced. Internal searched-character budget and ordinary/malformed no-op controls. No equivalent replacement coverage is claimed. Audit1365: focused Linux unit selection passed on source head 8880357cb420c45f1b808ae545a5bc609324624d. This new result has its own exact command; historical results keep their prior scope. Intentional test losses remain recorded in knownGaps. No physical-provider, native input, rendered E2E, p95, soak or replacement-coverage claim. Audit1369: src/renderer/src/components/terminal-pane/pty-connection/disposed-spawn-retention.test.ts removed. Rootless/removed/moved tabs, missing leaves, queued deletion and host-qualified/legacy deletion eligibility fixtures. No equivalent replacement coverage is claimed. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/renderer/src/components/terminal-pane/pty-connection/terminal-input-echo-delay.test.ts reduced. Removes two fabricated-binding pipeline registrations; retains timestamp-policy outcomes without wall-clock speed assertions. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. src/renderer/src/components/terminal-pane/pty-connection/main-pane-resume-banner.test.ts reduced. Loses subscription-budget and attach-start generation predicate alarms; actual restored-banner renderer is not exercised. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result.", + "coverageNotes": "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3086: the transport filename selector loses IPC suspension/input/reattach cases and the entire spawn-errors suite. Unique classification, ownership, fallback retirement, reply-limit, write-failure and teardown-branch alarms are intentionally retired without replacement. Remaining registrations are unchanged; no fresh execution or real provider result is claimed. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The retained directory-level discovery command continues to discover the reduced family; historical wrapper mentions are not fresh import-closure or execution evidence. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-startup-cwd-fallback-notice.spec.ts: prints a terminal notice when the startup cwd fell back to the workspace root. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-coalesce.test.ts: surfaces working frames when many spinner frames arrive in one chunk. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-spinner.test.ts: surfaces normalized working and idle labels across a spinner cycle; surfaces working even when a single chunk contains multiple spinner frames. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionStartupCwdFallbackNoticeTests } from '../startup/pty-connection-startup-cwd-fallback-notice.spec'; registerPtyConnectionStartupCwdFallbackNoticeTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-agent-trust-hold.test.ts: spawns only after the answer, carrying \"let agents ask\" to main for this launch; reattaches a section terminal without asking or changing trust; spawns with today's default when the prompt is released without an answer. src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-ssh-hook-status-authority.spec.ts: leaves SSH IPC OSC 9999 status ownership in the main runtime. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionSshHookStatusAuthorityTests } from '../host-ownership/pty-connection-ssh-hook-status-authority.spec'; registerPtyConnectionSshHookStatusAuthorityTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-intent.test.ts: declares the intent only when the spawn resumes an agent; reports a deferral to the pane instead of an error toast. src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold.test.ts: owns the record while the start runs, through a nested start, and releases on settle; holds nothing for a start not resuming a record, or once the pane is disposed. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): The existing directory-level pnpm test selector includes eleven changed source files and automatically omits the three whole deletions. Keep this nonempty discovery command unchanged; no dated receipt uses this broad path. Removed agent admission fields, mock transport routing and terminal-id projection alarms are lost. Retained foreground state, actual headless xterm, redraw, abort/rebind reader and bridge claim progression remain scoped to their unchanged callbacks. No current-source execution, independent replacement, native transport or physical provider result is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/components/terminal-pane/pty-connection/main-pane-start-wait.test.ts: Loses joined waiter invocation/failure notification and raw terminal error/paired-host readable sentence alarms; survivors preserve hold detection and card clearing. deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/pty-connection-pi-synchronized-input.test.ts: Loses typed-input forced synchronized-frame presentation alarm; setup implements the parser behavior it claims to exercise. deletes src/renderer/src/components/terminal-pane/pty-connection-unserved-ssh-pane.test.ts: Loses automatic SSH dial deduplication, passphrase gating, stale pane exclusion, and disposal cancellation alarms. deletes src/renderer/src/components/terminal-pane/pty-connection-remote-snapshot-source-grid.test.ts: Loses source grid before frame and destination grid restoration ordering alarm. deletes src/renderer/src/components/terminal-pane/pty-connection-restart-replacement.spec.ts: Loses wrapper-level hidden/visible restart resume, dispose/rebind suppression and finished-turn replay alarms; manual pipeline and mock-implemented binding invalidate the whole callbacks. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1391 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1361 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): macOS daemon-backed Electron journey verifies same PID and terminal identity plus rendered output. Focused renderer contracts pass on Linux, Windows and WSL. Neighboring SSH model and replay contracts pass locally; no new live SSH or paired-runtime journey. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-unanswered-command-finish.spec.ts removed. Unanswered SSH shell finish keeps/drops mocked agent row matrix disappears. src/renderer/src/components/terminal-pane/pty-connection-split-cwd-resolution.test.ts reduced. Happy inherited-cwd wait and transport-option forwarding sample loses its individual alarm. src/renderer/src/components/terminal-pane/pty-connection-command-input-agent-identity.spec.ts removed. Typed Droid versus process/launch identity and SSH/runtime process-evidence matrices disappear. src/renderer/src/components/terminal-pane/pty-connection/reattach-success-settle.test.ts removed. Success/no-ID/expired/superseded attach-settlement bag alarms disappear. src/renderer/src/components/terminal-pane/pty-transport-user-input.test.ts reduced. Every-write kind forwarding and synchronous driving-attempt observer/rejection/ACK call counts disappear. src/renderer/src/components/terminal-pane/pty-connection-codex-restart-input-lookup.spec.ts removed. No global tab enumeration on ordinary/stale input and known restart notice input-block mock-call alarms. src/renderer/src/components/terminal-pane/pty-connection-layout-owner-wake.test.ts removed. Hidden-to-visible single-pane start request, attach-only argument and negative local wake-record alarms are intentionally dropped; no real server wake/ack occurs. src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. src/renderer/src/components/terminal-pane/pty-connection-command-finished-cleanup.spec.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. src/renderer/src/components/terminal-pane/pty-connection-terminal-input-gating.spec.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Audit1361: src/renderer/src/components/terminal-pane/pty-connection/foreground-output-scan.test.ts reduced. Internal searched-character budget and ordinary/malformed no-op controls. No equivalent replacement coverage is claimed. Audit1365: focused Linux unit selection passed on source head 8880357cb420c45f1b808ae545a5bc609324624d. This new result has its own exact command; historical results keep their prior scope. Intentional test losses remain recorded in knownGaps. No physical-provider, native input, rendered E2E, p95, soak or replacement-coverage claim. Audit1369: src/renderer/src/components/terminal-pane/pty-connection/disposed-spawn-retention.test.ts removed. Rootless/removed/moved tabs, missing leaves, queued deletion and host-qualified/legacy deletion eligibility fixtures. No equivalent replacement coverage is claimed. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/renderer/src/components/terminal-pane/pty-connection/terminal-input-echo-delay.test.ts reduced. Removes two fabricated-binding pipeline registrations; retains timestamp-policy outcomes without wall-clock speed assertions. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. src/renderer/src/components/terminal-pane/pty-connection/main-pane-resume-banner.test.ts reduced. Loses subscription-budget and attach-start generation predicate alarms; actual restored-banner renderer is not exercised. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result.", "motivatingLinks": [ "https://github.com/user-attachments/assets/e8c6d1dc-6150-4c3d-b55a-3d12efefdd04", "https://github.com/user-attachments/assets/b0328f88-34ac-4d51-8119-9efe17072435" ], "invariant": "Adopting a prestarted terminal preserves its existing process and paints snapshot-covered startup output once while retaining subsequent live output. Missing sequence proof or blank snapshots must not authorize dropping output.", - "oracle": "Audit3086: the transport filename selector loses IPC suspension/input/reattach cases and the entire spawn-errors suite. Unique classification, ownership, fallback retirement, reply-limit, write-failure and teardown-branch alarms are intentionally retired without replacement. Remaining registrations are unchanged; no fresh execution or real provider result is claimed. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The retained directory-level discovery command continues to discover the reduced family; historical wrapper mentions are not fresh import-closure or execution evidence. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-startup-cwd-fallback-notice.spec.ts: prints a terminal notice when the startup cwd fell back to the workspace root. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-coalesce.test.ts: surfaces working frames when many spinner frames arrive in one chunk. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-spinner.test.ts: surfaces normalized working and idle labels across a spinner cycle; surfaces working even when a single chunk contains multiple spinner frames. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionStartupCwdFallbackNoticeTests } from '../startup/pty-connection-startup-cwd-fallback-notice.spec'; registerPtyConnectionStartupCwdFallbackNoticeTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-agent-trust-hold.test.ts: spawns only after the answer, carrying \"let agents ask\" to main for this launch; reattaches a section terminal without asking or changing trust; spawns with today's default when the prompt is released without an answer. src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-ssh-hook-status-authority.spec.ts: leaves SSH IPC OSC 9999 status ownership in the main runtime. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionSshHookStatusAuthorityTests } from '../host-ownership/pty-connection-ssh-hook-status-authority.spec'; registerPtyConnectionSshHookStatusAuthorityTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-intent.test.ts: declares the intent only when the spawn resumes an agent; reports a deferral to the pane instead of an error toast. src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold.test.ts: owns the record while the start runs, through a nested start, and releases on settle; holds nothing for a start not resuming a record, or once the pane is disposed. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): The existing directory-level pnpm test selector includes eleven changed source files and automatically omits the three whole deletions. Keep this nonempty discovery command unchanged; no dated receipt uses this broad path. Removed agent admission fields, mock transport routing and terminal-id projection alarms are lost. Retained foreground state, actual headless xterm, redraw, abort/rebind reader and bridge claim progression remain scoped to their unchanged callbacks. No current-source execution, independent replacement, native transport or physical provider result is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Pass snapshot sequence and proven zero keyboard flags through real IPC transport projection. Deliver snapshot-covered and newer output before reattach resolves; drain replay parse callbacks and require one startup marker and the newer output. Repeat with no sequence and blank snapshot to retain unproven bytes. In Electron select a prestarted workspace, type a generated marker and compare PID and stable terminal identities before and after.", - "commands": [ - "pnpm test src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts", - "pnpm test src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts", - "pnpm test src/renderer/src/components/terminal-pane/pty-connection src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport", - "pnpm test src/shared/terminal/protocol/escape/terminal-synchronized-output-socket-splits.test.ts" - ], - "testFiles": [ - "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts" - ], - "assertionRefs": [ - { - "file": "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts", - "assertions": [ - "startup output covered by the snapshot is painted once", - "new output remains visible", - "legacy unsequenced and blank snapshots retain bytes" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-11-04", - "runner": "local", - "platform": "linux", - "command": "pnpm --config.verifyDepsBeforeRun=false test src/renderer/src/components/terminal-pane/pty-connection/foreground-output-scan.test.ts --maxWorkers=2", - "result": "passed", - "durationSeconds": 2.31, - "summary": "Test Files 1 passed (1); Tests 3 passed (3). Source head 8880357cb420c45f1b808ae545a5bc609324624d. Focused retained foreground-output scan only, not all directory-selected gate cases or live provider behavior. Node24.22.0 with ORCA_BACKGROUND_LAUNCH=1 and an isolated Xvfb display.", - "currentCommand": "pnpm test src/shared/terminal/protocol/escape/terminal-synchronized-output-socket-splits.test.ts" - } - ], + "oracle": "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3086: the transport filename selector loses IPC suspension/input/reattach cases and the entire spawn-errors suite. Unique classification, ownership, fallback retirement, reply-limit, write-failure and teardown-branch alarms are intentionally retired without replacement. Remaining registrations are unchanged; no fresh execution or real provider result is claimed. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The retained directory-level discovery command continues to discover the reduced family; historical wrapper mentions are not fresh import-closure or execution evidence. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-startup-cwd-fallback-notice.spec.ts: prints a terminal notice when the startup cwd fell back to the workspace root. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-coalesce.test.ts: surfaces working frames when many spinner frames arrive in one chunk. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-spinner.test.ts: surfaces normalized working and idle labels across a spinner cycle; surfaces working even when a single chunk contains multiple spinner frames. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionStartupCwdFallbackNoticeTests } from '../startup/pty-connection-startup-cwd-fallback-notice.spec'; registerPtyConnectionStartupCwdFallbackNoticeTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-agent-trust-hold.test.ts: spawns only after the answer, carrying \"let agents ask\" to main for this launch; reattaches a section terminal without asking or changing trust; spawns with today's default when the prompt is released without an answer. src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-ssh-hook-status-authority.spec.ts: leaves SSH IPC OSC 9999 status ownership in the main runtime. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionSshHookStatusAuthorityTests } from '../host-ownership/pty-connection-ssh-hook-status-authority.spec'; registerPtyConnectionSshHookStatusAuthorityTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-intent.test.ts: declares the intent only when the spawn resumes an agent; reports a deferral to the pane instead of an error toast. src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold.test.ts: owns the record while the start runs, through a nested start, and releases on settle; holds nothing for a start not resuming a record, or once the pane is disposed. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): The existing directory-level pnpm test selector includes eleven changed source files and automatically omits the three whole deletions. Keep this nonempty discovery command unchanged; no dated receipt uses this broad path. Removed agent admission fields, mock transport routing and terminal-id projection alarms are lost. Retained foreground state, actual headless xterm, redraw, abort/rebind reader and bridge claim progression remain scoped to their unchanged callbacks. No current-source execution, independent replacement, native transport or physical provider result is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Pass snapshot sequence and proven zero keyboard flags through real IPC transport projection. Deliver snapshot-covered and newer output before reattach resolves; drain replay parse callbacks and require one startup marker and the newer output. Repeat with no sequence and blank snapshot to retain unproven bytes. In Electron select a prestarted workspace, type a generated marker and compare PID and stable terminal identities before and after.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 15, "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." @@ -2193,7 +2166,9 @@ "Audit1939 (sources1934/1935): The existing directory-level pnpm test selector includes eleven changed source files and automatically omits the three whole deletions. Keep this nonempty discovery command unchanged; no dated receipt uses this broad path. Removed agent admission fields, mock transport routing and terminal-id projection alarms are lost. Retained foreground state, actual headless xterm, redraw, abort/rebind reader and bridge claim progression remain scoped to their unchanged callbacks. No current-source execution, independent replacement, native transport or physical provider result is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Exact retired authored alarms: 'bounds a startup title storm to one extra read ladder and never adopts the title as identity'; 'leaves untrackable providers free of client process scans'; 'keeps a legacy remote process hint unverifiable after a startup title'; 'releases a retained capability when disposed mid-read'; 'releases a retained capability when an exit schedules no successor read'; 'releases a retained capability when an untrackable $exit ends the read'; 'does not release when the cancelled read has a successor'; 'settles the visible confirmation when the pty id is gone before the read runs'; 'reports a read in flight when a command-finished read owns the pane'; 'reads the foreground once after a command starts and publishes the recognized agent'; 'does not replace known foreground identity with typed command inference'; 'revokes stale routing immediately while a known pane confirms a new command'; 'reads the foreground for a visible PTY so restored running Codex panes regain identity'; 'does not retry or publish visible PTY reads for an idle shell foreground'; 'retries visible PTY reads only while a foreground wrapper may resolve to an agent'; 'stops after the ladder and publishes no identity for a persistent unknown process'; 'does not treat a nested shell seen mid-command as prompt proof'; 'recognizes an agent started from a nested shell on a ladder re-read'; 'marks shell foreground on command finished without any foreground read'; 'trusts a rapid ordinary command finish without forcing a fresh scan'; 'still marks shell without a read for a duplicate D pair on an idle pane'; 'marks shell on a rapid command start->finish when the foreground is a shell'; 'marks shell foreground when the confirming read shows the agent is gone'; 'confirms a command finished for a launch-known agent pane before any read'; 'accepts a fresh shell result for a launch-known Droid pane'; 'marks a confirmed shell without repeating a post-boundary scan'; 'never reads or publishes for remote or ssh panes'; 'does not let forged OSC 133/777 output assert remote identity'; 'keeps command-only pane inference bounded for large pasted scripts'; 'skips jcode colors for command-only startup %s'; 'keeps explicit pane ownership ahead of a delayed command hint'; 'does not infer a TUI from %s'; 'survives a launch config registered before its identity lands'; 'prefers the tab launch agent over every later signal'; 'falls back through startup, then initial status, then the registered config'; 'ignores a registered agent name that is not a known TUI agent'; 'skips the OSC color answer for jcode and no one else'; 'drops a Done that landed before the command-finished fact'; 'keeps a program Done reported before the command-finished fact'; 'dismisses the kept result when the next command starts'; 'keeps a facet-less OSC Done from a non-agent program'; 'still drops a real agent Done'; 'still drops an interrupted program Done'; 'retires a hook-identified row the foreground tracker never read'; 'leaves a pane with an armed command-finished drop to its own confirming read'; 'leaves a remote pane to its execution host'; 'keeps the row when the host can verify the owner process itself'; 'keeps a row that belongs to a different agent'; 'does not watch the store for an owner it can never name'; 'control: a fresh host image repaints the pane without resizing the program'; 'asks the program to repaint when the image is %s'; 'asks the program to repaint when the host never answers the snapshot request'; 'repaints a full-screen TUI on the alternate screen the same way'; 'leaves the size alone while a phone or another desktop holds it'; 'grows a pane at the host minimum height instead of asking for the same clamped size'; 'does not nudge while the stream is still reconnecting'; 'mounts and remounts the tab owner while an unrelated workspace is active (%s)'; 'continues a recorded live folder owner despite ambiguous inventory (%s)'; 'resolves an encoded split surface using its parent tab and active leaf'; 'does not capture a remote revision for a local terminal'; 'omits incarnation and length for older runtime responses'; 'refuses %s owner before RPC'; 'refuses a resolved terminal belonging to another native PTY'; 'refuses a foreign remote terminal handle despite a matching native PTY ID'; 'refuses a remote handle owned by another environment'; 'refuses a remote terminal with no live native PTY'; 'does not fall back locally when remote lacks RPC'; 'rejects malformed or oversized encoded response %#'; 'maps a unified terminal tab id to its legacy owner id'; 'keeps non-terminal and unknown ids unchanged'; 'keeps an exact terminal owner ahead of a stale unified alias'; 'stays inert on a host that was not kept for the bridge'; 'stays inert for a pane main does not list, so it still dials the host'.", "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-intent.test.ts: declares the intent only when the spawn resumes an agent; reports a deferral to the pane instead of an error toast. src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold.test.ts: owns the record while the start runs, through a nested start, and releases on settle; holds nothing for a start not resuming a record, or once the pane is disposed. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed.", "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-agent-trust-hold.test.ts: spawns only after the answer, carrying \"let agents ask\" to main for this launch; reattaches a section terminal without asking or changing trust; spawns with today's default when the prompt is released without an answer. src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-ssh-hook-status-authority.spec.ts: leaves SSH IPC OSC 9999 status ownership in the main runtime. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionSshHookStatusAuthorityTests } from '../host-ownership/pty-connection-ssh-hook-status-authority.spec'; registerPtyConnectionSshHookStatusAuthorityTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed.", - "Audit3086: the transport filename selector loses IPC suspension/input/reattach cases and the entire spawn-errors suite. Unique classification, ownership, fallback retirement, reply-limit, write-failure and teardown-branch alarms are intentionally retired without replacement. Remaining registrations are unchanged; no fresh execution or real provider result is claimed." + "Audit3086: the transport filename selector loses IPC suspension/input/reattach cases and the entire spawn-errors suite. Unique classification, ownership, fallback retirement, reply-limit, write-failure and teardown-branch alarms are intentionally retired without replacement. Remaining registrations are unchanged; no fresh execution or real provider result is claimed.", + "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"pnpm test src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"pnpm test src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts\",\n \"pnpm test src/renderer/src/components/terminal-pane/pty-connection src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport\",\n \"pnpm test src/shared/terminal/protocol/escape/terminal-synchronized-output-socket-splits.test.ts\"\n ]\ntestFiles: [\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"assertions\": [\n \"startup output covered by the snapshot is painted once\",\n \"new output remains visible\",\n \"legacy unsequenced and blank snapshots retain bytes\"\n ]\n }\n ]", + "Audit3392 validation correction: no remaining directly selected suite protects prestarted snapshot adoption; protection is none. Remaining broad scan commands do not establish this invariant. Retired gate status, covered scope, commands and complete dated receipt follow as historical raw values:\nprotection: \"partial\"\ncommands: [\n \"pnpm test src/renderer/src/components/terminal-pane/pty-connection src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport\",\n \"pnpm test src/shared/terminal/protocol/escape/terminal-synchronized-output-socket-splits.test.ts\"\n ]\ncoveredPlatforms: [\"linux\"]\ncoveredProviders: []\nevidenceRuns: [\n {\n \"date\": \"2026-11-04\",\n \"runner\": \"local\",\n \"platform\": \"linux\",\n \"command\": \"pnpm --config.verifyDepsBeforeRun=false test src/renderer/src/components/terminal-pane/pty-connection/foreground-output-scan.test.ts --maxWorkers=2\",\n \"result\": \"passed\",\n \"durationSeconds\": 2.31,\n \"summary\": \"Test Files 1 passed (1); Tests 3 passed (3). Source head 8880357cb420c45f1b808ae545a5bc609324624d. Focused retained foreground-output scan only, not all directory-selected gate cases or live provider behavior. Node24.22.0 with ORCA_BACKGROUND_LAUNCH=1 and an isolated Xvfb display.\",\n \"currentCommand\": \"pnpm test src/shared/terminal/protocol/escape/terminal-synchronized-output-socket-splits.test.ts\"\n }\n ]" ], "demotionRule": "Keep experimental or demote if adoption duplicates covered output, drops newer or unproven output, changes terminal ownership, or flakes without explanation." }, @@ -2501,14 +2476,14 @@ "providers": ["orca-server", "direct-ssh"], "coveredPlatforms": ["macos"], "coveredProviders": ["orca-server", "direct-ssh"], - "coverageNotes": "Audit 3292 retires the direct-SSH failed-project retention, managed-server failed-project retention and ordinary confirmed managed-VM destruction/no-repo.rm examples from repos-ephemeral-vm-cleanup-retention.test.ts. Host-scoped same-workspace isolation and stale renderer catalog reconciliation remain byte-identical. These three supplied-result alarms are intentionally lost without equivalent replacement. Existing selectors/assertionRefs, unrelated cross-version rollback receipt and archived complete 122-case cleanup receipt remain exact; no fresh broad runtime, provider, platform or mixed-version result is claimed. Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n } Historical prior account (preserved verbatim): Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1441 removes the complete renderer VM-runtime settings suite: display filter/status/SSH-retry flags, cleanup and stop RPC-to-toast/dialog plumbing, manual-copy plumbing and polling toast silence. The suite did not execute provider teardown or process cancellation. Its rendered stop/retry and hidden-SSH display alarms are intentionally retired; no equivalent replacement or fresh reduced-selector runtime result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/lib/ephemeral-vm-workspace-target.test.ts: Loses wrapper-level host rebinding, incompatible provisioned-root refusal and best-effort cleanup-call alarms; all are mock-only orchestration projections. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A pinned exact-source harness runs the pre-#14352 reader and lifecycle service against baseline, affected-main, candidate, and fix-reverted stores. Platform-neutral tests cover store compatibility, user-cancellable cleanup, branch/ref adoption; audit885 removes the direct resume ownership predicate alarms. The direct-SSH provisioned-root Electron journey remains the live transport and destroy proof; this desktop sidecar is not mobile-facing and changes no RPC or remote wire payload. The test-value audit removed the renderer provisioned-root create-options suite. Its two incomplete-identity rejection assertions are lost: one omitted workspaceRunContext and other identity fields, and one supplied the context but omitted ephemeralVmExpectedRefHead. The suite did not test successful option mapping. Retained source-ref and lifecycle suites do not establish equivalent renderer guard coverage. Audit1342: src/renderer/src/lib/ephemeral-vm-runtime-cleanup.test.ts removed. Runtime/SSH ownership, encoded target, retry/failure/listing-error cleanup projection samples disappear. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. The runtime-service source intentionally loses14of16cases: ordinary lifecycle/retry/configuration/cleanup projections, unreadable-companion refusal and successful post-create compensation examples are retired. Keep only non-JSON credential refusal before provider launch and failed compensation after post-create persistence failure, with old-readable recovery identity across two local injected faults. This does not prove a subsequent retry or actual remote provider cleanup. Existing unrelated rollback reproduction receipt remains exact; no fresh execution, protection change or equivalent replacement claimed. Audit 3292 retires the direct-SSH failed-project retention, managed-server failed-project retention and ordinary confirmed managed-VM destruction/no-repo.rm examples from repos-ephemeral-vm-cleanup-retention.test.ts. Host-scoped same-workspace isolation and stale renderer catalog reconciliation remain byte-identical. These three supplied-result alarms are intentionally lost without equivalent replacement. Existing selectors/assertionRefs, unrelated cross-version rollback receipt and archived complete 122-case cleanup receipt remain exact; no fresh broad runtime, provider, platform or mixed-version result is claimed. Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n } Historical prior account (preserved verbatim): Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1441 removes the complete renderer VM-runtime settings suite: display filter/status/SSH-retry flags, cleanup and stop RPC-to-toast/dialog plumbing, manual-copy plumbing and polling toast silence. The suite did not execute provider teardown or process cancellation. Its rendered stop/retry and hidden-SSH display alarms are intentionally retired; no equivalent replacement or fresh reduced-selector runtime result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/lib/ephemeral-vm-workspace-target.test.ts: Loses wrapper-level host rebinding, incompatible provisioned-root refusal and best-effort cleanup-call alarms; all are mock-only orchestration projections. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A pinned exact-source harness runs the pre-#14352 reader and lifecycle service against baseline, affected-main, candidate, and fix-reverted stores. Platform-neutral tests cover store compatibility, user-cancellable cleanup, branch/ref adoption; audit885 removes the direct resume ownership predicate alarms. The direct-SSH provisioned-root Electron journey remains the live transport and destroy proof; this desktop sidecar is not mobile-facing and changes no RPC or remote wire payload. The test-value audit removed the renderer provisioned-root create-options suite. Its two incomplete-identity rejection assertions are lost: one omitted workspaceRunContext and other identity fields, and one supplied the context but omitted ephemeralVmExpectedRefHead. The suite did not test successful option mapping. Retained source-ref and lifecycle suites do not establish equivalent renderer guard coverage. Audit1342: src/renderer/src/lib/ephemeral-vm-runtime-cleanup.test.ts removed. Runtime/SSH ownership, encoded target, retry/failure/listing-error cleanup projection samples disappear. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4274", "https://github.com/stablyai/orca/pull/14352", "https://github.com/stablyai/orca/issues/13044" ], "invariant": "A sidecar written by the new build cannot make the previous production build lose otherwise compatible VM runtimes. Downgrade lifecycle writes remain authoritative after re-upgrade, provisioned-root metadata remains recoverable, and corrupt or future feature metadata is preserved without poisoning the rollback-readable v1 store. Destroy attempts have no automatic wall-clock cutoff; a user stop terminates the process tree, retains cleanup ownership, and permits a fresh retry. Provider failure retains the SSH/project context needed for safe cleanup. Unrecoverable recipe context releases only the hidden SSH registration while preserving lifecycle/provider metadata. Provisioned-root create receives the source ref's pinned commit, adoption verifies the requested branch/ref, and resume preserves the connection mode plus stable SSH ownership identity while allowing endpoint rotation.", - "oracle": "Audit 3292 retires the direct-SSH failed-project retention, managed-server failed-project retention and ordinary confirmed managed-VM destruction/no-repo.rm examples from repos-ephemeral-vm-cleanup-retention.test.ts. Host-scoped same-workspace isolation and stale renderer catalog reconciliation remain byte-identical. These three supplied-result alarms are intentionally lost without equivalent replacement. Existing selectors/assertionRefs, unrelated cross-version rollback receipt and archived complete 122-case cleanup receipt remain exact; no fresh broad runtime, provider, platform or mixed-version result is claimed. Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n } Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Write one ordinary schema-v1 runtime and one provisioned-root runtime. Require the exact pre-#14352 reader to return both, run the old destroy lifecycle against the projected provisioned record, then require the candidate to retain the cleaned state while restoring schema-v2 and checkout-mode metadata. The same old reader must reject affected-main and fix-reverted bytes. Malformed, oversized, unknown-record, and future-version feature sidecars must leave rollback-compatible records accessible and must not be overwritten during compatible lifecycle mutations. Require destroy to have no implicit deadline, stop a hung destroy through the public desktop action, require cleanup_failed plus a fresh successful retry, prove provider or project-host rollback failure retains every ownership record required to retry, and prove missing recipe context cannot leave an unremovable hidden SSH registration. Supply the source ref's captured commit to create, reject a provisioned checkout on the wrong branch/ref, and reject a resume that changes connection mode or SSH ownership.", + "oracle": "Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. The runtime-service source intentionally loses14of16cases: ordinary lifecycle/retry/configuration/cleanup projections, unreadable-companion refusal and successful post-create compensation examples are retired. Keep only non-JSON credential refusal before provider launch and failed compensation after post-create persistence failure, with old-readable recovery identity across two local injected faults. This does not prove a subsequent retry or actual remote provider cleanup. Existing unrelated rollback reproduction receipt remains exact; no fresh execution, protection change or equivalent replacement claimed. Audit 3292 retires the direct-SSH failed-project retention, managed-server failed-project retention and ordinary confirmed managed-VM destruction/no-repo.rm examples from repos-ephemeral-vm-cleanup-retention.test.ts. Host-scoped same-workspace isolation and stale renderer catalog reconciliation remain byte-identical. These three supplied-result alarms are intentionally lost without equivalent replacement. Existing selectors/assertionRefs, unrelated cross-version rollback receipt and archived complete 122-case cleanup receipt remain exact; no fresh broad runtime, provider, platform or mixed-version result is claimed. Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n } Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Write one ordinary schema-v1 runtime and one provisioned-root runtime. Require the exact pre-#14352 reader to return both, run the old destroy lifecycle against the projected provisioned record, then require the candidate to retain the cleaned state while restoring schema-v2 and checkout-mode metadata. The same old reader must reject affected-main and fix-reverted bytes. Malformed, oversized, unknown-record, and future-version feature sidecars must leave rollback-compatible records accessible and must not be overwritten during compatible lifecycle mutations. Require destroy to have no implicit deadline, stop a hung destroy through the public desktop action, require cleanup_failed plus a fresh successful retry, prove provider or project-host rollback failure retains every ownership record required to retry, and prove missing recipe context cannot leave an unremovable hidden SSH registration. Supply the source ref's captured commit to create, reject a provisioned checkout on the wrong branch/ref, and reject a resume that changes connection mode or SSH ownership.", "commands": [ "node config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/shared/ephemeral-vm-runtime-store.test.ts src/shared/ephemeral-vm-runtime-store-rollback.test.ts src/shared/ephemeral-vm-recipe-process.test.ts src/main/ephemeral-vm/runtime-service.test.ts src/main/ephemeral-vm/recipe-runner.test.ts src/main/ephemeral-vm/runtime-ssh-cleanup.test.ts src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts src/main/ipc/ephemeral-vm-provision-cancel.test.ts src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts src/main/ipc/ephemeral-vm.test.ts src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts", @@ -2549,8 +2524,6 @@ { "file": "src/main/ephemeral-vm/runtime-service.test.ts", "assertions": [ - "an unreadable companion rejects checkout-mode recipes before their create command runs", - "post-create persistence failure destroys the provider resource when possible", "failed destroy persists a durable rollback-readable cleanup recovery record" ] }, @@ -2636,7 +2609,9 @@ "Audit1853 accepts removal of the runtime-ssh-cleanup.test.ts alarm for repairing cleanup_failed/provider-succeeded records that already lack a target ID. No equivalent replacement coverage is claimed. Keep the surviving cleanup selector and unchanged cross-version rollback receipt; the historical 2026-08-14 122-case cleanup receipt remains archived verbatim in knownGaps.", "Audit1863 removes the standalone default-source-ref provisioning example. Its direct default-ref pinning alarm is intentionally lost; selected-ref pinning and invalid-ref cases remain without an equivalent replacement claim. Focused survivor execution does not validate the broad rollback selector or physical cross-version provisioning. Existing receipts retain their original commands and counts.", "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n }", - "Audit 3292 retires the direct-SSH failed-project retention, managed-server failed-project retention and ordinary confirmed managed-VM destruction/no-repo.rm examples from repos-ephemeral-vm-cleanup-retention.test.ts. Host-scoped same-workspace isolation and stale renderer catalog reconciliation remain byte-identical. These three supplied-result alarms are intentionally lost without equivalent replacement. Existing selectors/assertionRefs, unrelated cross-version rollback receipt and archived complete 122-case cleanup receipt remain exact; no fresh broad runtime, provider, platform or mixed-version result is claimed." + "Audit 3292 retires the direct-SSH failed-project retention, managed-server failed-project retention and ordinary confirmed managed-VM destruction/no-repo.rm examples from repos-ephemeral-vm-cleanup-retention.test.ts. Host-scoped same-workspace isolation and stale renderer catalog reconciliation remain byte-identical. These three supplied-result alarms are intentionally lost without equivalent replacement. Existing selectors/assertionRefs, unrelated cross-version rollback receipt and archived complete 122-case cleanup receipt remain exact; no fresh broad runtime, provider, platform or mixed-version result is claimed.", + "Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. The runtime-service source intentionally loses14of16cases: ordinary lifecycle/retry/configuration/cleanup projections, unreadable-companion refusal and successful post-create compensation examples are retired. Keep only non-JSON credential refusal before provider launch and failed compensation after post-create persistence failure, with old-readable recovery identity across two local injected faults. This does not prove a subsequent retry or actual remote provider cleanup. Existing unrelated rollback reproduction receipt remains exact; no fresh execution, protection change or equivalent replacement claimed. All previous note strings, dated receipts, archived raw receipts and prior gap entries retain their original scopes.", + "Audit3413 retires two runtime-service assertion claims after source reduction; the failed-destroy durable rollback-readable cleanup recovery claim remains current. Complete prior assertionRef preserved as historical data only: {\n \"file\": \"src/main/ephemeral-vm/runtime-service.test.ts\",\n \"assertions\": [\n \"an unreadable companion rejects checkout-mode recipes before their create command runs\",\n \"post-create persistence failure destroys the provider resource when possible\",\n \"failed destroy persists a durable rollback-readable cleanup recovery record\"\n ]\n }" ], "demotionRule": "Demote if a new write fails the pinned rollback reader, a downgrade lifecycle mutation is lost after re-upgrade, malformed/future metadata overwrites recoverable bytes, ordinary v1 bytes change, user stop cannot settle a destroy process tree, cleanup loses retry ownership, an unrecoverable context leaves a permanent hidden SSH registration, or the focused gate flakes without an identified harness defect." }, @@ -3461,16 +3436,16 @@ "providers": ["local", "ssh"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Module layout SSH policy: Retire reset/private-arithmetic generation rollover registrations. The two retained local-versus-SSH mutation refusals do not establish process-scope rollover or sibling-token invalidation; remove this unrelated gate selector and its rollover assertion claim. Unchanged unrelated execution receipts retain only their original scope. No replacement, fresh rollover execution or cross-platform proof is claimed. Historical prior account (preserved verbatim): Audit2003: Remove the standalone one-client shared-runtime/headless-publication example. The retained two-client callback (real WebSocket/runtime coordination with supplied Git listings and watcher notifications) and invalidated scan/reconnect races keep their exact owning scope, without replacement-equivalence or rendered-headless proof. Retire the entire dated38-case receipt through its effective currentCommand. Preserve the unrelated SSH bridge receipt and paired Electron receipt within their original commands. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Local deterministic evidence covers git-common classification, desktop watcher debounce counts, non-overlapping poller semantics, macOS native-watch fallback, paired-runtime publication to two independent clients with reconnect and stale-cache checks, and process generation-scope rollover across sibling targets. A headed macOS Electron host and separate paired Electron client both rendered a worktree created through the real Git binary and watcher entry path without reconnect. Linux/Windows desktop clients, multi-target live fanout, and WSL runs remain gaps. Audit1309: src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts: Keep real filesystem HEAD/loose/packed/relative metadata reads and traversal refusal. Remove invalid-oid/nonstandard-layout characterization. Lose malformed object-id and bare-dir omission alarms; no Git-produced layout claim. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1381 removes the two mock-forwarding registrations in src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts. Sibling attribution suppression and missing/unknown attribution refresh callback alarms are intentionally lost; no equivalent replacement or real hook lifecycle/status-update coverage is claimed. Remaining exact receipts, platform/provider scope, and budgets remain limited to their unchanged selectors; no new execution result is claimed. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Module layout SSH policy: Retire reset/private-arithmetic generation rollover registrations. The two retained local-versus-SSH mutation refusals do not establish process-scope rollover or sibling-token invalidation; remove this unrelated gate selector and its rollover assertion claim. Unchanged unrelated execution receipts retain only their original scope. No replacement, fresh rollover execution or cross-platform proof is claimed. Historical prior account (preserved verbatim): Audit2003: Remove the standalone one-client shared-runtime/headless-publication example. The retained two-client callback (real WebSocket/runtime coordination with supplied Git listings and watcher notifications) and invalidated scan/reconnect races keep their exact owning scope, without replacement-equivalence or rendered-headless proof. Retire the entire dated38-case receipt through its effective currentCommand. Preserve the unrelated SSH bridge receipt and paired Electron receipt within their original commands. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Local deterministic evidence covers git-common classification, desktop watcher debounce counts, non-overlapping poller semantics, macOS native-watch fallback, paired-runtime publication to two independent clients with reconnect and stale-cache checks, and process generation-scope rollover across sibling targets. A headed macOS Electron host and separate paired Electron client both rendered a worktree created through the real Git binary and watcher entry path without reconnect. Linux/Windows desktop clients, multi-target live fanout, and WSL runs remain gaps. Audit1309: src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts: Keep real filesystem HEAD/loose/packed/relative metadata reads and traversal refusal. Remove invalid-oid/nonstandard-layout characterization. Lose malformed object-id and bare-dir omission alarms; no Git-produced layout claim. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1381 removes the two mock-forwarding registrations in src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts. Sibling attribution suppression and missing/unknown attribution refresh callback alarms are intentionally lost; no equivalent replacement or real hook lifecycle/status-update coverage is claimed. Remaining exact receipts, platform/provider scope, and budgets remain limited to their unchanged selectors; no new execution result is claimed. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/7086", "https://github.com/stablyai/orca/issues/16477" ], "invariant": "Index-only Git activity below the common Git directory must not emit worktrees:changed, invalidate worktree caches, or trigger fetchWorktrees fanout; structural add/remove/HEAD/gitdir/locked/config.worktree changes must still refresh worktrees and nudge Source Control. When the authoritative paired host accepts an external structural change for a uniquely identified server-local repo, each live client for that host must receive one existing host-scoped worktreesChanged invalidation and converge to the same repo/worktree identity without reconnect; duplicate watcher events must coalesce, stale cached or in-flight catalogs must not survive invalidation, and event-ignoring clients must remain compatible. Colliding local/SSH repo IDs must not publish the host-blind event until existing semantics can carry owner identity. External head moves (commit, amend, reset) must reach background worktree rows through spawn-free metadata reads, never through structural fanout. A process generation-scope rollover revokes every direct SSH target and old-scope provider request, not only the target whose counter exhausted.", - "oracle": "Module layout SSH policy: Retire reset/private-arithmetic generation rollover registrations. The two retained local-versus-SSH mutation refusals do not establish process-scope rollover or sibling-token invalidation; remove this unrelated gate selector and its rollover assertion claim. Unchanged unrelated execution receipts retain only their original scope. No replacement, fresh rollover execution or cross-platform proof is claimed. Historical prior account (preserved verbatim): Audit2003: Remove the standalone one-client shared-runtime/headless-publication example. The retained two-client callback (real WebSocket/runtime coordination with supplied Git listings and watcher notifications) and invalidated scan/reconnect races keep their exact owning scope, without replacement-equivalence or rendered-headless proof. Retire the entire dated38-case receipt through its effective currentCommand. Preserve the unrelated SSH bridge receipt and paired Electron receipt within their original commands. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Classify exact git-common paths as structural, status-only, or ignored; count notifications from debounced watcher events; force the Linux/Windows poll path to emit allowlisted leaf events, detect linked HEAD rewrites independent of entry-directory mtime, and surface in-place index rewrites via the backstop re-stat; diff head identities from metadata-file reads and notify only real head moves. Join the real runtime RPC server to two independently authenticated E2EE clients plus an event-ignoring client, advance the host Git inventory, trigger duplicate structural watcher callbacks, and require one host renderer notification plus one runtime event and a refreshed catalog per subscribed client; require the event-ignoring client to refresh safely on explicit read. Hold a scan after it captures old inventory, join it from a second paired client, publish the watcher invalidation, advance Git independently, and require both overlapping RPCs to retry or join one fresh scan before returning. Disconnect one client, advance inventory again, and require reconnect to read current state without stale event replay. Give a watcher a local repo ID colliding with an SSH owner and require the host renderer refresh while the unqualified runtime event stays absent. Force the real path in isolated Electron apps with git worktree add, a host Git inventory assertion, store-subscription barriers, matching host/client worktree identity, and visible rows in both renderers. For direct SSH, roll one exhausted target into a fresh process generation scope while invalidating sibling target tokens, and fill a partial pushed authority before clearing that target's PTY bindings once. Audit1381 removes the two mock-forwarding registrations in src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts. Sibling attribution suppression and missing/unknown attribution refresh callback alarms are intentionally lost; no equivalent replacement or real hook lifecycle/status-update coverage is claimed. Remaining exact receipts, platform/provider scope, and budgets remain limited to their unchanged selectors; no new execution result is claimed.", + "oracle": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Module layout SSH policy: Retire reset/private-arithmetic generation rollover registrations. The two retained local-versus-SSH mutation refusals do not establish process-scope rollover or sibling-token invalidation; remove this unrelated gate selector and its rollover assertion claim. Unchanged unrelated execution receipts retain only their original scope. No replacement, fresh rollover execution or cross-platform proof is claimed. Historical prior account (preserved verbatim): Audit2003: Remove the standalone one-client shared-runtime/headless-publication example. The retained two-client callback (real WebSocket/runtime coordination with supplied Git listings and watcher notifications) and invalidated scan/reconnect races keep their exact owning scope, without replacement-equivalence or rendered-headless proof. Retire the entire dated38-case receipt through its effective currentCommand. Preserve the unrelated SSH bridge receipt and paired Electron receipt within their original commands. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Classify exact git-common paths as structural, status-only, or ignored; count notifications from debounced watcher events; force the Linux/Windows poll path to emit allowlisted leaf events, detect linked HEAD rewrites independent of entry-directory mtime, and surface in-place index rewrites via the backstop re-stat; diff head identities from metadata-file reads and notify only real head moves. Join the real runtime RPC server to two independently authenticated E2EE clients plus an event-ignoring client, advance the host Git inventory, trigger duplicate structural watcher callbacks, and require one host renderer notification plus one runtime event and a refreshed catalog per subscribed client; require the event-ignoring client to refresh safely on explicit read. Hold a scan after it captures old inventory, join it from a second paired client, publish the watcher invalidation, advance Git independently, and require both overlapping RPCs to retry or join one fresh scan before returning. Disconnect one client, advance inventory again, and require reconnect to read current state without stale event replay. Give a watcher a local repo ID colliding with an SSH owner and require the host renderer refresh while the unqualified runtime event stays absent. Force the real path in isolated Electron apps with git worktree add, a host Git inventory assertion, store-subscription barriers, matching host/client worktree identity, and visible rows in both renderers. For direct SSH, roll one exhausted target into a fresh process generation scope while invalidating sibling target tokens, and fill a partial pushed authority before clearing that target's PTY bindings once. Audit1381 removes the two mock-forwarding registrations in src/renderer/src/components/right-sidebar/source-control/sync/git-status-push-signal-refresh.test.ts. Sibling attribution suppression and missing/unknown attribution refresh callback alarms are intentionally lost; no equivalent replacement or real hook lifecycle/status-update coverage is claimed. Remaining exact receipts, platform/provider scope, and budgets remain limited to their unchanged selectors; no new execution result is claimed.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/worktrees/creation/worktree-base-directory-event-filter.test.ts src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts src/main/window/attach-main-window-services.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts", "ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-external-worktree-discovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts --reporter=dot" ], @@ -3478,7 +3453,6 @@ "src/main/ipc/worktrees/creation/worktree-base-directory-event-filter.test.ts", "src/main/ipc/worktrees/creation/worktree-head-identity-reader.test.ts", "src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts", - "src/main/window/attach-main-window-services.test.ts", "tests/e2e/paired-external-worktree-discovery.spec.ts", "src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts" ], @@ -3506,12 +3480,6 @@ "an event-ignoring client remains compatible, and colliding local/SSH owners do not publish an owner-blind event" ] }, - { - "file": "src/main/window/attach-main-window-services.test.ts", - "assertions": [ - "main-window wiring installs the runtime as the watched-worktree remote-client notifier alongside the existing repo notifier" - ] - }, { "file": "tests/e2e/paired-external-worktree-discovery.spec.ts", "assertions": [ @@ -3583,7 +3551,11 @@ "Audit2003 historical original assertionRefs object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"file\": \"src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts\",\n \"assertions\": [\n \"duplicate host watcher callbacks coalesce to one local notification and one worktreesChanged event for each of two live paired clients\",\n \"host inventory and both paired catalogs advance to the same worktree identity after runtime cache invalidation\",\n \"an invalidated in-flight host scan and a second client's joined read converge through one fresh retry before either can return stale data\",\n \"a disconnected client reconnects to current catalog state without replaying a stale invalidation\",\n \"an event-ignoring client remains compatible, and colliding local/SSH owners do not publish an owner-blind event\",\n \"the shared runtime publication remains valid without a headed renderer notifier\"\n ]\n }", "Audit2003 historical original evidenceRuns object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"date\": \"2026-08-26\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/watched-worktree-catalog-notification.test.ts src/main/runtime/external-worktree-paired-client-discovery.integration.test.ts src/main/window/attach-main-window-services.test.ts\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts src/main/window/attach-main-window-services.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 6.19,\n \"summary\": \"Three watcher/runtime/wiring files passed with 38 tests, including two-client publication, reconnect, stale scan fencing, headless parity, owner-collision suppression, failure isolation, and main-window notifier wiring. Historical run: the watched-worktree-catalog-notification suite was later removed as mock forwarding coverage; it is not an active gate or replacement-equivalence claim.\"\n }", "Module layout SSH policy: Retire reset/private-arithmetic generation rollover registrations. The two retained local-versus-SSH mutation refusals do not establish process-scope rollover or sibling-token invalidation; remove this unrelated gate selector and its rollover assertion claim. Unchanged unrelated execution receipts retain only their original scope. No replacement, fresh rollover execution or cross-platform proof is claimed.", - "Historical SSH generation selector and assertion metadata before policy retirement, preserved verbatim; not current coverage:\n\"pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/connection/authority/ssh-connection-generation.test.ts --reporter=dot\"\n\"src/main/ssh/connection/authority/ssh-connection-generation.test.ts\"\n{\n \"file\": \"src/main/ssh/connection/authority/ssh-connection-generation.test.ts\",\n \"assertions\": [\n \"one exhausted target rolls the process generation scope and invalidates every sibling target token\",\n \"old-scope mutation expectations fail while the new-scope authority continues rotating\"\n ]\n }" + "Historical SSH generation selector and assertion metadata before policy retirement, preserved verbatim; not current coverage:\n\"pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/connection/authority/ssh-connection-generation.test.ts --reporter=dot\"\n\"src/main/ssh/connection/authority/ssh-connection-generation.test.ts\"\n{\n \"file\": \"src/main/ssh/connection/authority/ssh-connection-generation.test.ts\",\n \"assertions\": [\n \"one exhausted target rolls the process generation scope and invalidates every sibling target token\",\n \"old-scope mutation expectations fail while the new-scope authority continues rotating\"\n ]\n }", + "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. All earlier notes and dated/archived evidence retain original scopes.", + "Exact prior command before deleted attach-main-window-services selector removal: \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts src/main/window/attach-main-window-services.test.ts\"", + "Exact retired testFiles selector: \"src/main/window/attach-main-window-services.test.ts\"", + "Complete prior assertionRef retired as historical data only: {\n \"file\": \"src/main/window/attach-main-window-services.test.ts\",\n \"assertions\": [\n \"main-window wiring installs the runtime as the watched-worktree remote-client notifier alongside the existing repo notifier\"\n ]\n }" ], "demotionRule": "Keep experimental or demote if the focused gate flakes without a product or harness bug, if index-only churn can emit worktrees:changed, or if structural add/remove/HEAD/lock changes fail to converge." }, @@ -3706,15 +3678,15 @@ "providers": ["local", "daemon", "ssh"], "coveredPlatforms": ["linux"], "coveredProviders": [], - "coverageNotes": "Audit2271: Linux coverage is limited to the unchanged serve-signal-exit-diagnostic supervisor selector and the late-handoff-after-child-exit assertion recorded below. It does not cover desktop promotion, renderer continuity, persistent PTYs or native updater behavior. No current local, daemon or SSH provider execution is established; coveredProviders is empty. Historical macOS/provider scope remains only in preserved prior accounts and archived receipts. Audit2252 removes the entire handassembled serve promotion/renderer hydration suite. Retired alarms: queued and repeated activation coalescing, duplicate serve suppression, unavailable-provider diagnostic, and zero resume/replacement accounting on independently supplied renderer state. The fixture never joined actual daemon-to-renderer delivery. These exact alarms have no equivalent replacement assigned. Remaining gate selectors keep their existing narrower scope; historical dated receipts remain verbatim and do not validate this changed selector set. No fresh runtime, native/provider, live remote/mobile, cross-platform or performance result is claimed. Archived removed active entries verbatim: commands: \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/serve-desktop-promotion-session-continuity.test.ts\"\ntestFiles: \"src/renderer/src/lib/serve-desktop-promotion-session-continuity.test.ts\"\nassertionRefs: {\n \"file\": \"src/renderer/src/lib/serve-desktop-promotion-session-continuity.test.ts\",\n \"assertions\": [\n \"a forced desktop relaunch reaching the headless lock owner opens exactly one window, and only after the persistent provider settles\",\n \"a duplicate `orca serve` launch never promotes the headless owner\",\n \"the renderer promoted inside the serve process resumes zero agents while daemon panes survive, before and after those panes rebind their PTYs\",\n \"no replacement resume tab, startup command, or automatic-resume claim is created, and every surviving session record is left untouched\"\n ]\n } Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: Retire CLI supervisor outcome, local-open promotion and paired-open projection alarms; launch retains only the two referenced stream-framing cases. Remaining CLI refusal/timeout cases do not replace headless-promotion coverage. Preserve both independent dated receipts at their original commands. Reduced selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1589 removes mock-only CLI forwarding, canned provisioning/catalog/error projections and private inventories without equivalent replacement coverage. Retained cases exercise actual local markdown/paste/reconciliation, stream framing/backpressure/output-drain, temporary directory cleanup and persisted handoff with injected host/provider/process boundaries. No real Jira, provisioning, remote launch, native pipe/process-tree authority or deployed provider catalog proof. Assertion references use the surviving handoff registration titles; changed-selector historical receipts are retired and unaffected receipts remain unchanged. Historical scope before this audit: Deterministic unit coverage exercises activation gating, single-instance ownership, local/remote CLI status, headless binding persistence, local daemon identity, SSH identity transfer, the promoted renderer's agent-resume accounting, and the macOS serve update handoff from staged installer through atomic bundle replacement and target-version readiness. Supervisor settlement coverage prevents a late handoff-completion failure from rearming termination after the replacement child exits. A macOS Electron journey covers headless promotion and persistent PTY identity. A disposable locally signed Electron canary exercised real ShipIt and a temporary LaunchAgent with the compiled production supervisor; full packaged Orca and Linux/Windows serve updates remain uncollected. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2271: Linux coverage is limited to the unchanged serve-signal-exit-diagnostic supervisor selector and the late-handoff-after-child-exit assertion recorded below. It does not cover desktop promotion, renderer continuity, persistent PTYs or native updater behavior. No current local, daemon or SSH provider execution is established; coveredProviders is empty. Historical macOS/provider scope remains only in preserved prior accounts and archived receipts. Audit2252 removes the entire handassembled serve promotion/renderer hydration suite. Retired alarms: queued and repeated activation coalescing, duplicate serve suppression, unavailable-provider diagnostic, and zero resume/replacement accounting on independently supplied renderer state. The fixture never joined actual daemon-to-renderer delivery. These exact alarms have no equivalent replacement assigned. Remaining gate selectors keep their existing narrower scope; historical dated receipts remain verbatim and do not validate this changed selector set. No fresh runtime, native/provider, live remote/mobile, cross-platform or performance result is claimed. Archived removed active entries verbatim: commands: \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/serve-desktop-promotion-session-continuity.test.ts\"\ntestFiles: \"src/renderer/src/lib/serve-desktop-promotion-session-continuity.test.ts\"\nassertionRefs: {\n \"file\": \"src/renderer/src/lib/serve-desktop-promotion-session-continuity.test.ts\",\n \"assertions\": [\n \"a forced desktop relaunch reaching the headless lock owner opens exactly one window, and only after the persistent provider settles\",\n \"a duplicate `orca serve` launch never promotes the headless owner\",\n \"the renderer promoted inside the serve process resumes zero agents while daemon panes survive, before and after those panes rebind their PTYs\",\n \"no replacement resume tab, startup command, or automatic-resume claim is created, and every surviving session record is left untouched\"\n ]\n } Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: Retire CLI supervisor outcome, local-open promotion and paired-open projection alarms; launch retains only the two referenced stream-framing cases. Remaining CLI refusal/timeout cases do not replace headless-promotion coverage. Preserve both independent dated receipts at their original commands. Reduced selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1589 removes mock-only CLI forwarding, canned provisioning/catalog/error projections and private inventories without equivalent replacement coverage. Retained cases exercise actual local markdown/paste/reconciliation, stream framing/backpressure/output-drain, temporary directory cleanup and persisted handoff with injected host/provider/process boundaries. No real Jira, provisioning, remote launch, native pipe/process-tree authority or deployed provider catalog proof. Assertion references use the surviving handoff registration titles; changed-selector historical receipts are retired and unaffected receipts remain unchanged. Historical scope before this audit: Deterministic unit coverage exercises activation gating, single-instance ownership, local/remote CLI status, headless binding persistence, local daemon identity, SSH identity transfer, the promoted renderer's agent-resume accounting, and the macOS serve update handoff from staged installer through atomic bundle replacement and target-version readiness. Supervisor settlement coverage prevents a late handoff-completion failure from rearming termination after the replacement child exits. A macOS Electron journey covers headless promotion and persistent PTY identity. A disposable locally signed Electron canary exercised real ShipIt and a temporary LaunchAgent with the compiled production supervisor; full packaged Orca and Linux/Windows serve updates remain uncollected. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/8457", "https://github.com/stablyai/orca/issues/9563" ], "invariant": "A safely promotable headless serve process is the single app owner. Desktop activation preserves its daemon-backed sessions. On macOS, a CLI-supervised serve update keeps the node-mode parent alive across ShipIt's atomic bundle swap, restarts with the original serve arguments only after the target bundle is present, and clears handoff state only after that target version reports runtime readiness. Once a supervised child exits or fails to start, no late handoff completion may signal it or arm force-kill escalation. Unsupported or failed handoffs leave the current serving owner intact or recover it once without an install retry loop.", - "oracle": "Audit2252: The removed synthetic lock/gate/hydration fixture supplies no current promotion continuity oracle. Existing other selectors retain only their own independent scope; changed selector execution is pending. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: Retire CLI supervisor outcome, local-open promotion and paired-open projection alarms; launch retains only the two referenced stream-framing cases. Remaining CLI refusal/timeout cases do not replace headless-promotion coverage. Preserve both independent dated receipts at their original commands. Reduced selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Unit tests coalesce early activation, preserve daemon and SSH identity, and reproduce the update race with a staged target, old serving child, persistent CLI parent, atomic .app replacement, and replacement readiness message. They assert the parent does not exit for launchd to respawn the old app, the native updater does not launch an interactive GUI, the replacement version is verified before handoff completion, mismatches become durable failures without retries, and unsupported/preflight-failed installs do not invoke native quit or PTY cleanup. Force handoff completion to fail after the replacement child exits and require zero later child signals and zero escalation timers. A joined lock-owner/activation/hydration contract asserts that a forced relaunch opens exactly one window and that the renderer promoted inside the serve process launches zero agent resumes, creates no replacement tab or startup command, and leaves every surviving session record untouched. The Electron journey independently verifies headless promotion retains owner/runtime/daemon/PTY identity and terminal I/O.", + "oracle": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2252: The removed synthetic lock/gate/hydration fixture supplies no current promotion continuity oracle. Existing other selectors retain only their own independent scope; changed selector execution is pending. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: Retire CLI supervisor outcome, local-open promotion and paired-open projection alarms; launch retains only the two referenced stream-framing cases. Remaining CLI refusal/timeout cases do not replace headless-promotion coverage. Preserve both independent dated receipts at their original commands. Reduced selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Unit tests coalesce early activation, preserve daemon and SSH identity, and reproduce the update race with a staged target, old serving child, persistent CLI parent, atomic .app replacement, and replacement readiness message. They assert the parent does not exit for launchd to respawn the old app, the native updater does not launch an interactive GUI, the replacement version is verified before handoff completion, mismatches become durable failures without retries, and unsupported/preflight-failed installs do not invoke native quit or PTY cleanup. Force handoff completion to fail after the replacement child exits and require zero later child signals and zero escalation timers. A joined lock-owner/activation/hydration contract asserts that a forced relaunch opens exactly one window and that the renderer promoted inside the serve process launches zero agent resumes, creates no replacement tab or startup command, and leaves every surviving session record untouched. The Electron journey independently verifies headless promotion retains owner/runtime/daemon/PTY identity and terminal I/O.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/cli/runtime/launch.test.ts src/main/updater/serve-update-handoff.test.ts src/main/updater/updater.headless-serve-install.test.ts src/main/updater/mac-install/updater.mac-install.test.ts src/main/window/attach-main-window-services.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/cli/runtime/launch.test.ts src/main/updater/serve-update-handoff.test.ts src/main/updater/updater.headless-serve-install.test.ts src/main/updater/mac-install/updater.mac-install.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/cli/runtime/serve-signal-exit-diagnostic.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/startup/serve-desktop-activation.test.ts src/cli/runtime-client.test.ts src/cli/runtime/websocket-transport.test.ts src/main/runtime/construction/orca-runtime.test.ts", "pnpm exec electron-vite build --mode e2e", @@ -3836,7 +3808,10 @@ "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed.", "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed.", "Module layout policy correction: retire the remaining program-status-osc.spec.ts event-projection case (production/mock-derived pane-key oracle) and sign-in timeout case (real setTimeout wait with Date-only fake clocks). The runtime test registrar no longer imports that file. No replacement coverage or fresh execution is claimed for these losses; historical receipts retain their original source scope.", - "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope." + "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope.", + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged.", + "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. All earlier notes and dated/archived evidence retain original scopes.", + "Exact prior command before deleted attach-main-window-services selector removal: \"pnpm exec vitest run --config config/vitest.config.ts src/cli/runtime/launch.test.ts src/main/updater/serve-update-handoff.test.ts src/main/updater/updater.headless-serve-install.test.ts src/main/updater/mac-install/updater.mac-install.test.ts src/main/window/attach-main-window-services.test.ts\"" ], "demotionRule": "Quarantine the Electron journey only with a linked product or harness defect; demote if activation changes the owner/runtime/daemon/PTY identity, loses prior output, opens before provider readiness, or fails to honor a committed quit." }, @@ -3856,16 +3831,16 @@ "providers": ["local", "daemon", "ssh", "paired-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "paired-runtime"], - "coverageNotes": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic lifecycle, IPC, window-notification, and runtime ownership tests cover generation replacement, stale callbacks, same-frame old-document publication, blocked external navigation, cancelled renderer navigation, concurrent provisional starts, process loss, timeout cleanup, headless fallback, and competing windows. Isolated macOS Electron validation covers cancelled navigation, forced renderer recovery, and headless serve promotion with live daemon-backed PTY identity and I/O. Linux, Windows, WSL, SSH promotion, and mixed-version desktop/server live runs remain uncollected; the renderer generation stays local to Electron IPC and does not change the remote wire. The renderer scheduling fixture now retains in-flight coalescing only, and payload partitioning retains publication-failure and main-dropped-worktree retry. Immediate publication, stale SSH cleanup, reconnect resync and isolated partition membership alarms were removed; other lifecycle evidence does not establish equivalent coverage. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1400: src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic lifecycle, IPC, window-notification, and runtime ownership tests cover generation replacement, stale callbacks, same-frame old-document publication, blocked external navigation, cancelled renderer navigation, concurrent provisional starts, process loss, timeout cleanup, headless fallback, and competing windows. Isolated macOS Electron validation covers cancelled navigation, forced renderer recovery, and headless serve promotion with live daemon-backed PTY identity and I/O. Linux, Windows, WSL, SSH promotion, and mixed-version desktop/server live runs remain uncollected; the renderer generation stays local to Electron IPC and does not change the remote wire. The renderer scheduling fixture now retains in-flight coalescing only, and payload partitioning retains publication-failure and main-dropped-worktree retry. Immediate publication, stale SSH cleanup, reconnect resync and isolated partition membership alarms were removed; other lifecycle evidence does not establish equivalent coverage. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1400: src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/14066", "https://linear.app/stably/issue/STA-4016", "https://github.com/stablyai/orca/pull/14070" ], "invariant": "Every genuine renderer graph reload revision settles exactly once, while a blocked external navigation that preserves the current document never starts a revision. A cancelled renderer-document navigation restores authority only when that same renderer survived; cancellation after an earlier document committed remains fenced until publication or timeout. Replacing a reload cancels only the prior revision; its timer and callbacks cannot settle a newer revision. A desktop reload succeeds only from a publication carrying a new renderer-document generation, while a failed headless promotion may recover only from its originating window. Timeout, renderer loss, and close reach a terminal graph state, and successful desktop publication permanently retires headless sentinel fallback until a new headless runtime is established.", - "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Start a blocked external main-frame navigation and require the current renderer graph and notification path to remain authoritative. Start a same-renderer navigation, cancel it before commit, and require the renderer canary and ready authority to survive; coalesce overlapping provisional starts into one fence, and keep an earlier committed reload fenced if a later navigation is cancelled. Drive two genuine reloads half a timeout apart and require the first deadline to leave the second revision reloading while the second deadline alone makes it unavailable. During the second revision publish from the prior renderer document through the still-current main frame and require rejection without graph mutation or timeout cancellation. Restore headless authority after failed promotion, publish from a competing window, and require rejection while the sentinel remains authoritative. Then force a real renderer crash and separately promote an isolated headless serve owner; require runtime graph readiness, stable runtime/main/daemon/PTY identities, recovered visible terminal output, and post-recovery input/output.", + "oracle": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Start a blocked external main-frame navigation and require the current renderer graph and notification path to remain authoritative. Start a same-renderer navigation, cancel it before commit, and require the renderer canary and ready authority to survive; coalesce overlapping provisional starts into one fence, and keep an earlier committed reload fenced if a later navigation is cancelled. Drive two genuine reloads half a timeout apart and require the first deadline to leave the second revision reloading while the second deadline alone makes it unavailable. During the second revision publish from the prior renderer document through the still-current main frame and require rejection without graph mutation or timeout cancellation. Restore headless authority after failed promotion, publish from a competing window, and require rejection while the sentinel remains authoritative. Then force a real renderer crash and separately promote an isolated headless serve owner; require runtime graph readiness, stable runtime/main/daemon/PTY identities, recovered visible terminal output, and post-recovery input/output.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/window/runtime-renderer-notification-sender.test.ts src/main/window/renderer-document-navigation.test.ts src/main/ipc/runtime.test.ts src/main/window/attach-main-window-services.test.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/window/runtime-renderer-notification-sender.test.ts src/main/window/renderer-document-navigation.test.ts src/main/ipc/runtime.test.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts", "pnpm exec electron-vite build --mode e2e", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "SKIP_BUILD=1 pnpm exec playwright test e2e/renderer-crash-recovery-terminal-input.spec.ts tests/e2e/renderer-crash-recovery-terminal-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", @@ -3876,7 +3851,6 @@ "src/main/window/runtime-renderer-notification-sender.test.ts", "src/main/window/renderer-document-navigation.test.ts", "src/main/ipc/runtime.test.ts", - "src/main/window/attach-main-window-services.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", "src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts", "tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts", @@ -4005,7 +3979,11 @@ "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed.", "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed.", "Module layout policy correction: retire the remaining program-status-osc.spec.ts event-projection case (production/mock-derived pane-key oracle) and sign-in timeout case (real setTimeout wait with Date-only fake clocks). The runtime test registrar no longer imports that file. No replacement coverage or fresh execution is claimed for these losses; historical receipts retain their original source scope.", - "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope." + "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope.", + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged.", + "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. All earlier notes and dated/archived evidence retain original scopes.", + "Exact prior command before deleted attach-main-window-services selector removal: \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/window/runtime-renderer-notification-sender.test.ts src/main/window/renderer-document-navigation.test.ts src/main/ipc/runtime.test.ts src/main/window/attach-main-window-services.test.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-payload-partition.test.ts\"", + "Exact retired testFiles selector: \"src/main/window/attach-main-window-services.test.ts\"" ], "demotionRule": "Demote if a reload revision settles more than once, a stale document or competing window can publish, a timer survives settlement, desktop failure stays indefinitely reloading, headless fallback returns after successful promotion, or either isolated Electron journey loses runtime or PTY identity." }, @@ -4095,10 +4073,10 @@ "providers": ["remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["remote-runtime"], - "coverageNotes": "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic main-IPC contract tests cover disconnect-driven close delivery, exactly-once close, per-subscription teardown isolation against a failing socket close and a throwing liveness probe, containment of a throwing renderer send on the unguarded host-close path, and continued suppression of stale payloads from a retired transport. A headed paired-server journey (real Orca host plus a separate paired Orca desktop client) covers hidden-but-mounted reveal, cold-parked reveal, and cold-parked reveal across a disconnect/reconnect. Live Linux and Windows paired-server evidence and real sleep/wake transport loss remain uncollected.", + "coverageNotes": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic main-IPC contract tests cover disconnect-driven close delivery, exactly-once close, per-subscription teardown isolation against a failing socket close and a throwing liveness probe, containment of a throwing renderer send on the unguarded host-close path, and continued suppression of stale payloads from a retired transport. A headed paired-server journey (real Orca host plus a separate paired Orca desktop client) covers hidden-but-mounted reveal, cold-parked reveal, and cold-parked reveal across a disconnect/reconnect. Live Linux and Windows paired-server evidence and real sleep/wake transport loss remain uncollected.", "motivatingLinks": ["tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts"], "invariant": "Every renderer-held runtime subscription receives exactly one terminal close event when its transport is retired, including when the retirement advanced the transport generation first, and a single failing teardown never abandons that environment's remaining subscriptions nor escapes into the transport that reported the close. Payload frames from a retired transport stay suppressed. A revealed remote terminal therefore reattaches over a live multiplex connection: its buffer restores, typed input reaches the host PTY, the echo paints without a tab flip, and the PTY converges on the revealed pane grid.", - "oracle": "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): The main IPC contract test subscribes terminal.multiplex through the real handler, disconnects the environment, and asserts the renderer received exactly one {type: close} subscription event. Two isolation tests subscribe a second stream to the same environment and make the first one fail -- in its socket close, and in the liveness probe inside notifyClosed -- then assert the disconnect does not throw, both transports closed, and every close the renderer could still receive was delivered. A third drives a host-initiated close through the transport callback, which is the one notifyClosed call site with no surrounding guard, with a renderer send that throws, and asserts it cannot escape into the WebSocket close handler. A fourth test asserts that after retirement a late response frame is not forwarded and a late transport close does not re-send. The paired-server journey runs three reveal scenarios against one real host and one real paired desktop client, and for each records buffer restore, host-side receipt of the typed marker through an out-of-band host sink file, live paint without a tab flip, and PTY-versus-pane grid convergence.", + "oracle": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): The main IPC contract test subscribes terminal.multiplex through the real handler, disconnects the environment, and asserts the renderer received exactly one {type: close} subscription event. Two isolation tests subscribe a second stream to the same environment and make the first one fail -- in its socket close, and in the liveness probe inside notifyClosed -- then assert the disconnect does not throw, both transports closed, and every close the renderer could still receive was delivered. A third drives a host-initiated close through the transport callback, which is the one notifyClosed call site with no surrounding guard, with a renderer send that throws, and asserts it cannot escape into the WebSocket close handler. A fourth test asserts that after retirement a late response frame is not forwarded and a late transport close does not re-send. The paired-server journey runs three reveal scenarios against one real host and one real paired desktop client, and for each records buffer restore, host-side receipt of the typed marker through an out-of-band host sink file, live paint without a tab flip, and PTY-versus-pane grid convergence.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts", "pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" @@ -4215,7 +4193,11 @@ "Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope.", "Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope.", "Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope.", - "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes." + "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes.", + "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts\",\n \"pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\"tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts\"]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts\",\n \"assertions\": [\n \"a revealed hidden-but-mounted remote terminal restores, accepts input, and paints live\",\n \"a revealed cold-parked remote terminal restores, accepts input, and paints live\",\n \"a cold-parked remote terminal revealed after a runtime disconnect and reconnect restores, accepts input, and paints live\",\n \"the host PTY grid converges on the revealed pane grid in every scenario\"\n ]\n }\n ]", + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged.", + "Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. All previous note strings, dated receipts, archived raw receipts and prior gap entries retain their original scopes.", + "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. All earlier notes and dated/archived evidence retain original scopes." ], "demotionRule": "Demote if a retired runtime transport can leave a renderer subscription without a close event, if a close is delivered more than once, if one failing teardown strands its sibling subscriptions, if payload frames from a retired transport reach the renderer, or if a revealed remote terminal can stay blank or reject input after a reconnect." }, @@ -4333,7 +4315,7 @@ "providers": ["remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3342 retires the complete mobile editor/diff tab-publication projection suite: editor/diff serialization, workspace-document privacy withholding, pending/focus and capability/options projections are intentionally lost without equivalent replacement. The surviving focused selectors are unexecuted in this source composition. Six complete compound macOS receipts whose command fields select the changed source are retired verbatim as history; their other selected tests receive no promoted evidence. Other dated receipts keep their original scope; no fresh runtime/UI/mobile/mixed-version or cross-platform validation is claimed. Audit3335 retires the complete three-case browser-tabs snapshot assembly suite: canonical snapshot replay/placement/focus, local host-page adoption and unstamped host echo leaving a local page untouched alarms are intentionally lost without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/network, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit3108: doc-preview-grants.test.ts now retains only the stale grant-rejection race: a late rejected grant request must not evict a newer grant registry entry, witnessed by later revocation of grant-2. Retire stable minted-location and outside-workspace POSIX/Windows request-projection alarms without replacement. The direct nonempty grant selector remains unchanged; no real grant-server/file authorization, SSH/HTML delivery or native-focus result is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1899 replays sealed Audit1895: workspace-doc-history.test.ts is entirely removed from its current command and testFiles. Supplied recency/dedupe/cap/title/identity examples and the10000-row getter-read budget alarm are intentionally lost. No current assertionRef or active receipt selects that file. Unrelated active receipts and all prior gap literals remain verbatim; no replacement history/index-work coverage or new browser/paired-preview gate execution is claimed. Historical coverage account before Audit1899: Audit1853 reduces LinkActionPopover.test.tsx and archives its complete 2026-09-06 mixed-selector receipt. The lost copy/open-state and Settings callback-order/omission alarms are accepted without equivalent replacement coverage. No fresh execution of this gate is credited. Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1568 removes API inventories, supplied mock-value/forwarding assertions, implementation-shape tables and negative/setup cases that do not reach their intended boundary, without equivalent replacement claims. Retained changed definitions exercise owned manager lifetime/queue/refcount/clamp and real synthetic process/files/staging boundaries. Seventeen unchanged native Electron definitions across this combined audit are statically reviewed and not rerun. Changed native suites exercise local popup wire/cookie/session and clean/native process-identity behavior; known popup-admission flaws remain unfixed. Unit native/event/session/registry inputs remain injected. No actual OS focus, registry/host execution, CRX verification or durable restart proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1564 retires copied cookie key recipes, mock bridge/preview forwarding and flag tables, source-spelling/script inventories and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise actual scoped SQLite merge/rollback/schema refusal, owned cancellation and grant authority/canonical containment, ranged response consistency, replacement guest ownership and executed guest-script promise/DOM cleanup behavior. Session, host response, geometry/observer and transport producers remain injected where documented. One unchanged native extension definition is not rerun locally; no actual remote filesystem, native layout/focus or authentication claim. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1386 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A macOS desktop host and a separate paired Electron client exercise the Explorer preview action end to end: the document renders inside the client-local orca-preview guest, the client gains exactly one browser workspace and it is the document one, the host's own page registry and tab snapshot gain nothing, the split does not take focus from the source editor, an explicit click activates the preview, and closing it with its X leaves the editor and terminal intact. Both host oracles are read in a run where an ordinary URL browser tab from the same client does arrive in them, because a host that cannot project browser pages at all would otherwise answer the absence question the same way. A second journey quits that client with a document tab open and relaunches it on the same profile, which is the restore the user's original report turned on: the same workspace row comes back blank and named by the document, renders again, and does so over a grant URL that differs from the one that was quit. The same journey pins the guest URL to the orca-preview scheme, so a regression back to file:// or to a host browser page is visible. The rewritten journey caught a live gap the old one could not see: since previews became browser pages they had no chrome to hand focus to their guest, so main refused every reported link click as coming from an unfocused guest and the one route out of a preview was dead. Main's own log answered it — registered true, grant live, focused false — after the embedder reported the anchor really taking six real presses. The pane now hands focus over when it is the reader's surface, and the journey routes. The preview's own components moved out of the editor folder into browser-pane/workspace-doc/ with this change, since a preview is a browser pane and no longer an editor one; their i18n keys keep the historical auto.components.editor.HtmlDocPreview prefix rather than dropping thirty translated strings across four locales for a tidier key path. Seven gate commands named those files by their old paths and were re-issued at the new ones, and the nine dated runs behind them were retired rather than left naming files that are no longer there, on the same principle this gate already applied twice: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. Each retired record's finding is carried into the replacement run recorded below it, including the red half of the entry/subresource pair, which was re-measured by re-applying its mutant at the new path rather than being dropped. The fence over the page-management channels was decided channel by channel before it was built, and that decision record is: of the 23 channels that can name a page, 6 are allowed for a workspace-document page — the tool channels the reader drives, which reach it through the one authority that reads both halves of the registry — 9 refuse (download accept and cancel, devtools, certificate proceed, client page metadata publish, viewport override, WebAuthn account response, registration probe, registration repair), 3 cannot name a page at all because they take a profile or a worktree instead, and the rest are the registration and activation doors, refused on membership. What shipped is not the per-channel guard that classification implies: eleven call sites read the browsing map directly, so a guard per channel is exactly the caller-flag seam that has to be remembered at every future call site. The registry was split in two instead, which makes the classification structural — a document guest is absent from the browsing map, so every refusing channel refuses by absence rather than by a guard, and a channel added later inherits the refusal without being classified at all. Unit contracts cover grant scoping and path containment, per-owner read routing, refusal of a truncated or over-cap read, the old-server binary degradation, scheme admission on will-attach-webview, the guest navigation policy, the plan layer's local/SSH/paired/out-of-worktree routing, and the distinct sentence the reader sees for each failure reason. The paired browser-creation surfaces this gate still owns — capability rejection cleanup, canonical page identity, reconciliation rollback, close convergence — keep their existing headed and headless journeys. Linux and Windows live journeys remain gaps. A refused subresource is a notice on a rendered document rather than a failure panel, since only the entry document's failure leaves the reader with nothing; the entry document is served as text by every owner and cannot be refused for its format at all. Grants die with the renderer document that minted them, at window creation and on every reload, because the renderer holds the only record of which preview owns which grant. The mint and revoke channels answer only the trusted renderer, and a preview tab is never republished to mobile clients, which have no grant to read it with. External URLs leave the preview only via a trusted user click on an anchor while the preview is focused; script-driven navigation and popups reach nothing. The guest's navigation sinks are deny-only and route no URL at all, and the guest carries a preview-only preload, pinned by will-attach-webview and denied to every other attach path, whose capture-phase click handler reports an anchor's URL to main; main answers only a report from a preview guest with a live bound grant that is the focused contents, and only for http(s). Two earlier reader-facing records from 2026-08-26, which measured a shape where a subresource failure was filtered out and the panel still carried an unsupported-asset sentence, were retired with that shape rather than left contradicting the 10/10 runs of the command they share. Two more were retired on the same principle when the external-link design changed: a record showing that removing a recent-input gate let the unattended document open two browser tabs, and a record showing that dropping the webview's allowpopups attribute left a target=_blank press with nothing to route. Both measured machinery that no longer exists — the input gate could not tell a script's navigation from the click it followed, which is the case now recorded below, and the preload intercepts the press before Chromium considers a popup at all, so allowpopups was removed. WebRTC is fenced by the guest's IP-handling policy alone: this Chromium answers a webrtc content-security-policy directive as unrecognized and gathers candidates anyway, so the directive is deliberately absent from the served policy and a unit assertion keeps it out. A standalone Electron probe on the same version gathered 7 candidates including a STUN reflexive one without the policy and 0 with it. Two command paths this gate used to carry no longer exist, and their structured evidence was retired with them rather than left naming files that are no longer there: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. The first is src/renderer/src/lib/file-preview-capability-cleanup.test.ts, deleted in STA-5557 when HTML previews stopped creating paired browser tabs: on 2026-08-12 its five-assertion STA-4063 oracle ran red 5/5 on scan e4c278eb52 and on main bc2e30000b, partially green 2/5 on pre-fix PR #14100, and green 5/5 on candidate 14b5877a75; the surviving half of that oracle is web-runtime-browser-capability-cleanup.test.ts, still commanded above. The second is tests/e2e/paired-remote-html-browser-focus.spec.ts, renamed in STA-5557 to paired-remote-html-preview-local-render.spec.ts because the journey no longer proves anything about browser focus: its 2026-08-12 runs established the owning-runtime routing and no-focus-steal behavior of the then-current browser-tab preview (red on main 346e59c879 and a90a18d43d, green on candidates d05217c40d and b7de9c0961, red again with only the side-preview focus or routing seam disabled), and its 2026-08-26 runs are recorded below under the current path. An adversarial pass after the journey landed found four coverage gaps rather than shipping defects, and all four are pinned here. The page url had a third door: the navigation commit wrote whatever url was reported, unfenced, and while nothing reaches it for a document page today it sat one report away from giving a document page a URL that persistence, the publish boundary and the address bar all read. The group projection was the load-bearing half of the mobile publish boundary that no test had: removing it alone left the whole suite green, because no test in it had tab groups, while the phone payload gained a group whose order and active tab named a document tab it was never sent. The focus handoff was covered only in the narrowing direction, so widening it — dropping the page-activity check, or either half of the reader-surface check — survived both suites. And the handoff itself was offered once and never again, so another app taking the front left the preview's one route out shut until the pane remounted, which is a desktop gap rather than a test-only one. The standalone capability-cleanup and browser-placement ledger suites were removed, including their mixed-version rejection, cleanup transfer, capacity and partition alarms. web-runtime-session.test.ts no longer supplies browser creation, rollback or recovery assertions. The grouped workspace-document exclusion remains; the separate no-group publication example was removed. Existing live/browser-store evidence does not establish equivalent replacement alarms. Earlier descriptions of the removed fixtures and their run results are historical. The client-owned-placement and layout-groups suites are removed. The broad mirror fixture no longer supplies preview placement/reservation/move assertions. Browser rows retain pre-response replay and real local-workspace reuse; focus intent retains response ordering and exact-leaf sibling ordering. Supplied browser-layout and placement/focus projection alarms are lost; retained evidence is narrower and not equivalent. The test-value audit retires renderer grant-release mock ledgers, direct creation/title/session-field copies, notification/onboarding calls and several placement/per-page projections. Canonical-ID rejection, document reopen/restore and preview URL fences remain; they do not prove close-to-registry revocation or replace every lost alarm. Historical execution evidence is unchanged. The test-value audit removed the direct legacy editor-preview hydration example from tabs-hydration.test.ts. Dropping legacy preview chrome while preserving the same-document ordinary editor no longer has that alarm. The surviving corrupt-id deduplication case does not cover that migration, and retained preview journeys are not equivalent replacement coverage. Historical run counts and migration mutation findings describe the earlier suite. Audit1308: src/renderer/src/components/editor/EditorPanelShell.header.test.tsx removed. Header visibility and mocked editor-surface inventory alarms disappear. No equivalent replacement coverage is claimed. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1386: src/renderer/src/lib/doc-preview-grants.test.ts reduced. Repeated-mount mint count, ordinary release/remint and failed-mint cache retry standalone alarms removed; no actual grant server/access test. No equivalent replacement coverage is claimed. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/browser/guest-lifecycle/manager/browser-manager-guest-policy-profile.test.ts removed. Loses workspace-document in-grant navigation/popup refusal, cleanup/re-attach, cross-registry guest authorization and browsing-map separation alarms. No equivalent browser policy coverage is claimed. No equivalent replacement coverage is claimed. Audit1421 removes browser-address-bar-suggestions.test.ts. Document suggestion title/path matching, recency merging and path-prefix ranking alarms are lost. No equivalent replacement coverage is claimed. Historical receipts remain scoped to unchanged selectors; the reduced command has no new execution result. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", + "coverageNotes": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3342 retires the complete mobile editor/diff tab-publication projection suite: editor/diff serialization, workspace-document privacy withholding, pending/focus and capability/options projections are intentionally lost without equivalent replacement. The surviving focused selectors are unexecuted in this source composition. Six complete compound macOS receipts whose command fields select the changed source are retired verbatim as history; their other selected tests receive no promoted evidence. Other dated receipts keep their original scope; no fresh runtime/UI/mobile/mixed-version or cross-platform validation is claimed. Audit3335 retires the complete three-case browser-tabs snapshot assembly suite: canonical snapshot replay/placement/focus, local host-page adoption and unstamped host echo leaving a local page untouched alarms are intentionally lost without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/network, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit3108: doc-preview-grants.test.ts now retains only the stale grant-rejection race: a late rejected grant request must not evict a newer grant registry entry, witnessed by later revocation of grant-2. Retire stable minted-location and outside-workspace POSIX/Windows request-projection alarms without replacement. The direct nonempty grant selector remains unchanged; no real grant-server/file authorization, SSH/HTML delivery or native-focus result is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1899 replays sealed Audit1895: workspace-doc-history.test.ts is entirely removed from its current command and testFiles. Supplied recency/dedupe/cap/title/identity examples and the10000-row getter-read budget alarm are intentionally lost. No current assertionRef or active receipt selects that file. Unrelated active receipts and all prior gap literals remain verbatim; no replacement history/index-work coverage or new browser/paired-preview gate execution is claimed. Historical coverage account before Audit1899: Audit1853 reduces LinkActionPopover.test.tsx and archives its complete 2026-09-06 mixed-selector receipt. The lost copy/open-state and Settings callback-order/omission alarms are accepted without equivalent replacement coverage. No fresh execution of this gate is credited. Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1568 removes API inventories, supplied mock-value/forwarding assertions, implementation-shape tables and negative/setup cases that do not reach their intended boundary, without equivalent replacement claims. Retained changed definitions exercise owned manager lifetime/queue/refcount/clamp and real synthetic process/files/staging boundaries. Seventeen unchanged native Electron definitions across this combined audit are statically reviewed and not rerun. Changed native suites exercise local popup wire/cookie/session and clean/native process-identity behavior; known popup-admission flaws remain unfixed. Unit native/event/session/registry inputs remain injected. No actual OS focus, registry/host execution, CRX verification or durable restart proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1564 retires copied cookie key recipes, mock bridge/preview forwarding and flag tables, source-spelling/script inventories and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise actual scoped SQLite merge/rollback/schema refusal, owned cancellation and grant authority/canonical containment, ranged response consistency, replacement guest ownership and executed guest-script promise/DOM cleanup behavior. Session, host response, geometry/observer and transport producers remain injected where documented. One unchanged native extension definition is not rerun locally; no actual remote filesystem, native layout/focus or authentication claim. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1386 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A macOS desktop host and a separate paired Electron client exercise the Explorer preview action end to end: the document renders inside the client-local orca-preview guest, the client gains exactly one browser workspace and it is the document one, the host's own page registry and tab snapshot gain nothing, the split does not take focus from the source editor, an explicit click activates the preview, and closing it with its X leaves the editor and terminal intact. Both host oracles are read in a run where an ordinary URL browser tab from the same client does arrive in them, because a host that cannot project browser pages at all would otherwise answer the absence question the same way. A second journey quits that client with a document tab open and relaunches it on the same profile, which is the restore the user's original report turned on: the same workspace row comes back blank and named by the document, renders again, and does so over a grant URL that differs from the one that was quit. The same journey pins the guest URL to the orca-preview scheme, so a regression back to file:// or to a host browser page is visible. The rewritten journey caught a live gap the old one could not see: since previews became browser pages they had no chrome to hand focus to their guest, so main refused every reported link click as coming from an unfocused guest and the one route out of a preview was dead. Main's own log answered it — registered true, grant live, focused false — after the embedder reported the anchor really taking six real presses. The pane now hands focus over when it is the reader's surface, and the journey routes. The preview's own components moved out of the editor folder into browser-pane/workspace-doc/ with this change, since a preview is a browser pane and no longer an editor one; their i18n keys keep the historical auto.components.editor.HtmlDocPreview prefix rather than dropping thirty translated strings across four locales for a tidier key path. Seven gate commands named those files by their old paths and were re-issued at the new ones, and the nine dated runs behind them were retired rather than left naming files that are no longer there, on the same principle this gate already applied twice: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. Each retired record's finding is carried into the replacement run recorded below it, including the red half of the entry/subresource pair, which was re-measured by re-applying its mutant at the new path rather than being dropped. The fence over the page-management channels was decided channel by channel before it was built, and that decision record is: of the 23 channels that can name a page, 6 are allowed for a workspace-document page — the tool channels the reader drives, which reach it through the one authority that reads both halves of the registry — 9 refuse (download accept and cancel, devtools, certificate proceed, client page metadata publish, viewport override, WebAuthn account response, registration probe, registration repair), 3 cannot name a page at all because they take a profile or a worktree instead, and the rest are the registration and activation doors, refused on membership. What shipped is not the per-channel guard that classification implies: eleven call sites read the browsing map directly, so a guard per channel is exactly the caller-flag seam that has to be remembered at every future call site. The registry was split in two instead, which makes the classification structural — a document guest is absent from the browsing map, so every refusing channel refuses by absence rather than by a guard, and a channel added later inherits the refusal without being classified at all. Unit contracts cover grant scoping and path containment, per-owner read routing, refusal of a truncated or over-cap read, the old-server binary degradation, scheme admission on will-attach-webview, the guest navigation policy, the plan layer's local/SSH/paired/out-of-worktree routing, and the distinct sentence the reader sees for each failure reason. The paired browser-creation surfaces this gate still owns — capability rejection cleanup, canonical page identity, reconciliation rollback, close convergence — keep their existing headed and headless journeys. Linux and Windows live journeys remain gaps. A refused subresource is a notice on a rendered document rather than a failure panel, since only the entry document's failure leaves the reader with nothing; the entry document is served as text by every owner and cannot be refused for its format at all. Grants die with the renderer document that minted them, at window creation and on every reload, because the renderer holds the only record of which preview owns which grant. The mint and revoke channels answer only the trusted renderer, and a preview tab is never republished to mobile clients, which have no grant to read it with. External URLs leave the preview only via a trusted user click on an anchor while the preview is focused; script-driven navigation and popups reach nothing. The guest's navigation sinks are deny-only and route no URL at all, and the guest carries a preview-only preload, pinned by will-attach-webview and denied to every other attach path, whose capture-phase click handler reports an anchor's URL to main; main answers only a report from a preview guest with a live bound grant that is the focused contents, and only for http(s). Two earlier reader-facing records from 2026-08-26, which measured a shape where a subresource failure was filtered out and the panel still carried an unsupported-asset sentence, were retired with that shape rather than left contradicting the 10/10 runs of the command they share. Two more were retired on the same principle when the external-link design changed: a record showing that removing a recent-input gate let the unattended document open two browser tabs, and a record showing that dropping the webview's allowpopups attribute left a target=_blank press with nothing to route. Both measured machinery that no longer exists — the input gate could not tell a script's navigation from the click it followed, which is the case now recorded below, and the preload intercepts the press before Chromium considers a popup at all, so allowpopups was removed. WebRTC is fenced by the guest's IP-handling policy alone: this Chromium answers a webrtc content-security-policy directive as unrecognized and gathers candidates anyway, so the directive is deliberately absent from the served policy and a unit assertion keeps it out. A standalone Electron probe on the same version gathered 7 candidates including a STUN reflexive one without the policy and 0 with it. Two command paths this gate used to carry no longer exist, and their structured evidence was retired with them rather than left naming files that are no longer there: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. The first is src/renderer/src/lib/file-preview-capability-cleanup.test.ts, deleted in STA-5557 when HTML previews stopped creating paired browser tabs: on 2026-08-12 its five-assertion STA-4063 oracle ran red 5/5 on scan e4c278eb52 and on main bc2e30000b, partially green 2/5 on pre-fix PR #14100, and green 5/5 on candidate 14b5877a75; the surviving half of that oracle is web-runtime-browser-capability-cleanup.test.ts, still commanded above. The second is tests/e2e/paired-remote-html-browser-focus.spec.ts, renamed in STA-5557 to paired-remote-html-preview-local-render.spec.ts because the journey no longer proves anything about browser focus: its 2026-08-12 runs established the owning-runtime routing and no-focus-steal behavior of the then-current browser-tab preview (red on main 346e59c879 and a90a18d43d, green on candidates d05217c40d and b7de9c0961, red again with only the side-preview focus or routing seam disabled), and its 2026-08-26 runs are recorded below under the current path. An adversarial pass after the journey landed found four coverage gaps rather than shipping defects, and all four are pinned here. The page url had a third door: the navigation commit wrote whatever url was reported, unfenced, and while nothing reaches it for a document page today it sat one report away from giving a document page a URL that persistence, the publish boundary and the address bar all read. The group projection was the load-bearing half of the mobile publish boundary that no test had: removing it alone left the whole suite green, because no test in it had tab groups, while the phone payload gained a group whose order and active tab named a document tab it was never sent. The focus handoff was covered only in the narrowing direction, so widening it — dropping the page-activity check, or either half of the reader-surface check — survived both suites. And the handoff itself was offered once and never again, so another app taking the front left the preview's one route out shut until the pane remounted, which is a desktop gap rather than a test-only one. The standalone capability-cleanup and browser-placement ledger suites were removed, including their mixed-version rejection, cleanup transfer, capacity and partition alarms. web-runtime-session.test.ts no longer supplies browser creation, rollback or recovery assertions. The grouped workspace-document exclusion remains; the separate no-group publication example was removed. Existing live/browser-store evidence does not establish equivalent replacement alarms. Earlier descriptions of the removed fixtures and their run results are historical. The client-owned-placement and layout-groups suites are removed. The broad mirror fixture no longer supplies preview placement/reservation/move assertions. Browser rows retain pre-response replay and real local-workspace reuse; focus intent retains response ordering and exact-leaf sibling ordering. Supplied browser-layout and placement/focus projection alarms are lost; retained evidence is narrower and not equivalent. The test-value audit retires renderer grant-release mock ledgers, direct creation/title/session-field copies, notification/onboarding calls and several placement/per-page projections. Canonical-ID rejection, document reopen/restore and preview URL fences remain; they do not prove close-to-registry revocation or replace every lost alarm. Historical execution evidence is unchanged. The test-value audit removed the direct legacy editor-preview hydration example from tabs-hydration.test.ts. Dropping legacy preview chrome while preserving the same-document ordinary editor no longer has that alarm. The surviving corrupt-id deduplication case does not cover that migration, and retained preview journeys are not equivalent replacement coverage. Historical run counts and migration mutation findings describe the earlier suite. Audit1308: src/renderer/src/components/editor/EditorPanelShell.header.test.tsx removed. Header visibility and mocked editor-surface inventory alarms disappear. No equivalent replacement coverage is claimed. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1386: src/renderer/src/lib/doc-preview-grants.test.ts reduced. Repeated-mount mint count, ordinary release/remint and failed-mint cache retry standalone alarms removed; no actual grant server/access test. No equivalent replacement coverage is claimed. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/browser/guest-lifecycle/manager/browser-manager-guest-policy-profile.test.ts removed. Loses workspace-document in-grant navigation/popup refusal, cleanup/re-attach, cross-registry guest authorization and browsing-map separation alarms. No equivalent browser policy coverage is claimed. No equivalent replacement coverage is claimed. Audit1421 removes browser-address-bar-suggestions.test.ts. Document suggestion title/path matching, recency merging and path-prefix ranking alarms are lost. No equivalent replacement coverage is claimed. Historical receipts remain scoped to unchanged selectors; the reduced command has no new execution result. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-5557/remote-html-preview-render-workspace-files-locally-over-the-file", "https://linear.app/stably/issue/STA-3872/unable-to-open-html-files-in-remote-server", @@ -4344,7 +4326,7 @@ "https://github.com/stablyai/orca/pull/13876" ], "invariant": "Opening one HTML preview from a paired client renders the workspace document in exactly one client-local browser tab, located by that document and served over the orca-preview scheme. The client gains exactly that one browser workspace and it is the document one — blank where a URL page carries a URL, named by the document, with the chip naming the file — while the host gains no browser page at all, neither in its own page registry nor in the tab snapshot its clients publish into. The preview occupies its own split without taking focus from the source editor; an explicit click activates it, and closing it removes only the preview. Following a document from a file link is the other half of that switch and does move the reader to it, tab group included, whether the preview is new or already open, because opening a file is a request to look at it. A document tab quit with the client comes back as the same row on a grant the relaunched client mints afresh. A preview is named by the browser page it is open in, not by a namespace of its own, and the page registry has two halves: a workspace-document guest is registered in its own map and is absent from the browsing one entirely. That absence is the fence. Page, session and profile management, agent tab enumeration and command targeting, download routing and certificate attribution all read the browsing map directly, in more places than a per-channel guard could be remembered in, so none of them can name a document page and none of them carries a guard. Browser tools the reader drives (element grab, hover describe, selection capture, the annotation viewport bridge) are the one operation that legitimately spans the halves, and they go through the single authority that reads both, keyed by the page and its hosting renderer. The halves are disjoint in both directions: browsing registration refuses a page the document half already holds, and minting a grant refuses a page the browsing half already holds, so one id can never name a surface in both. The headless backend acts on that refusal by destroying the window it had already opened rather than leaving a policy-less page behind an id nothing can drive, keeping nothing under that id for its own shutdown to hand back. Registration refuses on the same terms when the guest it was asked about is already gone. The exit door is guarded in both its halves: a preview withdraws by revoking its grant and never through the unregister channel, so a page the document half holds arriving there is refused before either the registration teardown or the grab-state disposal beside it, which would otherwise drop the intent an in-flight preview grab compares by identity and leave that grab answering ok without ever arming its guest. A bridge request whose guest does not resolve is refused without tearing down the page it named, so a misaddressed request cannot cancel a healthy page's in-flight downloads and grabs. The annotation viewport bridge resolves its guest when its serialized op actually runs rather than when the request arrived, so a cross-process navigation while it waited cannot leave the bridge installed in a retired guest while the reader looks at a new one. State main keys by a preview's page is disposed when that page's grant is revoked, which is the only signal a preview's surface is gone. A tool asking for a page whose guest has not attached yet waits for that registration and arms when it arrives, rather than answering not-ready at the reader; that wait resolves only the request already naming this page, never the worktree-wide or any-tab waits the CLI and agents use to ask for a browser tab to drive. Handing the previewed document to the reader's own machine routes on the owners its grant was minted against — the file's own connection owner and the worktree's own runtime owner, neither read from the tab's stored fields. Only a document proven to live on this machine reaches the client OS; one with a resolved remote owner is downloaded first; and one whose owner cannot be resolved at all, workspace root included, is refused with a message naming that, because the download route would otherwise read the same absolute path on the client and hand back a same-named local file under the remote document's name. A runtime-owned path that falls outside its worktree root is refused by that route itself and surfaces as a failure toast rather than a download. Nothing the document does writes a file to this machine either: the preview partition denies downloads outright instead of routing them through the browser download flow, which has no page to attribute a preview's bytes to and would otherwise reserve a name in this desktop's Downloads folder and write them there unprompted. That refusal is visible to the reader and invisible to the document: the preview's shell carries a fixed sentence saying downloads are off, published at most once per preview per interval so a document asking in a loop cannot fill Orca's chrome, while the page itself gets back exactly what it got before, which is nothing. The sentence names no file, because the document chooses the name it offers; and a refusal never takes the document away the way an entry document's own failure does, whatever it names. A preview is a browser tab, not an editor tab in a preview mode: it is named the way a browser tab is named — by the document it shows when that document declares a title, and by the file it shows when it does not — while the chip goes on naming the file and the host whatever the document calls itself. A title is refused on the same terms the url is: a document that declares none has Chromium report the grant URL as its title, and that title is stored, mirrored onto the tab and written to disk, so anything carrying the scheme falls back to the file instead. It is created by the preview action as a page located by its document, it carries the workspace-relative path copy the editor's path header owned, and closing it revokes the grant that made the document readable while a URL tab closing beside it revokes nothing. Chrome persisted by builds that made previews editor tabs is dropped on restore rather than coming back naming a surface no restore can produce, and the ordinary editor tab for the same document is left alone. A document tab is held back at the mobile publish boundary — no client holds its grant, and the wire has no tab kind for it — while an ordinary browser tab beside it still publishes. It is held back from the group projection that publishes tab order, recency and group activity as well as from the tab list itself, so no published group names a tab the phone is never sent. A browser page can be located by a workspace document instead of a URL, and the document is the whole of its stored identity. The grant and the orca-preview URL that document is served over are minted when the page mounts and replaced by a hard reload, so neither is ever written to the page's url, mirrored onto its tab, persisted or published: such a page's url is the blank URL from creation through restore, including when a session written elsewhere carries a grant URL in, and what the session carries is the worktree and path a restored page mints afresh against today's owners. Every door onto a page's url holds that line — creation, the title update, and the navigation commit alike — so a report about a document page cannot give it a URL it never had, and the title fallback and the loading affordance follow the url each door actually wrote. The mirror carries the document too, so a tab entry cannot go on naming a document its active page has left. Every guest in the app is policy-attached through one door: a workspace document takes a restricted profile there rather than a separate installer beside it, so the attachment bookkeeping that door owns — what registration refuses, and what teardown frees — covers a preview on the same terms as a browsing page, and a preview takes none of the browsing machinery that door installs. That authority answers from the moment the embedder hands the guest over rather than only after a later navigation: the guest binds to the grant it is already showing, so the tools reach the document the reader opened and not just one they navigated to. A read the host reports as truncated or over-cap is refused rather than served partially, and a document outside the paired worktree is refused with a message naming that boundary instead of a bare read failure. The rendered document reaches nothing off-machine on its own: every served response carries a self-only content security policy, the preview session cancels any request that is not in-document, subframes cannot navigate outside the grant, a guest no document has yet bound to a grant may not navigate at all, the guest gathers no ICE candidates, and an SSH path that canonicalizes outside the grant root is refused before it is read. The one route out is a link the reader presses: a trusted click on an anchor, reported by the preview's own preload from a guest still bound to a live grant, leaves through the configured browser destination and captured source route — and only after the reader confirms the exact destination URL, so a document cannot spend a single stray press exfiltrating what it can read into a link it authored. The preview hands its guest that focus itself whenever it is the surface the reader is in — a browsing page gets it from the chrome around it, and a preview has no chrome to get it from — and it does so only then, so a preview mounted behind a terminal or an editor never takes the keyboard from what the reader is actually in. It offers again when the window itself takes focus back and nothing in the embedder has claimed that focus, because another app coming to the front lands focus on the embedder rather than the guest and the route out would otherwise stay shut until something remounted the pane — while the same window focus also arrives when the reader presses a tab, that being the guest's own blur returning, and taking focus back from there would fight the reader for their own click. Nothing else does. A navigation or popup the document starts by itself is swallowed whatever else is happening, including immediately after a genuine press elsewhere in the document, so a page that can read its grant cannot hand it to a browser tab; a middle click opens nothing; and a fragment link is answered inside the document. A preview attach carries the preview preload and no renderer-supplied one, and no other attach path can acquire it. A subresource the workspace will not send degrades the document to a notice naming that file, never to a failure panel over a page that rendered. A grant outlives neither the tab that owns it nor the renderer document that minted it, and only the trusted renderer can mint or revoke one. For the browser creations this gate still owns, owner-pinned creation returns the canonical host page identity before navigation readiness; delayed navigation cannot turn a created page into an unidentifiable failure or a duplicate retry. Capability rejection before host mutation must preserve the original error, issue no RPC, surface a failure toast, and remove only a caller-declared newly-created empty split. Post-create reconciliation failure requires exact rollback; ambiguous rollback rejects without local fallback.", - "oracle": "Audit3342 retires the complete mobile editor/diff tab-publication projection suite: editor/diff serialization, workspace-document privacy withholding, pending/focus and capability/options projections are intentionally lost without equivalent replacement. The surviving focused selectors are unexecuted in this source composition. Six complete compound macOS receipts whose command fields select the changed source are retired verbatim as history; their other selected tests receive no promoted evidence. Other dated receipts keep their original scope; no fresh runtime/UI/mobile/mixed-version or cross-platform validation is claimed. Audit3335 retires the complete three-case browser-tabs snapshot assembly suite: canonical snapshot replay/placement/focus, local host-page adoption and unstamped host echo leaving a local page untouched alarms are intentionally lost without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/network, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit3108: doc-preview-grants.test.ts now retains only the stale grant-rejection race: a late rejected grant request must not evict a newer grant registry entry, witnessed by later revocation of grant-2. Retire stable minted-location and outside-workspace POSIX/Windows request-projection alarms without replacement. The direct nonempty grant selector remains unchanged; no real grant-server/file authorization, SSH/HTML delivery or native-focus result is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1421 narrows renderer unit coverage as recorded in coverageNotes. Prior oracle descriptions are historical for the changed suite. The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): In paired Electron, write an HTML fixture that declares its own title on the host, invoke the Explorer preview action on the client, and require the document text to be readable out of the orca-preview guest before judging any absence. With that presence established, require the client to hold exactly one browser workspace more than its baseline and that workspace to be the document one: page and tab url blank, the document path mirrored onto both, the tab named by the document's title, the chip naming the file, no editor row of the retired preview species anywhere, and the guest URL carrying the orca-preview scheme. Ask the host through its own page registry as well as through the tab snapshot, and in the same run open an ordinary URL browser tab from the same client and require that one to arrive in both — the presence precondition without which “the host gained nothing” is satisfied just as well by an oracle that cannot see browser pages at all. Require the preview to sit in a group other than the source editor's while the active group and tab remain the source editor's. Then click away to the terminal, click the preview tab, require it to reactivate and still render, close it with its own X, and require the document tab to be gone while the host still holds only the URL tab and the source group, source editor and terminal survive. Quit the client with a document tab open and relaunch it on the same profile: require the same workspace row to come back, blank and named by the document, rendering the document again over a grant URL that differs from the one that was quit, with no preview-scheme or document-named page anywhere in what the host holds. Prove the halves are live by flipping one product property at a time and requiring the run to fail: publish document workspaces to the host like ordinary ones, and stop mirroring the document onto the workspace row. Have the fixture document attempt its own egress on every load — an unattended window.open and location.href to an off-machine URL, plus an inline ICE gathering probe — and require the same baseline counts and a candidate count of zero, so the document's own attempts are measured rather than assumed. Then, as a separate phase after the close oracle has already run, bring the client window to the front, press the document's heading with a real mouse event, and require the document to report that the same press drove it to attempt a second window.open and location.href while both browser counts stay at that phase's baseline and nothing routes — the case a recent-input gate cannot distinguish from the press's own effect. Only then press the target=_blank link with a real mouse event and require both a recorded routing call that returned success and a browser count above that baseline, with the preview tab still open. Drive the preload's click policy as a unit oracle over a real document: a dispatched click, a trusted press on an external anchor, an anchor reached through what it wraps, an SVG animated href, a sibling preview link, fragment and percent-encoded fragment targets, a bare hash, and a middle click. Create a browser page located by a workspace document, handing creation a live grant URL, and require its stored url, its mirrored tab url and the written session payload all to be blank with no orca-preview string anywhere in what was written, while an ordinary page created the same way keeps the URL it was given and asks for the address bar the document page never does. Parse the written page and tab through the session schema and require the document to survive both halves. Hydrate them back and require the document page to return blank and still named — including when its page row was salvaged away and only the tab's own copy remains, and when a foreign session carried a grant URL into both rows. Drive the mirror across a page switch out of the document and back, and across a repair in which the document is the only mirrored field that differs. Name a document page from its document and require the tab to take that name, name it with an empty title and require the file, name it with a live grant URL and require the file again with no preview scheme anywhere in the written session, and require an ordinary blank browser tab beside it to still be called New Tab. Dispatch a title update out of a rendered preview's own guest and require it to reach the page state while the identity chip still reads the document's workspace-relative path. Attach a browsing guest and a workspace-document guest through the same method in one run and require the browsing one to take clicked-link routing, popup handling and auth-identity detach tracking while the document guest takes none of them, stays inside the grant it is showing, denies every window it asks for, and is dropped from the page-keyed document registry by the same teardown that frees its id for a later attach. Register a browsing guest and attach a workspace-document guest in one run against the real manager, require the one door to answer each page with the guest of its own half, and require the document page to be absent from the browsing map and from its enumeration. Drive both browsing registration entry points with a page the document half already holds and require them to register nothing, and drive the mint channel with a page the browsing half already holds and require it to refuse; and drive the offscreen one with a guest that is missing and with one already destroyed, requiring the same refusal. Arm a grab on a live preview target, drive the unregister channel at that same target in the window before the queued operation runs, and require the grab to reach the guest anyway — then drive the same sequence for an ordinary browser page and require its grab state to be disposed after all. Hold one viewport-bridge op open, queue a second behind it, swap the page's guest while that second op waits, and require the injection to land in the guest the page has then. Revoke a grant after a tool has run against its page and require that page's grab state to be cancelled and disposed. Ask a tool for a document page whose guest has not attached, require the request to park in the registration wait, attach the guest, and require the same request to arm on it; require a page nothing ever renders to answer not-ready once that wait elapses. With a document open, ask a tool for a browsing page id and require it to be answered by the browsing half or not at all, with the same channel reaching the document guest under the page it really renders. Drive open-externally for a document whose per-file owner is remote while the workspace-scoped owner is unresolved, for a runtime-owned worktree whose preview tab carries no runtime id of its own, and for a worktree that resolves no runtime owner while the tab still carries one, requiring the download route in each; and for an owner that cannot be resolved at all, and for an unknown workspace root while nothing names another host, requiring a refusal that neither opens nor downloads. Drive the headless backend with a page the document half already holds and require it to reject, destroy the window, and unregister nothing — then shut the backend down and require it still to have unregistered nothing. Navigate a bound preview guest at a second grant through both latch events and require it to stay on the grant it bound to. Mount a preview while a renderer drag is already in flight and require its guest to be click-through at the moment it is appended, not a turn later. Render the editor panel shell in each remaining tab mode and require the path header exactly where the surface does not already name itself. Drive the preview action and require a browser tab located by the document rather than an editor tab, require a second open of the same document to activate the tab it is already in, and require closing that tab to revoke its grant while a URL tab closed beside it revokes none. Publish a worktree holding a document tab and a URL tab and require only the URL tab to reach the mobile snapshot. Install the shared partition policies for a preview partition and for an ordinary browsing partition in the same run, fire each one's own will-download listener, and require the preview's to cancel while the browsing one still reaches the download router — then require the preview protocol installer to be what asks for that deny. In the same run, require the cancelled download to raise a reader-facing notice and the routed one to raise none. require the guest registry to name the bound grant for a live preview guest and nothing for a contents that is not one, has committed no document, or is gone. Drive the shell with a refusal and require one fixed sentence, still one row after three more refusals, standing beside an asset failure rather than being counted with it, gone behind the failure panel, and ignored when it names another preview's grant. Drive the main-side report gate directly for a sender that is no preview guest, a guest with no bound or a revoked grant, a genuine press Electron's webview focus flag misreports as unfocused, and non-web URLs; drive the reader-facing confirmation for accept, cancel, and a confirmed tab the browser refuses; and drive will-attach-webview in both preload directions. Run the per-owner reader, grant-containment, scheme-admission, guest-policy, and plan-routing contracts as unit oracles, including a host-reported truncation, an over-cap binary, and an out-of-worktree paired path. Drive the reader-facing component with the payloads the reader can actually produce — the entry document fails only as truncated or unreadable, a subresource additionally as a refused format — and require the asset case to leave the guest mounted. Drive the closed-tab cleanup hook, the window installer, and the grant IPC handlers directly, requiring the grant to be released when the preview tab closes, cleared at window creation and on a cross-document main-frame navigation, and refused to any sender that is not the trusted renderer. For the browser creations this gate still owns, run the unchanged contract oracle for direct create and side-preview callers with absent status, unknown capabilities, and a mixed-version host, requiring the original unsupported error or visible toast, zero RPCs, and no retained new split; hold a real navigation response beyond the 15-second client deadline after host creation and require the first RPC to return the exact host inventory page ID, one host page, and no retry; repeat reconciliation faults against headless serve and retain the separate exact-page reconciliation rollback oracle. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", + "oracle": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3342 retires the complete mobile editor/diff tab-publication projection suite: editor/diff serialization, workspace-document privacy withholding, pending/focus and capability/options projections are intentionally lost without equivalent replacement. The surviving focused selectors are unexecuted in this source composition. Six complete compound macOS receipts whose command fields select the changed source are retired verbatim as history; their other selected tests receive no promoted evidence. Other dated receipts keep their original scope; no fresh runtime/UI/mobile/mixed-version or cross-platform validation is claimed. Audit3335 retires the complete three-case browser-tabs snapshot assembly suite: canonical snapshot replay/placement/focus, local host-page adoption and unstamped host echo leaving a local page untouched alarms are intentionally lost without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/network, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit3108: doc-preview-grants.test.ts now retains only the stale grant-rejection race: a late rejected grant request must not evict a newer grant registry entry, witnessed by later revocation of grant-2. Retire stable minted-location and outside-workspace POSIX/Windows request-projection alarms without replacement. The direct nonempty grant selector remains unchanged; no real grant-server/file authorization, SSH/HTML delivery or native-focus result is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1421 narrows renderer unit coverage as recorded in coverageNotes. Prior oracle descriptions are historical for the changed suite. The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): In paired Electron, write an HTML fixture that declares its own title on the host, invoke the Explorer preview action on the client, and require the document text to be readable out of the orca-preview guest before judging any absence. With that presence established, require the client to hold exactly one browser workspace more than its baseline and that workspace to be the document one: page and tab url blank, the document path mirrored onto both, the tab named by the document's title, the chip naming the file, no editor row of the retired preview species anywhere, and the guest URL carrying the orca-preview scheme. Ask the host through its own page registry as well as through the tab snapshot, and in the same run open an ordinary URL browser tab from the same client and require that one to arrive in both — the presence precondition without which “the host gained nothing” is satisfied just as well by an oracle that cannot see browser pages at all. Require the preview to sit in a group other than the source editor's while the active group and tab remain the source editor's. Then click away to the terminal, click the preview tab, require it to reactivate and still render, close it with its own X, and require the document tab to be gone while the host still holds only the URL tab and the source group, source editor and terminal survive. Quit the client with a document tab open and relaunch it on the same profile: require the same workspace row to come back, blank and named by the document, rendering the document again over a grant URL that differs from the one that was quit, with no preview-scheme or document-named page anywhere in what the host holds. Prove the halves are live by flipping one product property at a time and requiring the run to fail: publish document workspaces to the host like ordinary ones, and stop mirroring the document onto the workspace row. Have the fixture document attempt its own egress on every load — an unattended window.open and location.href to an off-machine URL, plus an inline ICE gathering probe — and require the same baseline counts and a candidate count of zero, so the document's own attempts are measured rather than assumed. Then, as a separate phase after the close oracle has already run, bring the client window to the front, press the document's heading with a real mouse event, and require the document to report that the same press drove it to attempt a second window.open and location.href while both browser counts stay at that phase's baseline and nothing routes — the case a recent-input gate cannot distinguish from the press's own effect. Only then press the target=_blank link with a real mouse event and require both a recorded routing call that returned success and a browser count above that baseline, with the preview tab still open. Drive the preload's click policy as a unit oracle over a real document: a dispatched click, a trusted press on an external anchor, an anchor reached through what it wraps, an SVG animated href, a sibling preview link, fragment and percent-encoded fragment targets, a bare hash, and a middle click. Create a browser page located by a workspace document, handing creation a live grant URL, and require its stored url, its mirrored tab url and the written session payload all to be blank with no orca-preview string anywhere in what was written, while an ordinary page created the same way keeps the URL it was given and asks for the address bar the document page never does. Parse the written page and tab through the session schema and require the document to survive both halves. Hydrate them back and require the document page to return blank and still named — including when its page row was salvaged away and only the tab's own copy remains, and when a foreign session carried a grant URL into both rows. Drive the mirror across a page switch out of the document and back, and across a repair in which the document is the only mirrored field that differs. Name a document page from its document and require the tab to take that name, name it with an empty title and require the file, name it with a live grant URL and require the file again with no preview scheme anywhere in the written session, and require an ordinary blank browser tab beside it to still be called New Tab. Dispatch a title update out of a rendered preview's own guest and require it to reach the page state while the identity chip still reads the document's workspace-relative path. Attach a browsing guest and a workspace-document guest through the same method in one run and require the browsing one to take clicked-link routing, popup handling and auth-identity detach tracking while the document guest takes none of them, stays inside the grant it is showing, denies every window it asks for, and is dropped from the page-keyed document registry by the same teardown that frees its id for a later attach. Register a browsing guest and attach a workspace-document guest in one run against the real manager, require the one door to answer each page with the guest of its own half, and require the document page to be absent from the browsing map and from its enumeration. Drive both browsing registration entry points with a page the document half already holds and require them to register nothing, and drive the mint channel with a page the browsing half already holds and require it to refuse; and drive the offscreen one with a guest that is missing and with one already destroyed, requiring the same refusal. Arm a grab on a live preview target, drive the unregister channel at that same target in the window before the queued operation runs, and require the grab to reach the guest anyway — then drive the same sequence for an ordinary browser page and require its grab state to be disposed after all. Hold one viewport-bridge op open, queue a second behind it, swap the page's guest while that second op waits, and require the injection to land in the guest the page has then. Revoke a grant after a tool has run against its page and require that page's grab state to be cancelled and disposed. Ask a tool for a document page whose guest has not attached, require the request to park in the registration wait, attach the guest, and require the same request to arm on it; require a page nothing ever renders to answer not-ready once that wait elapses. With a document open, ask a tool for a browsing page id and require it to be answered by the browsing half or not at all, with the same channel reaching the document guest under the page it really renders. Drive open-externally for a document whose per-file owner is remote while the workspace-scoped owner is unresolved, for a runtime-owned worktree whose preview tab carries no runtime id of its own, and for a worktree that resolves no runtime owner while the tab still carries one, requiring the download route in each; and for an owner that cannot be resolved at all, and for an unknown workspace root while nothing names another host, requiring a refusal that neither opens nor downloads. Drive the headless backend with a page the document half already holds and require it to reject, destroy the window, and unregister nothing — then shut the backend down and require it still to have unregistered nothing. Navigate a bound preview guest at a second grant through both latch events and require it to stay on the grant it bound to. Mount a preview while a renderer drag is already in flight and require its guest to be click-through at the moment it is appended, not a turn later. Render the editor panel shell in each remaining tab mode and require the path header exactly where the surface does not already name itself. Drive the preview action and require a browser tab located by the document rather than an editor tab, require a second open of the same document to activate the tab it is already in, and require closing that tab to revoke its grant while a URL tab closed beside it revokes none. Publish a worktree holding a document tab and a URL tab and require only the URL tab to reach the mobile snapshot. Install the shared partition policies for a preview partition and for an ordinary browsing partition in the same run, fire each one's own will-download listener, and require the preview's to cancel while the browsing one still reaches the download router — then require the preview protocol installer to be what asks for that deny. In the same run, require the cancelled download to raise a reader-facing notice and the routed one to raise none. require the guest registry to name the bound grant for a live preview guest and nothing for a contents that is not one, has committed no document, or is gone. Drive the shell with a refusal and require one fixed sentence, still one row after three more refusals, standing beside an asset failure rather than being counted with it, gone behind the failure panel, and ignored when it names another preview's grant. Drive the main-side report gate directly for a sender that is no preview guest, a guest with no bound or a revoked grant, a genuine press Electron's webview focus flag misreports as unfocused, and non-web URLs; drive the reader-facing confirmation for accept, cancel, and a confirmed tab the browser refuses; and drive will-attach-webview in both preload directions. Run the per-owner reader, grant-containment, scheme-admission, guest-policy, and plan-routing contracts as unit oracles, including a host-reported truncation, an over-cap binary, and an out-of-worktree paired path. Drive the reader-facing component with the payloads the reader can actually produce — the entry document fails only as truncated or unreadable, a subresource additionally as a refused format — and require the asset case to leave the guest mounted. Drive the closed-tab cleanup hook, the window installer, and the grant IPC handlers directly, requiring the grant to be released when the preview tab closes, cleared at window creation and on a cross-document main-frame navigation, and refused to any sender that is not the trusted renderer. For the browser creations this gate still owns, run the unchanged contract oracle for direct create and side-preview callers with absent status, unknown capabilities, and a mixed-version host, requiring the original unsupported error or visible toast, zero RPCs, and no retained new split; hold a real navigation response beyond the 15-second client deadline after host creation and require the first RPC to return the exact host inventory page ID, one host page, and no retry; repeat reconciliation faults against headless serve and retain the separate exact-page reconciliation rollback oracle. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-grant-registry.test.ts src/main/browser/document-preview/doc-preview-file-reader.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/main/browser/document-preview/doc-preview-failure-notice.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/lib/browser/documents/doc-preview-grants.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts", @@ -4784,7 +4766,8 @@ "Audit3342 historical original evidenceRuns object, preserved verbatim; retired objects are not active evidence or replacement coverage:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser-workspace-doc-location.test.ts src/renderer/src/runtime/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/components/browser-pane/workspace-doc/workspace-doc-page-pane.test.tsx src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"result\": \"failed\",\n \"durationSeconds\": 3,\n \"summary\": \"Three sole-delta mutants on the third url door, each failing only the new store test: committing the reported url onto a document page, dropping the document from the title normalizer there (which renames the tab New Tab, since a blank url is what that fallback reads), and marking a blank document page loading. The ordinary-page half of the same test passes under all three, so the door is pinned as a document-only refusal rather than as a door that writes nothing.\"\n }", "Audit3342 historical original evidenceRuns object, preserved verbatim; retired objects are not active evidence or replacement coverage:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser-workspace-doc-location.test.ts src/renderer/src/runtime/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/components/browser-pane/workspace-doc/workspace-doc-page-pane.test.tsx src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"result\": \"failed\",\n \"durationSeconds\": 3,\n \"summary\": \"Two sole-delta mutants on the mobile publish boundary. Dropping the document from the group projection's browser ids fails only the new grouped test — the tab list stays correct because the per-tab guard still refuses the tab, and what breaks is a published group whose order and active tab name a tab the phone is never sent. This is the survivor the adversarial pass reported: it survives the whole suite without this test, because no other test in it has tab groups. Dropping the per-tab guard instead fails only the ungrouped test, so the two halves of the boundary are pinned separately.\"\n }", "Audit3342 historical original evidenceRuns object, preserved verbatim; retired objects are not active evidence or replacement coverage:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser-workspace-doc-location.test.ts src/renderer/src/runtime/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/components/browser-pane/workspace-doc/workspace-doc-page-pane.test.tsx src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"result\": \"failed\",\n \"durationSeconds\": 3,\n \"summary\": \"Three sole-delta mutants widening the focus handoff, the direction the adversarial pass found uncovered: dropping the page-activity half, dropping the active-tab-type half, and dropping the active-browser-tab half each fail exactly one of the pane's refusals — the inactive page, the terminal in front, and the other browser tab respectively. The presence half of that test passes under all three, so a pane that had stopped offering focus at all would still fail rather than pass the refusals vacuously.\"\n }", - "Audit3342 historical original evidenceRuns object, preserved verbatim; retired objects are not active evidence or replacement coverage:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser-workspace-doc-location.test.ts src/renderer/src/runtime/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/components/browser-pane/workspace-doc/workspace-doc-page-pane.test.tsx src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"result\": \"failed\",\n \"durationSeconds\": 3,\n \"summary\": \"One sole-delta mutant dropping the window-focus re-offer: the guest is focused once at mount and never again after the window comes back, which is the desktop gap behind it — another app taking the front leaves the preview's only route out shut until the pane remounts. It fails only the new re-offer test, and the refusing-preview case beside it stays green, so the re-offer is pinned as gated rather than unconditional.\"\n }" + "Audit3342 historical original evidenceRuns object, preserved verbatim; retired objects are not active evidence or replacement coverage:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser-workspace-doc-location.test.ts src/renderer/src/runtime/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/components/browser-pane/workspace-doc/workspace-doc-page-pane.test.tsx src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-editor-diff-tabs.test.ts src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx\",\n \"result\": \"failed\",\n \"durationSeconds\": 3,\n \"summary\": \"One sole-delta mutant dropping the window-focus re-offer: the guest is focused once at mount and never again after the window comes back, which is the desktop gap behind it — another app taking the front leaves the preview's only route out shut until the pane remounts. It fails only the new re-offer test, and the refusing-preview case beside it stays green, so the re-offer is pinned as gated rather than unconditional.\"\n }", + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged." ], "demotionRule": "Demote if a paired HTML preview creates a browser workspace on either side, renders from anything other than the orca-preview scheme, serves a read the host reported as truncated or over-cap, serves a document without the self-only content security policy, lets the preview session carry an off-machine request, reads an SSH path that canonicalizes outside its grant root, steals focus from the source editor when it opens, removes unrelated editor or terminal state on close, hides a document that rendered because one subresource was refused, leaves a grant readable after the tab or renderer that owns it is gone, mints one for a sender that is not the trusted renderer, opens a browser tab for a navigation the document started with no one at the keyboard, or lets the guest gather an ICE candidate; or if a paired browser creation this gate still owns produces duplicate client or host identities or loses its requested split." }, @@ -5819,12 +5802,12 @@ "providers": ["local", "daemon", "ssh", "remote-runtime", "wsl"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "remote-runtime"], - "coverageNotes": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial mobile-presence suite retains only five authored callbacks: admitted preview-paste completion across phone takeover, desktop take-back superseding mobile input, desktop viewport write/restore geometry, and held-fit reclaim convergence. Other supplied floor/rollback/selection/viewport/grace/disconnect/reconnect/orphan-state alarms are lost. No per-source assertion object exists to reassign. The one affected dated mobile-view-authority receipt is retired whole into historical notes with its full original/currentCommand/raw data preserved; it is not active corroboration for reduced candidate bytes. Imported mobile-subscribe registrations and retained callbacks remain bounded to their actual source obligations, without equivalent replacement or physical-phone/native-PTY claims. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1320 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic host/parser, process-classifier, snapshot-publication, mixed-version, renderer, and macOS Electron coverage proves the local and shared paired-runtime contracts. Direct SSH intentionally publishes no shell proof and immediately preserves incumbent behavior. WSL, Windows ConPTY, Linux desktop, and paired headed/headless journeys remain gaps. The audit removed the isolated terminal-multiplex pending-escape-tail forwarding test. Its direct RPC snapshot field-copy alarm is lost; retained parser, snapshot and lifecycle suites do not establish equivalent RPC field coverage. Audit1320: src/renderer/src/components/terminal-pane/remote-runtime-pty-snapshot-escape-tail.test.ts removed. Snapshot pending escape/alternate-screen/shell metadata forwarding and negative app-store-read alarm disappears. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/daemon/terminal-host-concurrent-create.test.ts reduced. Loses race deduplication, attach during unsettled ownership proof, retry after failed spawn, distinct-session parallelism, disposal waiting and shutdown retry-fencing alarms bundled with removed internal-call counts or real-time waits. No replacement-equivalence claim. src/main/daemon/terminal-checkpoint-serializer.test.ts reduced. Loses bounded native conversion/no-whole-candidate materialization and snapshot getter single-read alarms. Retained byte-size outcomes do not establish CPU/allocation bounds. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial mobile-presence suite retains only five authored callbacks: admitted preview-paste completion across phone takeover, desktop take-back superseding mobile input, desktop viewport write/restore geometry, and held-fit reclaim convergence. Other supplied floor/rollback/selection/viewport/grace/disconnect/reconnect/orphan-state alarms are lost. No per-source assertion object exists to reassign. The one affected dated mobile-view-authority receipt is retired whole into historical notes with its full original/currentCommand/raw data preserved; it is not active corroboration for reduced candidate bytes. Imported mobile-subscribe registrations and retained callbacks remain bounded to their actual source obligations, without equivalent replacement or physical-phone/native-PTY claims. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1320 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic host/parser, process-classifier, snapshot-publication, mixed-version, renderer, and macOS Electron coverage proves the local and shared paired-runtime contracts. Direct SSH intentionally publishes no shell proof and immediately preserves incumbent behavior. WSL, Windows ConPTY, Linux desktop, and paired headed/headless journeys remain gaps. The audit removed the isolated terminal-multiplex pending-escape-tail forwarding test. Its direct RPC snapshot field-copy alarm is lost; retained parser, snapshot and lifecycle suites do not establish equivalent RPC field coverage. Audit1320: src/renderer/src/components/terminal-pane/remote-runtime-pty-snapshot-escape-tail.test.ts removed. Snapshot pending escape/alternate-screen/shell metadata forwarding and negative app-store-read alarm disappears. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/daemon/terminal-host-concurrent-create.test.ts reduced. Loses race deduplication, attach during unsettled ownership proof, retry after failed spawn, distinct-session parallelism, disposal waiting and shutdown retry-fencing alarms bundled with removed internal-call counts or real-time waits. No replacement-equivalence claim. src/main/daemon/terminal-checkpoint-serializer.test.ts reduced. Loses bounded native conversion/no-whole-candidate materialization and snapshot getter single-read alarms. Retained byte-size outcomes do not establish CPU/allocation bounds. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": ["https://github.com/stablyai/orca/pull/16379"], "invariant": "After a TUI exits or is killed, reveal, reattach, snapshot replay, or renderer remount must not deliver terminal-owned mouse or alternate-screen protocol bytes to the surviving shell. Recovery is an ordered output barrier in the daemon session data path: an OSC 133;D completing while the alternate screen is still active pauses the stream at that exact byte boundary, a fresh execution-host process inspection proves shell ownership, and on proof a mode reset is injected as in-stream output so every consumer converges by parsing the same bytes and the queued post-boundary shell output (the prompt) lands on the normal buffer. Snapshots are pure reads. Any failure — refuted proof, timeout, queue overflow, session death, disposal — flushes the queue unmodified, preserving incumbent behavior; later command or mode bytes revoke proof. Clean alternate-screen exits prove ownership asynchronously without pausing.", - "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial mobile-presence suite retains only five authored callbacks: admitted preview-paste completion across phone takeover, desktop take-back superseding mobile input, desktop viewport write/restore geometry, and held-fit reclaim convergence. Other supplied floor/rollback/selection/viewport/grace/disconnect/reconnect/orphan-state alarms are lost. No per-source assertion object exists to reassign. The one affected dated mobile-view-authority receipt is retired whole into historical notes with its full original/currentCommand/raw data preserved; it is not active corroboration for reduced candidate bytes. Imported mobile-subscribe registrations and retained callbacks remain bounded to their actual source obligations, without equivalent replacement or physical-phone/native-PTY claims. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Run one fixed child-TUI journey for normal exit and cleanup-free SIGKILL. Assert renderer and host normal-buffer/non-mouse state, host snapshot terminalOwner metadata, exact PTY writes with no post-exit mouse report, unrelated-pane survival, post-boundary prompt output preserved (normal exit), ordered proof invalidation, bounded settlement and bail-out flush, one inspection per unclean episode with zero scans for ordinary output, split-escape safety at every chunk boundary, and old/new client-host fallback parity.", + "oracle": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial mobile-presence suite retains only five authored callbacks: admitted preview-paste completion across phone takeover, desktop take-back superseding mobile input, desktop viewport write/restore geometry, and held-fit reclaim convergence. Other supplied floor/rollback/selection/viewport/grace/disconnect/reconnect/orphan-state alarms are lost. No per-source assertion object exists to reassign. The one affected dated mobile-view-authority receipt is retired whole into historical notes with its full original/currentCommand/raw data preserved; it is not active corroboration for reduced candidate bytes. Imported mobile-subscribe registrations and retained callbacks remain bounded to their actual source obligations, without equivalent replacement or physical-phone/native-PTY claims. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Run one fixed child-TUI journey for normal exit and cleanup-free SIGKILL. Assert renderer and host normal-buffer/non-mouse state, host snapshot terminalOwner metadata, exact PTY writes with no post-exit mouse report, unrelated-pane survival, post-boundary prompt output preserved (normal exit), ordered proof invalidation, bounded settlement and bail-out flush, one inspection per unclean episode with zero scans for ordinary output, split-escape safety at every chunk boundary, and old/new client-host fallback parity.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/terminal-shell-recovery-barrier.test.ts src/main/daemon/sessions/testing/session-shell-recovery.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts src/main/providers/agent-foreground-process.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/terminal/layout/mobile-presence-lock.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/terminal-shell-recovery-barrier.test.ts src/main/daemon/sessions/testing/session-shell-recovery.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts src/main/providers/agent-foreground-process.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/terminal/layout/mobile-presence-lock.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts --reporter=dot", "pnpm exec electron-vite build --mode e2e", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" @@ -5840,9 +5823,6 @@ "src/main/providers/agent-foreground-process.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", "src/main/runtime/terminal/layout/mobile-presence-lock.test.ts", - "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts", - "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts", - "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts", "src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts", "src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts", "tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts", @@ -5949,7 +5929,9 @@ "Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed.", "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed.", "Module layout policy correction: retire the remaining program-status-osc.spec.ts event-projection case (production/mock-derived pane-key oracle) and sign-in timeout case (real setTimeout wait with Date-only fake clocks). The runtime test registrar no longer imports that file. No replacement coverage or fresh execution is claimed for these losses; historical receipts retain their original source scope.", - "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope." + "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope.", + "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/terminal-shell-recovery-barrier.test.ts src/main/daemon/sessions/testing/session-shell-recovery.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts src/main/providers/agent-foreground-process.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/terminal/layout/mobile-presence-lock.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts --reporter=dot\",\n \"pnpm exec electron-vite build --mode e2e\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/main/daemon/shell-readiness/testing/terminal-shell-recovery-barrier.test.ts\",\n \"src/main/daemon/sessions/testing/session-shell-recovery.test.ts\",\n \"src/main/daemon/sessions/testing/session.test.ts\",\n \"src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts\",\n \"src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts\",\n \"src/main/providers/agent-foreground-process.test.ts\",\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/main/runtime/terminal/layout/mobile-presence-lock.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts\",\n \"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts\",\n \"tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts\",\n \"tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/main/daemon/sessions/testing/session-shell-recovery.test.ts\",\n \"assertions\": [\n \"post-kill shell output survives into the normalized snapshot instead of the discarded alt buffer\",\n \"a snapshot taken during a split escape keeps the pending tail intact and stale proof is revoked by the completing bytes\"\n ]\n },\n {\n \"file\": \"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts\",\n \"assertions\": [\n \"the pending tail this gate threads over the wire folds identically at every code-unit split of the combined stream, including boundaries landing inside oscEsc/stringEsc\",\n \"the split sweep runs over an alphabet carrying CAN, SUB, doubled ESC inside OSC/DCS/SOS/PM/APC, BEL, C1 ST, NUL, DEL, intermediates, CJK, astral, and lone surrogates\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts\",\n \"assertions\": [\n \"normal exit and cleanup-free SIGKILL both restore a visible clean shell marker\",\n \"renderer logical buffer is normal and mouse tracking is disabled after host-proven recovery\",\n \"real pointer input writes no SGR mouse report to the surviving shell\",\n \"an unrelated pane remains live\"\n ]\n }\n ]", + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged." ], "demotionRule": "Keep experimental or demote if missing ownership proof changes incumbent behavior, a live TUI loses mouse/focus modes, foreground inspection enters ordinary output/reveal paths, or the focused Electron journey flakes without an identified product or harness fault." }, @@ -6207,7 +6189,7 @@ "providers": ["local", "daemon", "ssh", "runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "ssh", "runtime"], - "coverageNotes": "Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Live macOS Electron tests prove exact local PTY disappearance after parked-tab close and detached-pgid descendant death after agent close. A deterministic final-pane interleaving now proves durable tab retirement commits before externally owned PTY teardown can publish graph loss, and preserves an unrelated live canary through duplicate exit retirement. Deterministic tests also cover final-pane CLI close durability and same-incarnation handle continuity; persisted-empty restart suppression remains historical Electron evidence, alongside replacement and hard graph-loss stale fencing, preallocated-handle supersession, daemon and SSH routing, local/daemon pending-snapshot ownership across natural exit, stale-root descendant-signal suppression, graceful-to-immediate kill upgrades, duplicate-kill completion sharing, locale-stable bounded/fresh/coalesced process-table reads, deadline-safe successor scans, cycle-safe linear descendant traversal, target-only escalation indexing, 32-wide bulk teardown, source-scan timestamp identity, same-second PID ambiguity, ordinary runtime close ownership, unified-only hydration, split ownership, pane detach transfer, restart alias hydration, and late-hook suppression; live Linux, Windows, WSL, SSH, and remote-runtime process evidence remains pending. A paired macOS Electron journey (real attached-window desktop host plus a separate real paired desktop client, isolated profiles) covers the inverse authority direction for host-created terminals: a renderer graph sync must not retire a tab that `orca terminal create` made. The retained paired journey covers the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId. The repeated target-after-unrelated-terminal journey was retired; its separate ordering alarm is no longer provided. An earlier reading of this gate called a preceding host-created terminal and a `clientMutationId` protective; main-process instrumentation refuted that. The renderer's stale session write deleted the host tab from persistence in every variant, and only the delete's timing relative to the measured sync differed, so those rows were false negatives of a single-sync oracle. The defect was in persistence: persistPtyBinding did not raise the repo's terminal topology fence for the first host-admitted tab, leaving the renderer's pre-create tab list free to replay over it. Elapsed time and paired-client mirroring never decided anything. A windowless `orca serve` parity arm runs the identical oracle and passes on both the merge-base and the branch, confirming that topology does not exhibit the defect (the gate it turns on is window-conditioned) and that making the host binding unconditional did not regress it. All of this is macOS-local only. The reported incident occurred on a physical Windows host; we did not run against one. The claim that the mechanism is platform-independent rests on the authoritative-window gate and publication-epoch inheritance being OS-agnostic, not on Windows evidence, so no ConPTY, Windows window-lifecycle, update, or sleep behavior is covered here. The synthetic default-tabs unit suite was retired: its explicit-empty/default-tab assertions no longer supply unit evidence. This retirement supplies no new persisted-restart, runtime-routing, cross-platform, or mobile evidence; existing historical runs and counts remain historical. The test-value audit removes the isolated re-retirement-token/epoch, activity-cutoff, idle-reattach and sibling-restore examples. The cited exact retirement and chained-detach cases remain unchanged, alongside closed-tab revival fencing and alias churn bounds. Their retained evidence is not equivalent coverage for every removed permutation; historical execution evidence is unchanged. The test-value audit removed shared-owner snapshot/cold-restore reference examples, a direct absent-tab PTY-index update, caller-supplied host-owned teardown boolean/no-dispatch, and a single local-provider rejection example. It also removed hand-built detach-retention comparator examples for different runs, handles, provider identities, and handle-less rows without independent identity ingress. Their specific snapshot, missing-tab, host-decision, rejection-count, and comparator alarms are lost. Current exact authority/ordering and chained-detach cases remain retained; they do not establish equivalent coverage for the removed examples. Historical commands, counts, results, and red-green narratives remain historical. The test-value audit retires terminals-explicit-empty-hydration.test.ts in full: its direct git/folder empty-tombstone assertions and literal-flag auto-create helper check are lost. The store test never mounted the initial-terminal effect or performed a persisted restart. The audit also removes terminal-tab-retirement.test.ts pure ownership/alias/routing plan inventories and sleeping-record map assertions; its former 100-tab scan-count case was subsequently retired too; no assertion remains in that suite. These retained and historical cases do not establish equivalent tombstone, default-create, provider teardown, cross-platform, or mobile coverage. Historical commands, results, counts, and red-green narratives remain historical. The subsequent test-value audit deletes the remaining terminal-tab-retirement.test.ts suite. Its 100-tab case asserted only returned plan count and one outer scan per ownership store; it never inspected per-tab plans or provider teardown. Those direct cardinality/work-count alarms are intentionally lost. Historical executed commands, results, counts and red-green narratives remain historical; no equivalent replacement or new runtime, platform or mobile evidence is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1392: src/main/agent-hooks/server-pane-authority.test.ts reduced. Retires one duplicate-transfer no-op listener count and latest pty/timestamp callback fixture. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Live macOS Electron tests prove exact local PTY disappearance after parked-tab close and detached-pgid descendant death after agent close. A deterministic final-pane interleaving now proves durable tab retirement commits before externally owned PTY teardown can publish graph loss, and preserves an unrelated live canary through duplicate exit retirement. Deterministic tests also cover final-pane CLI close durability and same-incarnation handle continuity; persisted-empty restart suppression remains historical Electron evidence, alongside replacement and hard graph-loss stale fencing, preallocated-handle supersession, daemon and SSH routing, local/daemon pending-snapshot ownership across natural exit, stale-root descendant-signal suppression, graceful-to-immediate kill upgrades, duplicate-kill completion sharing, locale-stable bounded/fresh/coalesced process-table reads, deadline-safe successor scans, cycle-safe linear descendant traversal, target-only escalation indexing, 32-wide bulk teardown, source-scan timestamp identity, same-second PID ambiguity, ordinary runtime close ownership, unified-only hydration, split ownership, pane detach transfer, restart alias hydration, and late-hook suppression; live Linux, Windows, WSL, SSH, and remote-runtime process evidence remains pending. A paired macOS Electron journey (real attached-window desktop host plus a separate real paired desktop client, isolated profiles) covers the inverse authority direction for host-created terminals: a renderer graph sync must not retire a tab that `orca terminal create` made. The retained paired journey covers the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId. The repeated target-after-unrelated-terminal journey was retired; its separate ordering alarm is no longer provided. An earlier reading of this gate called a preceding host-created terminal and a `clientMutationId` protective; main-process instrumentation refuted that. The renderer's stale session write deleted the host tab from persistence in every variant, and only the delete's timing relative to the measured sync differed, so those rows were false negatives of a single-sync oracle. The defect was in persistence: persistPtyBinding did not raise the repo's terminal topology fence for the first host-admitted tab, leaving the renderer's pre-create tab list free to replay over it. Elapsed time and paired-client mirroring never decided anything. A windowless `orca serve` parity arm runs the identical oracle and passes on both the merge-base and the branch, confirming that topology does not exhibit the defect (the gate it turns on is window-conditioned) and that making the host binding unconditional did not regress it. All of this is macOS-local only. The reported incident occurred on a physical Windows host; we did not run against one. The claim that the mechanism is platform-independent rests on the authoritative-window gate and publication-epoch inheritance being OS-agnostic, not on Windows evidence, so no ConPTY, Windows window-lifecycle, update, or sleep behavior is covered here. The synthetic default-tabs unit suite was retired: its explicit-empty/default-tab assertions no longer supply unit evidence. This retirement supplies no new persisted-restart, runtime-routing, cross-platform, or mobile evidence; existing historical runs and counts remain historical. The test-value audit removes the isolated re-retirement-token/epoch, activity-cutoff, idle-reattach and sibling-restore examples. The cited exact retirement and chained-detach cases remain unchanged, alongside closed-tab revival fencing and alias churn bounds. Their retained evidence is not equivalent coverage for every removed permutation; historical execution evidence is unchanged. The test-value audit removed shared-owner snapshot/cold-restore reference examples, a direct absent-tab PTY-index update, caller-supplied host-owned teardown boolean/no-dispatch, and a single local-provider rejection example. It also removed hand-built detach-retention comparator examples for different runs, handles, provider identities, and handle-less rows without independent identity ingress. Their specific snapshot, missing-tab, host-decision, rejection-count, and comparator alarms are lost. Current exact authority/ordering and chained-detach cases remain retained; they do not establish equivalent coverage for the removed examples. Historical commands, counts, results, and red-green narratives remain historical. The test-value audit retires terminals-explicit-empty-hydration.test.ts in full: its direct git/folder empty-tombstone assertions and literal-flag auto-create helper check are lost. The store test never mounted the initial-terminal effect or performed a persisted restart. The audit also removes terminal-tab-retirement.test.ts pure ownership/alias/routing plan inventories and sleeping-record map assertions; its former 100-tab scan-count case was subsequently retired too; no assertion remains in that suite. These retained and historical cases do not establish equivalent tombstone, default-create, provider teardown, cross-platform, or mobile coverage. Historical commands, results, counts, and red-green narratives remain historical. The subsequent test-value audit deletes the remaining terminal-tab-retirement.test.ts suite. Its 100-tab case asserted only returned plan count and one outer scan per ownership store; it never inspected per-tab plans or provider teardown. Those direct cardinality/work-count alarms are intentionally lost. Historical executed commands, results, counts and red-green narratives remain historical; no equivalent replacement or new runtime, platform or mobile evidence is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1392: src/main/agent-hooks/server-pane-authority.test.ts reduced. Retires one duplicate-transfer no-op listener count and latest pty/timestamp callback fixture. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4327", "https://github.com/stablyai/orca/pull/14590", @@ -6216,7 +6198,7 @@ "https://github.com/stablyai/orca/issues/14524" ], "invariant": "Close permanently removes the owned provider session, agent descendants, persisted tab/layout authority, and resume authority even when no TerminalPane is mounted; final-pane CLI close commits durable tab retirement before PTY stop can publish graph loss, does not acknowledge before that retirement, and treats the later exit retirement as idempotent. Workspace-wide CLI close applies that same durable contract to every terminal in exactly one worktree, including pinned and persisted-only surfaces, without touching sibling-worktree PTYs or resume records. A persisted explicit-empty state prevents initial-tab fallback from repopulating the workspace after reload or restart. A handle remains valid while the same provider-attested PTY incarnation survives renderer reload or re-key, and becomes stale without adopting a replacement incarnation. A terminating id remains reserved through natural exit, duplicate callers await the same completion, and immediate teardown upgrades any graceful request without signalling a recycled PID or a descendant tree after root ownership is lost; process-table work is locale-stable, bounded, fresh for each post-start request, same-turn coalesced, and begins within the requesting caller's deadline, including bulk worktree cleanup; detach and park preserve ownership; aliases prevent a detached agent's immutable physical pane key from being retired with its former tab.", - "oracle": "Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Capture exact tab, pane, PTY, handle, incarnation, and persisted layout identities. Final-pane terminal.close must invoke one durability-acknowledged tab retirement before exact PTY teardown; controlled PTY exit and graph removal afterward must remain idempotent, omit the target from persistence and provider inventory, and leave an unrelated canary handle live. terminal.closeAll must force-retire every pinned and unpinned target surface, clear its persisted agent-resume and incarnation records, await authoritative PTY exit, preserve a sibling worktree's tab, PTY, and resume authority, and return an unverifiable failure instead of claiming exit when the owning host does not confirm a stop. The ordinary path stays pending until the persisted row is removed and never falls back to the fire-and-forget pane event; reload/restart must keep the explicitly emptied worktree at zero terminal tabs and provider sessions. Reloading the renderer with the same tab/pane/PTY/incarnation must keep the handle readable; changing only the incarnation behind the same PTY id, losing the authoritative graph, or superseding the renderer handle with a preallocated handle must reject the old handle with terminal_handle_stale. Parked-close tests prove the exact PTY disappears; descendant/process tests keep natural exits reserved, upgrade teardown safely, bound/coalesce process-table work, and protect recycled identities.", + "oracle": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Capture exact tab, pane, PTY, handle, incarnation, and persisted layout identities. Final-pane terminal.close must invoke one durability-acknowledged tab retirement before exact PTY teardown; controlled PTY exit and graph removal afterward must remain idempotent, omit the target from persistence and provider inventory, and leave an unrelated canary handle live. terminal.closeAll must force-retire every pinned and unpinned target surface, clear its persisted agent-resume and incarnation records, await authoritative PTY exit, preserve a sibling worktree's tab, PTY, and resume authority, and return an unverifiable failure instead of claiming exit when the owning host does not confirm a stop. The ordinary path stays pending until the persisted row is removed and never falls back to the fire-and-forget pane event; reload/restart must keep the explicitly emptied worktree at zero terminal tabs and provider sessions. Reloading the renderer with the same tab/pane/PTY/incarnation must keep the handle readable; changing only the incarnation behind the same PTY id, losing the authoritative graph, or superseding the renderer handle with a preallocated handle must reject the old handle with terminal_handle_stale. Parked-close tests prove the exact PTY disappears; descendant/process tests keep natural exits reserved, upgrade teardown safely, bound/coalesce process-table work, and protect recycled identities.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts", @@ -6403,7 +6385,8 @@ "Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec'); await import('./orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec'); await import('./orca-runtime-tests/worktree-removal-execution-host.spec'); await import('./orca-runtime-tests/terminal-spawn-dispatch.spec'). src/main/runtime/orca-runtime-tests/headless-snapshots-part-02.spec.ts: replaces a cwd parsed before late WSL context with the provider cwd; keeps a live WSL cwd that arrives during late-context snapshot recovery; infers local reconstructed WSL context from a WSL UNC worktree; clears stale terminal file URI hostnames after empty-host OSC7 cwd updates; serializes SSH headless OSC7 cwd as POSIX when the desktop runtime is on Windows; keeps Windows SSH OSC7 cwd as a drive path when the desktop runtime is POSIX; serializes Windows SSH headless OSC7 cwd as a drive path on POSIX desktops; infers restored SSH connection identity from app-scoped PTY ids. src/main/runtime/orca-runtime-tests/mobile-session-tabs-headless-chat-rebuild.spec.ts: survives the rebuild that closing a saved editor tab forces; keeps its place in the tab order when the host lists the workspace again; lists tabs to phones in the order desktop clients draw after a rebuild; keeps the place a window gave a chat across a graph resend before the chat is restored. src/main/runtime/orca-runtime-tests/mobile-session-tabs-cold-serve-hydrate.spec.ts: lists every persisted terminal of a windowless host after a cold restart; lists every persisted terminal in the all-worktrees inventory after a cold restart; lists persisted editor tabs beside the terminals after a cold restart; restores a persisted split group layout on the cold rebuild; restores the saved active group of a split even when it is not the first group; falls back to the active tab group when the saved active group was not restored; keeps the headless group active when there is no persisted split; keeps phone and CLI creates in the group they joined across a cold restart. src/main/runtime/orca-runtime-tests/worktree-removal-failed-retry.spec.ts: lists the leftover with its error, though Git no longer does; takes the normal delete once Git registers a checkout at the path again; joins a retry another client started while this Delete listed Git; shows the failed row with its error, not the scan cached before the delete. src/main/runtime/orca-runtime-tests/worktree-removal-execution-host.spec.ts: refuses an SSH row whose host is unreachable instead of deleting here; refuses a runtime row with no nested SSH target rather than deleting locally; refuses a runtime row that also names a nested SSH target; retains runtime purge dispatch in a recovery job; uses the runtime helper override before resuming an interrupted removal; uses the runtime helper override before retrying a failed removal; captures the watcher callback and retains its job-host receiver; reads the current runtime removal queue. src/main/runtime/orca-runtime-tests/terminal-spawn-dispatch.spec.ts: reports the spawn request before it leaves for the pty controller; reports it even when the spawn itself then fails; does not report it when the create fails before any spawn request; captures the admission method before reading the incarnation; captures the record method before evaluating its state object; skips database payload serialization when no database exists; skips a throwing database payload when no database exists; keeps the database method and receiver captured before its payload; captures the canonical map method before a binding getter changes it; completes the captured replacement fence without another map lookup. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed.", "Module layout policy correction: retire the remaining program-status-osc.spec.ts event-projection case (production/mock-derived pane-key oracle) and sign-in timeout case (real setTimeout wait with Date-only fake clocks). The runtime test registrar no longer imports that file. No replacement coverage or fresh execution is claimed for these losses; historical receipts retain their original source scope.", "Module layout policy correction: retire the two remaining worktree-ps-agent-row-dismissal.spec.ts registrations. The remint/dismissal/exit case computed expected snapshotVersion increments from a production snapshot and used real-clock vi.waitFor; the legacy OSC case derived its expected paneKey from the production layout-owner switch. The runtime registrar no longer imports this file. These public projection scenarios have no replacement coverage or fresh execution claimed; all historical receipts and earlier loss notes retain their original source scope.", - "Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed." + "Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed.", + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged." ], "demotionRule": "Keep experimental or demote to protection none if exact PTY disappearance flakes, a sibling/detached pane is retired, late hooks can recreate closed authority, or a renderer graph sync retires a host-created tab that no explicit close retired." }, @@ -6425,7 +6408,7 @@ "providers": ["daemon", "runtime", "ssh", "wsl"], "coveredPlatforms": ["linux", "macos", "windows"], "coveredProviders": ["daemon", "runtime"], - "coverageNotes": "Audit2153: Reduced sources intentionally lose the forwarding smoke and retire an unrelated current selector; historical runs do not validate changed source bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: The CLI WebSocket source retains old-protocol refusal only; its paired-open, capability, timeout and admission projection examples are removed. No daemon-generation coverage is transferred to that callback. Both independent daemon E2E receipts remain unchanged at their original commands; the reduced unit selector has no fresh result. Historical prior account (preserved verbatim): Audit1983: Delete the reasonless-close scalar suite and optional-capability socket forwarding alias. Delete the mocked close-attribution topology field-inventory suite and its aliases/selectors; preserve independent dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1957:11, 1957:35, 1957:36): The fixture-supplied repository roundtrip, isolated capability metadata readback, parser/default-timer/size-threshold/internal failure-counter examples and standalone handshake-only replay example are removed. Source11 retains real encrypted multi-client event ordering, reconnect snapshot and multiplex delivery under synthetic runtime state, and does not establish the broad handshake-to-reasonless-close refusal alias; retire that whole assertion object. Source36 capability metadata readback alias is retired. Source35 retains the actual v2 runtime-only metadata/downgrade refusal callback and captured mutating-trace fresh-nonce rejection; its mapped mobile-v2 refusal alias remains within modeled credential lookup scope. Both independent daemon E2E dated receipts remain byte-exact with their original commands and results. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Retain actual parked exit/disposal/cancel/leaf progression using injected exit and close adapters. The retained last-watcher case checks exact lifecyclePtyId, but no retained callback establishes the whole existing replacement-or-sibling-incarnation alias. Retire that broad assertion object rather than transfer partial support. Capability admission, static fields and duplicate routing examples are intentionally lost; unchanged daemon E2E receipts remain scoped to their own commands. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): The browser auth capability-advertisement case is removed in this audit; its direct encrypted-auth literal alarm is lost. Retained lifecycle evidence is not an equivalent replacement. Historical run commands and results remain historical. Recorded native Windows evidence covers the v21/v22/v23/v24/v25 named-pipe matrix. The deterministic daemon harness covers capable and legacy paired-runtime request shapes against live v25/v26 PTYs in separate worktrees, plus an unrelated control. Host/renderer tests cover old servers, missing liveness, stale publications, reused claims, split parents, explicit user intent, cross-profile isolation, remote runtime clients, SSH-provider routing, and WSL boundaries. A headed host paired to a separate live client, headless serve parity, Linux, SSH, and WSL remain explicit gaps. The audit removed private-router tests of mocked kill results and log fields. Their isolated success/failure attribution and pending-spawn tolerance alarms are no longer registered here; live lifecycle evidence does not establish equivalent log coverage. The isolated close-intent suite was removed. web-runtime-session.test.ts no longer supplies the lifecycle-close or old-server method-not-found assertions formerly referenced here. Their direct partition and RPC-shape alarms are lost; retained live daemon evidence does not establish equivalent coverage. The broad mirror fixture retains user-close suppression, refused-close reconciliation and optimistic reorder only. Its earlier reconnect/incarnation and projection examples no longer establish current daemon-generation coverage. Those narrow alarms are lost; other daemon evidence is not equivalent replacement coverage. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2153: Reduced sources intentionally lose the forwarding smoke and retire an unrelated current selector; historical runs do not validate changed source bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: The CLI WebSocket source retains old-protocol refusal only; its paired-open, capability, timeout and admission projection examples are removed. No daemon-generation coverage is transferred to that callback. Both independent daemon E2E receipts remain unchanged at their original commands; the reduced unit selector has no fresh result. Historical prior account (preserved verbatim): Audit1983: Delete the reasonless-close scalar suite and optional-capability socket forwarding alias. Delete the mocked close-attribution topology field-inventory suite and its aliases/selectors; preserve independent dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1957:11, 1957:35, 1957:36): The fixture-supplied repository roundtrip, isolated capability metadata readback, parser/default-timer/size-threshold/internal failure-counter examples and standalone handshake-only replay example are removed. Source11 retains real encrypted multi-client event ordering, reconnect snapshot and multiplex delivery under synthetic runtime state, and does not establish the broad handshake-to-reasonless-close refusal alias; retire that whole assertion object. Source36 capability metadata readback alias is retired. Source35 retains the actual v2 runtime-only metadata/downgrade refusal callback and captured mutating-trace fresh-nonce rejection; its mapped mobile-v2 refusal alias remains within modeled credential lookup scope. Both independent daemon E2E dated receipts remain byte-exact with their original commands and results. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Retain actual parked exit/disposal/cancel/leaf progression using injected exit and close adapters. The retained last-watcher case checks exact lifecyclePtyId, but no retained callback establishes the whole existing replacement-or-sibling-incarnation alias. Retire that broad assertion object rather than transfer partial support. Capability admission, static fields and duplicate routing examples are intentionally lost; unchanged daemon E2E receipts remain scoped to their own commands. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): The browser auth capability-advertisement case is removed in this audit; its direct encrypted-auth literal alarm is lost. Retained lifecycle evidence is not an equivalent replacement. Historical run commands and results remain historical. Recorded native Windows evidence covers the v21/v22/v23/v24/v25 named-pipe matrix. The deterministic daemon harness covers capable and legacy paired-runtime request shapes against live v25/v26 PTYs in separate worktrees, plus an unrelated control. Host/renderer tests cover old servers, missing liveness, stale publications, reused claims, split parents, explicit user intent, cross-profile isolation, remote runtime clients, SSH-provider routing, and WSL boundaries. A headed host paired to a separate live client, headless serve parity, Linux, SSH, and WSL remain explicit gaps. The audit removed private-router tests of mocked kill results and log fields. Their isolated success/failure attribution and pending-spawn tolerance alarms are no longer registered here; live lifecycle evidence does not establish equivalent log coverage. The isolated close-intent suite was removed. web-runtime-session.test.ts no longer supplies the lifecycle-close or old-server method-not-found assertions formerly referenced here. Their direct partition and RPC-shape alarms are lost; retained live daemon evidence does not establish equivalent coverage. The broad mirror fixture retains user-close suppression, refused-close reconciliation and optimistic reorder only. Its earlier reconnect/incarnation and projection examples no longer establish current daemon-generation coverage. Those narrow alarms are lost; other daemon evidence is not equivalent replacement coverage. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/9749", "https://github.com/stablyai/orca/issues/9949", @@ -6434,7 +6417,7 @@ "https://github.com/stablyai/orca/issues/9229" ], "invariant": "Reconnect, replay, or lifecycle observations from a viewer that negotiated explicit close intent must never kill a live PTY. A capable reasonless close must keep and republish; a legacy paired viewer must retain current-main behavior because its intentional close and cleanup echo are wire-identical. Lifecycle close requires the exact observed publication, terminal, environment, and authoritative liveness, never signals a process, and leaves renderer-owned or partial-split retirement to its owner. Legacy daemon hello and warm reattachment remain non-destructive.", - "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1983: Delete the reasonless-close scalar suite and optional-capability socket forwarding alias. Delete the mocked close-attribution topology field-inventory suite and its aliases/selectors; preserve independent dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1957:11, 1957:35, 1957:36): The fixture-supplied repository roundtrip, isolated capability metadata readback, parser/default-timer/size-threshold/internal failure-counter examples and standalone handshake-only replay example are removed. Source11 retains real encrypted multi-client event ordering, reconnect snapshot and multiplex delivery under synthetic runtime state, and does not establish the broad handshake-to-reasonless-close refusal alias; retire that whole assertion object. Source36 capability metadata readback alias is retired. Source35 retains the actual v2 runtime-only metadata/downgrade refusal callback and captured mutating-trace fresh-nonce rejection; its mapped mobile-v2 refusal alias remains within modeled credential lookup scope. Both independent daemon E2E dated receipts remain byte-exact with their original commands and results. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Retain actual parked exit/disposal/cancel/leaf progression using injected exit and close adapters. The retained last-watcher case checks exact lifecyclePtyId, but no retained callback establishes the whole existing replacement-or-sibling-incarnation alias. Retire that broad assertion object rather than transfer partial support. Capability admission, static fields and duplicate routing examples are intentionally lost; unchanged daemon E2E receipts remain scoped to their own commands. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Start isolated v25 and v26 daemon generations with one capable-viewer PTY and one legacy-viewer PTY per generation in four target worktrees plus an unaddressed control PTY in a fifth worktree. Route them through the production desktop scanner, runtime, RPC dispatcher, renderer-close relay, and daemon router. First issue sequential reasonless closes from an authenticated capable connection and require refusal, snapshot republish, zero shutdown calls, exact process survival, and post-close I/O. Then issue the byte-identical requests without the negotiated capability and require current-main behavior: two ordered immediate shutdowns, session-killed events, and exact root/descendant death, while capable and control PTYs survive. An observer lists all targets before, between, and after while issuing zero closes. Unit contracts also require in-process reasonless refusal, legacy runtime/mobile compatibility, explicit user closes, encrypted client-auth advertisement, and old-server lifecycle calls never to fall back.", + "oracle": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1983: Delete the reasonless-close scalar suite and optional-capability socket forwarding alias. Delete the mocked close-attribution topology field-inventory suite and its aliases/selectors; preserve independent dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1957:11, 1957:35, 1957:36): The fixture-supplied repository roundtrip, isolated capability metadata readback, parser/default-timer/size-threshold/internal failure-counter examples and standalone handshake-only replay example are removed. Source11 retains real encrypted multi-client event ordering, reconnect snapshot and multiplex delivery under synthetic runtime state, and does not establish the broad handshake-to-reasonless-close refusal alias; retire that whole assertion object. Source36 capability metadata readback alias is retired. Source35 retains the actual v2 runtime-only metadata/downgrade refusal callback and captured mutating-trace fresh-nonce rejection; its mapped mobile-v2 refusal alias remains within modeled credential lookup scope. Both independent daemon E2E dated receipts remain byte-exact with their original commands and results. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Retain actual parked exit/disposal/cancel/leaf progression using injected exit and close adapters. The retained last-watcher case checks exact lifecyclePtyId, but no retained callback establishes the whole existing replacement-or-sibling-incarnation alias. Retire that broad assertion object rather than transfer partial support. Capability admission, static fields and duplicate routing examples are intentionally lost; unchanged daemon E2E receipts remain scoped to their own commands. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Start isolated v25 and v26 daemon generations with one capable-viewer PTY and one legacy-viewer PTY per generation in four target worktrees plus an unaddressed control PTY in a fifth worktree. Route them through the production desktop scanner, runtime, RPC dispatcher, renderer-close relay, and daemon router. First issue sequential reasonless closes from an authenticated capable connection and require refusal, snapshot republish, zero shutdown calls, exact process survival, and post-close I/O. Then issue the byte-identical requests without the negotiated capability and require current-main behavior: two ordered immediate shutdowns, session-killed events, and exact root/descendant death, while capable and control PTYs survive. An observer lists all targets before, between, and after while issuing zero closes. Unit contracts also require in-process reasonless refusal, legacy runtime/mobile compatibility, explicit user closes, encrypted client-auth advertisement, and old-server lifecycle calls never to fall back.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/e2ee-channel.test.ts src/main/runtime/rpc/e2ee-channel-v2.test.ts src/main/runtime/rpc/mobile-socket-wiring.test.ts src/main/runtime/rpc/runtime-client-capabilities.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/requests/remote-runtime-request-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/cli/runtime/websocket-transport.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/components/terminal/terminal-tab-actions.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts", "pnpm exec playwright test tests/e2e/daemon-generation-reconnect-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", @@ -6584,7 +6567,8 @@ "Audit2153: Intentionally retire the ordinary fake-create event-forwarding registration from src/main/runtime/rpc/server/remote-runtime-request-connection.integration.test.ts. The two retained callbacks prove encrypted fanout/reconnect and physical connection multiplexing under a fake business runtime; neither establishes close-intent authorization, actual terminal sleep, or equivalent replacement for the removed forwarding smoke. Remove this unrelated current close-safety selector. Existing assertionRefs and dated evidenceRuns remain byte-identical and scoped to their own source/commands. No fresh execution or platform/provider coverage is claimed.", "Audit2153 historical original commands item, preserved verbatim; retired selector is not active execution evidence: \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/server/remote-runtime-request-connection.integration.test.ts src/main/runtime/rpc/e2ee-channel.test.ts src/main/runtime/rpc/e2ee-channel-v2.test.ts src/main/runtime/rpc/mobile-socket-wiring.test.ts src/main/runtime/rpc/runtime-client-capabilities.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/requests/remote-runtime-request-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/cli/runtime/websocket-transport.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/components/terminal/terminal-tab-actions.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts\"", "Audit2153 historical original testFiles item, preserved verbatim; retired selector is not active execution evidence: \"src/main/runtime/rpc/server/remote-runtime-request-connection.integration.test.ts\"", - "Terminal/runtime defining-owner cleanup retires complete parking timer, lifecycle, mocked close/disposal and render/flip/mount work-count cases under repository test policy. The retained watcher source has only two literal-oracle coverage decisions; the retained cold-parking hook source has only the layout-PTY exemption invalidation case. Lost alarms include cooldown/measure/pin wakeups, split exit/close attribution and cancellation, watcher disposal/restart, flood timer rearm, worktree verdict damping, and destroyed-transport cold restore. No equivalent replacement coverage or execution pass for the reduced cases is claimed; prior dated receipts retain their original scope." + "Terminal/runtime defining-owner cleanup retires complete parking timer, lifecycle, mocked close/disposal and render/flip/mount work-count cases under repository test policy. The retained watcher source has only two literal-oracle coverage decisions; the retained cold-parking hook source has only the layout-PTY exemption invalidation case. Lost alarms include cooldown/measure/pin wakeups, split exit/close attribution and cancellation, watcher disposal/restart, flood timer rearm, worktree verdict damping, and destroyed-transport cold restore. No equivalent replacement coverage or execution pass for the reduced cases is claimed; prior dated receipts retain their original scope.", + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged." ], "demotionRule": "Keep experimental or quarantine if reconnect emits session-killed for a live canary, an exact root/descendant dies, an old server receives fallback destructive close, cleanup leaks a fixture process/pipe, or the gate flakes without a proven harness defect." }, @@ -6807,16 +6791,15 @@ "providers": ["local", "wsl", "ssh", "remote-runtime"], "coveredPlatforms": ["windows"], "coveredProviders": [], - "coverageNotes": "Audit2371 reduces repos-project-group-create-race.test.ts by removing the two-host generic failed-create-response/no-op example. Its alarm that a failed create reply leaves an intervening refreshed state untouched is intentionally lost. The surviving refreshed-field and original-owner races do not supply equivalent replacement coverage. No fresh execution or red/green evidence validates the reduced source; unrelated physical Windows/WSL receipt retains its original command and scope. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1396 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A deterministic Windows-mode renderer oracle keeps an active WSL project and explicit-local Floating Workspace mounted together with disjoint agent inventories, then independently asserts discovery and launch authority. A headed physical Windows 2 journey with real Ubuntu WSL2 independently verified the rendered inventory and native PowerShell launch; SSH and paired-runtime behavior retain their existing contract coverage. The test-value audit removes standalone WSL/provider argument inventories and basic supplied-result/cache-clear examples from detected-agents.test.ts. It retains shared in-flight detection, cached-context return, repair/retry, stale-response fencing, SSH refresh/pruning and old-server fallback behavior. These retained tests do not replace the removed route-argument alarms or execute a live WSL/remote probe. Historical commands, counts and results remain unchanged. The later test-value audit removes narrow refusal/reset ledgers, a settled-project eviction/reacquisition example, a simple stale-success variant and redundant plain-text draft cleanup examples. local-detected-agent-state retains independent inventory completion orders, preference-change fencing, full-refresh loading settlement, refresh failure/retry, native-versus-WSL separation, subscriber broadcast bounds and in-flight project eviction. The removed settled-context sibling-preservation/reacquisition alarm is intentionally lost; retained cases are not equivalent replacements and no live provider execution is claimed. Historical commands, counts and results remain unchanged. The test-value audit retires the standalone project-runtime registrar from repos-project-mutations.test.ts. Its updateProject runtime-preference example no longer checks clearing detectedAgentIds, isDetectingAgents and isRefreshingAgents or dispatch of orca:installed-agent-skills-changed. This narrow invalidation alarm is lost; no equivalent replacement is claimed. Historical executed commands, counts and results remain unchanged. Audit1342: src/renderer/src/hooks/useAgentDetectionTarget.test.ts removed. Floating/runtime/hydration/stamped owner key selection, scanning count and malformed decode fallback matrices disappear. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2371 reduces repos-project-group-create-race.test.ts by removing the two-host generic failed-create-response/no-op example. Its alarm that a failed create reply leaves an intervening refreshed state untouched is intentionally lost. The surviving refreshed-field and original-owner races do not supply equivalent replacement coverage. No fresh execution or red/green evidence validates the reduced source; unrelated physical Windows/WSL receipt retains its original command and scope. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1396 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A deterministic Windows-mode renderer oracle keeps an active WSL project and explicit-local Floating Workspace mounted together with disjoint agent inventories, then independently asserts discovery and launch authority. A headed physical Windows 2 journey with real Ubuntu WSL2 independently verified the rendered inventory and native PowerShell launch; SSH and paired-runtime behavior retain their existing contract coverage. The test-value audit removes standalone WSL/provider argument inventories and basic supplied-result/cache-clear examples from detected-agents.test.ts. It retains shared in-flight detection, cached-context return, repair/retry, stale-response fencing, SSH refresh/pruning and old-server fallback behavior. These retained tests do not replace the removed route-argument alarms or execute a live WSL/remote probe. Historical commands, counts and results remain unchanged. The later test-value audit removes narrow refusal/reset ledgers, a settled-project eviction/reacquisition example, a simple stale-success variant and redundant plain-text draft cleanup examples. local-detected-agent-state retains independent inventory completion orders, preference-change fencing, full-refresh loading settlement, refresh failure/retry, native-versus-WSL separation, subscriber broadcast bounds and in-flight project eviction. The removed settled-context sibling-preservation/reacquisition alarm is intentionally lost; retained cases are not equivalent replacements and no live provider execution is claimed. Historical commands, counts and results remain unchanged. The test-value audit retires the standalone project-runtime registrar from repos-project-mutations.test.ts. Its updateProject runtime-preference example no longer checks clearing detectedAgentIds, isDetectingAgents and isRefreshingAgents or dispatch of orca:installed-agent-skills-changed. This narrow invalidation alarm is lost; no equivalent replacement is claimed. Historical executed commands, counts and results remain unchanged. Audit1342: src/renderer/src/hooks/useAgentDetectionTarget.test.ts removed. Floating/runtime/hydration/stamped owner key selection, scanning count and malformed decode fallback matrices disappear. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4027/p1-floating-workspace-agent-detection-still-uses-active-wsl-project", "https://github.com/stablyai/orca/pull/13995" ], "invariant": "Every agent launch surface must advertise the provider set detected on its explicit execution authority and launch on that same authority; a local Floating Workspace must never inherit an unrelated active project's WSL, SSH, or paired-runtime context.", - "oracle": "Audit2371 reduces repos-project-group-create-race.test.ts by removing the two-host generic failed-create-response/no-op example. Its alarm that a failed create reply leaves an intervening refreshed state untouched is intentionally lost. The surviving refreshed-field and original-owner races do not supply equivalent replacement coverage. No fresh execution or red/green evidence validates the reduced source; unrelated physical Windows/WSL receipt retains its original command and scope. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Model an active WSL project and a native-Windows Floating Workspace with WSL-only Claude and host-only Codex. Keep both detection consumers mounted, require their advertised sets to stay disjoint through refresh, require the legacy active-project inventory to remain unchanged, then independently assert the Floating launch call and PTY transport select local IPC with no WSL project runtime.", + "oracle": "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2371 reduces repos-project-group-create-race.test.ts by removing the two-host generic failed-create-response/no-op example. Its alarm that a failed create reply leaves an intervening refreshed state untouched is intentionally lost. The surviving refreshed-field and original-owner races do not supply equivalent replacement coverage. No fresh execution or red/green evidence validates the reduced source; unrelated physical Windows/WSL receipt retains its original command and scope. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Model an active WSL project and a native-Windows Floating Workspace with WSL-only Claude and host-only Codex. Keep both detection consumers mounted, require their advertised sets to stay disjoint through refresh, require the legacy active-project inventory to remain unchanged, then independently assert the Floating launch call and PTY transport select local IPC with no WSL project runtime.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/useDetectedAgents.test.tsx src/renderer/src/store/slices/agent-inventory/detected-agents.test.ts src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.test.ts src/renderer/src/store/project-groups/repos-project-group-create-race.test.ts src/renderer/src/store/project-groups/repos-project-groups-delete.test.ts src/renderer/src/store/project-groups/repos-project-groups-owner-routing.test.ts src/renderer/src/store/projects/repos-project-host-capability.test.ts src/renderer/src/store/projects/repos-project-host-lifecycle.test.ts src/renderer/src/store/repos/repos-remove-project-purge-leak.test.ts src/renderer/src/store/repos/repos-update-serialization.test.ts src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab.test.ts --reporter=verbose", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/useDetectedAgents.test.tsx src/renderer/src/store/slices/agent-inventory/detected-agents.test.ts src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.test.ts src/renderer/src/store/project-groups/repos-project-group-create-race.test.ts src/renderer/src/store/project-groups/repos-project-groups-delete.test.ts src/renderer/src/store/project-groups/repos-project-groups-owner-routing.test.ts src/renderer/src/store/projects/repos-project-host-capability.test.ts src/renderer/src/store/projects/repos-project-host-lifecycle.test.ts src/renderer/src/store/repos/repos-remove-project-purge-leak.test.ts src/renderer/src/store/repos/repos-update-serialization.test.ts --reporter=verbose", "Headed Electron/CDP STA-4027 journey on Orca environment windows 2 with a selected Ubuntu-24.04 WSL project and local Floating Workspace" ], "testFiles": [ @@ -6829,9 +6812,7 @@ "src/renderer/src/store/projects/repos-project-host-capability.test.ts", "src/renderer/src/store/projects/repos-project-host-lifecycle.test.ts", "src/renderer/src/store/repos/repos-remove-project-purge-leak.test.ts", - "src/renderer/src/store/repos/repos-update-serialization.test.ts", - "src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab.test.ts", - "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts" + "src/renderer/src/store/repos/repos-update-serialization.test.ts" ], "assertionRefs": [ { @@ -6854,12 +6835,6 @@ "assertions": [ "removing one project evicts its authority-scoped agent inventory without disturbing another project" ] - }, - { - "file": "src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab.test.ts", - "assertions": [ - "the advertised Floating agent launches in a Floating tab with null runtime ownership and no paired-runtime create call" - ] } ], "evidenceRuns": [ @@ -6913,7 +6888,9 @@ "Audit1396 retires this complete dated receipt because a source in its selector was deleted or reduced. It does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-08-12\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection-fresh-spawn-guards.test.ts --reporter=dot\",\n \"result\": \"passed\",\n \"durationSeconds\": 20,\n \"summary\": \"The full PTY connection suite passed the independent Floating native-host transport oracle.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection-spawn-and-startup.test.ts --reporter=dot\"\n }", "Audit1396 historical platform/provider scope before source changes: {\"coveredPlatforms\":[\"macos\",\"windows\"],\"coveredProviders\":[\"local\",\"wsl\"]}. Remaining provider scope applies only to unchanged-source receipts.", "Audit2371 reduces repos-project-group-create-race.test.ts by removing the two-host generic failed-create-response/no-op example. Its alarm that a failed create reply leaves an intervening refreshed state untouched is intentionally lost. The surviving refreshed-field and original-owner races do not supply equivalent replacement coverage. No fresh execution or red/green evidence validates the reduced source; unrelated physical Windows/WSL receipt retains its original command and scope.", - "Finite R02 ownership closure retires all three cases from pty-connection/spawn/pty-connection-fresh-spawn-guards.spec.ts and its empty aggregate registration. Intentionally lost alarms: deletion-phase fresh-spawn admission; wrapped worktree-removal fence error suppression; classified typing versus synthetic query/mouse/alternate-wheel replay input, normal-arrow preservation, deferred input provenance and post-replay restoration. No equivalent replacement coverage, new execution, real PTY delivery or CI claim. Historical receipts and their original commands/counts/results remain historical and do not validate the reduced selector." + "Finite R02 ownership closure retires all three cases from pty-connection/spawn/pty-connection-fresh-spawn-guards.spec.ts and its empty aggregate registration. Intentionally lost alarms: deletion-phase fresh-spawn admission; wrapped worktree-removal fence error suppression; classified typing versus synthetic query/mouse/alternate-wheel replay input, normal-arrow preservation, deferred input provenance and post-replay restoration. No equivalent replacement coverage, new execution, real PTY delivery or CI claim. Historical receipts and their original commands/counts/results remain historical and do not validate the reduced selector.", + "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/useDetectedAgents.test.tsx src/renderer/src/store/slices/agent-inventory/detected-agents.test.ts src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.test.ts src/renderer/src/store/project-groups/repos-project-group-create-race.test.ts src/renderer/src/store/project-groups/repos-project-groups-delete.test.ts src/renderer/src/store/project-groups/repos-project-groups-owner-routing.test.ts src/renderer/src/store/projects/repos-project-host-capability.test.ts src/renderer/src/store/projects/repos-project-host-lifecycle.test.ts src/renderer/src/store/repos/repos-remove-project-purge-leak.test.ts src/renderer/src/store/repos/repos-update-serialization.test.ts src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab.test.ts --reporter=verbose\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts --reporter=dot\",\n \"Headed Electron/CDP STA-4027 journey on Orca environment windows 2 with a selected Ubuntu-24.04 WSL project and local Floating Workspace\"\n ]\ntestFiles: [\n \"src/renderer/src/hooks/useDetectedAgents.test.tsx\",\n \"src/renderer/src/store/slices/agent-inventory/detected-agents.test.ts\",\n \"src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.test.ts\",\n \"src/renderer/src/store/project-groups/repos-project-group-create-race.test.ts\",\n \"src/renderer/src/store/project-groups/repos-project-groups-delete.test.ts\",\n \"src/renderer/src/store/project-groups/repos-project-groups-owner-routing.test.ts\",\n \"src/renderer/src/store/projects/repos-project-host-capability.test.ts\",\n \"src/renderer/src/store/projects/repos-project-host-lifecycle.test.ts\",\n \"src/renderer/src/store/repos/repos-remove-project-purge-leak.test.ts\",\n \"src/renderer/src/store/repos/repos-update-serialization.test.ts\",\n \"src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/hooks/useDetectedAgents.test.tsx\",\n \"assertions\": [\n \"the active WSL project advertises only its WSL agent while Floating advertises only the native-host agent\",\n \"Floating refresh preserves both scoped inventories and does not overwrite the legacy active-project inventory\"\n ]\n },\n {\n \"file\": \"src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.test.ts\",\n \"assertions\": [\n \"same-context callers deduplicate without cached broadcast fanout\",\n \"refresh supersedes stale detection and failed cold refresh remains retryable\",\n \"project removal evicts in-flight context state\"\n ]\n },\n {\n \"file\": \"src/renderer/src/store/repos/repos-remove-project-purge-leak.test.ts\",\n \"assertions\": [\n \"removing one project evicts its authority-scoped agent inventory without disturbing another project\"\n ]\n },\n {\n \"file\": \"src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab.test.ts\",\n \"assertions\": [\n \"the advertised Floating agent launches in a Floating tab with null runtime ownership and no paired-runtime create call\"\n ]\n }\n ]", + "Renderer direct-owner cleanup retires the complete launch-agent-in-new-tab suite (six registrations/ten examples). Lost alarms cover child cwd/trust scope, captured host/selection ownership and creation settlement, precreation refusal, canonical args/model fallback, oversized Windows draft paste, and late-SSH status fencing. Owning private capability fixture state was consumed. No equivalent replacement, fresh execution, native process/provider, rendered UI, performance, or cross-platform result is claimed. Other source mappings and the existing independent manual Windows receipt keep their prior scope; retained shortcut/SourceControl/continuation cases do not replace these alarms. Historical removed active mappings (verbatim semantic values; no longer active): [{\"field\":\"testFiles\",\"previous\":[\"src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab.test.ts\"]},{\"field\":\"assertionRefs\",\"previous\":[{\"file\":\"src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab.test.ts\",\"assertions\":[\"the advertised Floating agent launches in a Floating tab with null runtime ownership and no paired-runtime create call\"]}]},{\"field\":\"commands\",\"previous\":[\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/useDetectedAgents.test.tsx src/renderer/src/store/slices/agent-inventory/detected-agents.test.ts src/renderer/src/store/slices/agent-inventory/local-detected-agent-state.test.ts src/renderer/src/store/project-groups/repos-project-group-create-race.test.ts src/renderer/src/store/project-groups/repos-project-groups-delete.test.ts src/renderer/src/store/project-groups/repos-project-groups-owner-routing.test.ts src/renderer/src/store/projects/repos-project-host-capability.test.ts src/renderer/src/store/projects/repos-project-host-lifecycle.test.ts src/renderer/src/store/repos/repos-remove-project-purge-leak.test.ts src/renderer/src/store/repos/repos-update-serialization.test.ts src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab.test.ts --reporter=verbose\"]}]" ], "demotionRule": "Demote if discovery and launch can resolve different authorities, a scoped Floating probe overwrites the active-project inventory, or local context selection adds recurring scans or retained in-flight entries." }, @@ -7097,7 +7074,7 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "daemon", "ssh", "wsl", "remote-runtime"], - "coverageNotes": "Audit3368 retires the whole host-session-launch unit source, including host-authority/create/ensure/legacy/Kimi/refusal/draft/options/prompt/cancel/kill/shared-disconnect and passive-sleep output callback alarms, without equivalent replacement. Its unit command token and test-file entry retire. Five unrelated macOS receipts remain verbatim and keep only their original scope; no fresh changed-selector/runtime/provider/process/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires the whole create-handoff suite. Supplied disposition, late completion, close-callback and metadata-bookkeeping alarms are intentionally lost without equivalent replacement; the compound unit selector and test-file entry narrow accordingly. Five unrelated macOS receipts retain their original scope. No fresh runtime, process-deduplication, physical provider/network, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1495 intentionally deletes the orphan-owner suite: explicit owner/host predicate examples are retired; no equivalent replacement coverage or fresh result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/agent-completion-coordinator-pending-title-inspection.test.ts: Loses obsolete pending title process races, inspection failure suppression, explicit completion precedence and delayed remote inspection alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audits1301 and1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic macOS tests cover controller claims, daemon and SSH/relay operation replay, mixed-version selection, runtime ownership, exact provisional handoff, durable terminal retirement, two independent viewer mirrors, guarded adoption of legacy live PTYs, and completion classification when either the outer remote transport or authoritative host/provider process inspection becomes unreachable. The adoption harness models v1.4.150 agent/setup/shell tabs, current-generation restart and reconnect, exact handle/incarnation/worktree/host checks, topology CAS, competing clients, split-pane/group restoration, WSL ownership, and SSH owner rejection. The secondary parity repro runs independent clients against one headless remote Orca runtime over encrypted pairing and a real daemon-backed PTY, with tokened fixture-process identity separated from unrelated Codex app-server startup probes. The automated primary topology runs an isolated headed macOS Orca desktop server plus a separate paired web client and proves viewer-local fresh/resume focus, exact legacy placement, writable PTYs, unrelated-terminal survival, and host/client cleanup. SSH coverage is provider/relay contract and fault-injection coverage only; it does not substitute for paired-server coverage. Live Windows, Linux, WSL, SSH, and physical paired-Linux hosts remain gaps. The isolated intent-owner ledger suite was removed. web-runtime-session.test.ts retains exact post-create handoff confirmation only; its previous fresh/resume presentation and publication-replay assertions are no longer current references. Those direct owner-partition, cap and RPC/focus alarms are lost; other agent-session evidence does not establish equivalence. Structured handoff and adopted-leaf focus references now point to their dedicated surviving fixtures. Mixed-version recovery retains actual old-host recovery followed by a new CLI tab; its unsupported/missing-evidence tables are removed. Orphan recovery retains in-flight adoption-conflict serialization only; previous topology/pruning and absence/adoption examples are removed. These removed projection, capability and adoption-shape alarms are lost; retained cases do not replace them. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1308: src/renderer/src/runtime/web-session-tabs-sync-agent-handoff.test.ts removed. Exact provisional replacement and post-create exit confirmation handoff pipeline alarms disappear. No equivalent replacement coverage is claimed. Audit1313: src/main/runtime/terminal-orphan-topology.test.ts: Retain actual topology merge algorithms preserving disjoint subtrees and grafted/ambiguous shared anchors with independent expected trees. Remove duplicate leaf validator and empty/no-change passthrough examples. Lose basic validation and no-group/noop characterization; no renderer layout proof. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3368 retires the whole host-session-launch unit source, including host-authority/create/ensure/legacy/Kimi/refusal/draft/options/prompt/cancel/kill/shared-disconnect and passive-sleep output callback alarms, without equivalent replacement. Its unit command token and test-file entry retire. Five unrelated macOS receipts remain verbatim and keep only their original scope; no fresh changed-selector/runtime/provider/process/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires the whole create-handoff suite. Supplied disposition, late completion, close-callback and metadata-bookkeeping alarms are intentionally lost without equivalent replacement; the compound unit selector and test-file entry narrow accordingly. Five unrelated macOS receipts retain their original scope. No fresh runtime, process-deduplication, physical provider/network, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1495 intentionally deletes the orphan-owner suite: explicit owner/host predicate examples are retired; no equivalent replacement coverage or fresh result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/agent-completion-coordinator-pending-title-inspection.test.ts: Loses obsolete pending title process races, inspection failure suppression, explicit completion precedence and delayed remote inspection alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audits1301 and1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic macOS tests cover controller claims, daemon and SSH/relay operation replay, mixed-version selection, runtime ownership, exact provisional handoff, durable terminal retirement, two independent viewer mirrors, guarded adoption of legacy live PTYs, and completion classification when either the outer remote transport or authoritative host/provider process inspection becomes unreachable. The adoption harness models v1.4.150 agent/setup/shell tabs, current-generation restart and reconnect, exact handle/incarnation/worktree/host checks, topology CAS, competing clients, split-pane/group restoration, WSL ownership, and SSH owner rejection. The secondary parity repro runs independent clients against one headless remote Orca runtime over encrypted pairing and a real daemon-backed PTY, with tokened fixture-process identity separated from unrelated Codex app-server startup probes. The automated primary topology runs an isolated headed macOS Orca desktop server plus a separate paired web client and proves viewer-local fresh/resume focus, exact legacy placement, writable PTYs, unrelated-terminal survival, and host/client cleanup. SSH coverage is provider/relay contract and fault-injection coverage only; it does not substitute for paired-server coverage. Live Windows, Linux, WSL, SSH, and physical paired-Linux hosts remain gaps. The isolated intent-owner ledger suite was removed. web-runtime-session.test.ts retains exact post-create handoff confirmation only; its previous fresh/resume presentation and publication-replay assertions are no longer current references. Those direct owner-partition, cap and RPC/focus alarms are lost; other agent-session evidence does not establish equivalence. Structured handoff and adopted-leaf focus references now point to their dedicated surviving fixtures. Mixed-version recovery retains actual old-host recovery followed by a new CLI tab; its unsupported/missing-evidence tables are removed. Orphan recovery retains in-flight adoption-conflict serialization only; previous topology/pruning and absence/adoption examples are removed. These removed projection, capability and adoption-shape alarms are lost; retained cases do not replace them. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1308: src/renderer/src/runtime/web-session-tabs-sync-agent-handoff.test.ts removed. Exact provisional replacement and post-create exit confirmation handoff pipeline alarms disappear. No equivalent replacement coverage is claimed. Audit1313: src/main/runtime/terminal-orphan-topology.test.ts: Retain actual topology merge algorithms preserving disjoint subtrees and grafted/ambiguous shared anchors with independent expected trees. Remove duplicate leaf validator and empty/no-change passthrough examples. Lose basic validation and no-group/noop characterization; no renderer layout proof. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/8878", "https://github.com/stablyai/orca/issues/9151", @@ -7107,7 +7084,7 @@ "https://github.com/stablyai/orca/pull/10193" ], "invariant": "For every claim-capable execution route, one provider-session identity has at most one live PTY owner and one canonical host surface across concurrent clients, retries, reconnects, and stale publications. For paired structured fresh and resume requests, the authenticated owning runtime creates in background without a renderer window; activate=true focuses the exact requested leaf only on the requesting viewer, while activate=false changes no viewer focus. A live orphan may be adopted only when the controller proves its exact handle and incarnation, its worktree and host owner match, no competing visual owner exists, and a host topology CAS wins. A viewer may classify completion only from successful host/provider inspection or explicit lifecycle evidence; transport, handle, or provider unavailability remains unknown and breaks any consecutive-idle proof. A physical exit retires that exact incarnation durably so stale client state and host restart cannot recreate it. Mixed-version routes select the unchanged legacy request before any authority side effect or execution-owner-local filesystem access.", - "oracle": "Audit3368 retires the whole host-session-launch unit source, including host-authority/create/ensure/legacy/Kimi/refusal/draft/options/prompt/cancel/kill/shared-disconnect and passive-sleep output callback alarms, without equivalent replacement. Its unit command token and test-file entry retire. Five unrelated macOS receipts remain verbatim and keep only their original scope; no fresh changed-selector/runtime/provider/process/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires the whole create-handoff suite. Supplied disposition, late completion, close-callback and metadata-bookkeeping alarms are intentionally lost without equivalent replacement; the compound unit selector and test-file entry narrow accordingly. Five unrelated macOS receipts retain their original scope. No fresh runtime, process-deduplication, physical provider/network, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Race independent clients and repeated operation IDs, then assert one physical spawn and one canonical PTY/surface; inject exit-before-reply, provider disconnect, conflicting claim scope, old daemon/relay capabilities, reused handles, stale incarnations, owner mismatch, and topology revision conflict; assert safe adoption or explicit failure without a second spawn or wrong-process attachment. Run fresh/resume with activate true/false against an isolated headed desktop host and a separate paired client, then against isolated headless serve: assert host presentation stays background, only the requesting viewer focuses the exact leaf, inactive calls preserve client/DOM focus, a same-version publication replay cannot lose focus intent, and sibling-first split publication cannot consume exact-leaf intent. Restore legacy split panes and groups beside a newer host-owned tab, preserving exact predecessor/new/successor order, output, input, resize, titles, tab/leaf identity, active group, and multi-client convergence. For completion, drive a known running agent through outer transport loss, authoritative provider rejection, reconnect, explicit stop, real exit status, and successful hook completion; assert unavailable evidence never dispatches completion and two fresh authoritative idle samples are required after the gap. After exact exit, assert terminal and tab listings omit the surface, a stale publication cannot restore it, restart cannot resurrect it, exact tokened fixture PIDs are dead, and unrelated tabs/processes survive until scoped cleanup.", + "oracle": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3368 retires the whole host-session-launch unit source, including host-authority/create/ensure/legacy/Kimi/refusal/draft/options/prompt/cancel/kill/shared-disconnect and passive-sleep output callback alarms, without equivalent replacement. Its unit command token and test-file entry retire. Five unrelated macOS receipts remain verbatim and keep only their original scope; no fresh changed-selector/runtime/provider/process/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires the whole create-handoff suite. Supplied disposition, late completion, close-callback and metadata-bookkeeping alarms are intentionally lost without equivalent replacement; the compound unit selector and test-file entry narrow accordingly. Five unrelated macOS receipts retain their original scope. No fresh runtime, process-deduplication, physical provider/network, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Race independent clients and repeated operation IDs, then assert one physical spawn and one canonical PTY/surface; inject exit-before-reply, provider disconnect, conflicting claim scope, old daemon/relay capabilities, reused handles, stale incarnations, owner mismatch, and topology revision conflict; assert safe adoption or explicit failure without a second spawn or wrong-process attachment. Run fresh/resume with activate true/false against an isolated headed desktop host and a separate paired client, then against isolated headless serve: assert host presentation stays background, only the requesting viewer focuses the exact leaf, inactive calls preserve client/DOM focus, a same-version publication replay cannot lose focus intent, and sibling-first split publication cannot consume exact-leaf intent. Restore legacy split panes and groups beside a newer host-owned tab, preserving exact predecessor/new/successor order, output, input, resize, titles, tab/leaf identity, active group, and multi-client convergence. For completion, drive a known running agent through outer transport loss, authoritative provider rejection, reconnect, explicit stop, real exit status, and successful hook completion; assert unavailable evidence never dispatches completion and two fresh authoritative idle samples are required after the gap. After exact exit, assert terminal and tab listings omit the surface, a stale publication cannot restore it, restart cannot resurrect it, exact tokened fixture PIDs are dead, and unrelated tabs/processes survive until scoped cleanup.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/shared/claimed-agent-pty-owner.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts", @@ -7371,7 +7348,8 @@ "Audit3359 historical original testFiles object, preserved verbatim; retired claims are not active evidence or replacement coverage:\n\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts\"", "Audit3368 retires the whole host-session-launch unit source, including host-authority/create/ensure/legacy/Kimi/refusal/draft/options/prompt/cancel/kill/shared-disconnect and passive-sleep output callback alarms, without equivalent replacement. Its unit command token and test-file entry retire. Five unrelated macOS receipts remain verbatim and keep only their original scope; no fresh changed-selector/runtime/provider/process/UI/mobile/mixed-version/cross-platform evidence is claimed.", "Audit3368 historical original commands object, preserved verbatim; retired claims are not active evidence or replacement coverage:\n\"pnpm exec vitest run --config config/vitest.config.ts src/shared/claimed-agent-pty-owner.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts src/main/runtime/session-construction/agent-session/remote-agent-session-host-authority.integration.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-session-launch.test.ts\"", - "Audit3368 historical original testFiles object, preserved verbatim; retired claims are not active evidence or replacement coverage:\n\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-session-launch.test.ts\"" + "Audit3368 historical original testFiles object, preserved verbatim; retired claims are not active evidence or replacement coverage:\n\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-session-launch.test.ts\"", + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged." ], "demotionRule": "Keep experimental or demote if the focused gate flakes without a product or harness bug, if a retry can physically spawn twice, if a stale exit/publication can replace or resurrect a terminal, or if mixed-version fallback occurs after an authority side effect." }, @@ -8270,13 +8248,13 @@ "providers": ["paired-runtime", "ssh"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3342 removes three supplied activation/inventory fallback and same-handle retry examples; their fallback/retry alarms are intentionally lost without equivalent replacement. The exact mounted-HUB pending old-stream-end versus replacement-snapshot registration and its assertion remain. Unrelated dated macOS receipts retain only their original scope; no fresh runtime, provider, performance, mobile, mixed-version or cross-platform validation is claimed. NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts, src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-stall-recovery.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence. Historical prior account (preserved verbatim): Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: restarts only the stream whose renderer delivery credit never settles — An unreturned renderer delivery credit stalls only its stream, leaving healthy sibling/shared transport alive. Fake-clock deadline plus real multiplexer unsubscribe isolates recovery ownership.; probes then restarts a stream when an entered command receives no frames — Entered command produces no output; actual multiplexer must probe then close only its stalled stream after probe timeout. Distinct response liveness from parser credit.; establishes a probe baseline before recovering an unsequenced stream — 142-line manual five-probe baseline/regression sequence derives request IDs from encoded mock traffic and checks repeated no-close/close choreography. Oversized algorithm/state-machine example; no actual renderer/host command or recovery delivery. Retires unsequenced/unchanged/regressed baseline classification alarms.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces remote-runtime-pty-transport-unpublished-host-graph.test.ts, retiring its direct published-empty-graph omission-to-pane-exit alarm. The unchanged bounded unpublished-frame/pushed-recovery and stale-handle park/manual-retry cases are narrower, not equivalent replacements. Both complete three-case Linux receipts dated 2026-11-04 are archived as historical, including source heads; they do not validate this reduced selector. Remaining fourteen active receipts are macOS only. No fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2162: Reduced inventory-authority source intentionally loses the examples recorded in knownGaps; historical execution is not validation of changed bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Module ownership cleanup retires the modeled cold-park private watcher/render/work-count suites under the current test policy. Their assertions are no longer active evidence. Retained lifecycle tests and headed/headless journeys do not establish equivalent coverage for those removed harness alarms. Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/terminal-cold-park-verdict-loop.test.tsx: Loses modeled React oscillation alarm; real pane/watchers are not exercised. deletes src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts: Loses delayed credit until parsing, malformed frame/unknown stream handling, discarded transformed output recovery and failed ACK rearm alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser response-after-manual-disconnect example. Its distinct in-flight response fencing alarm is lost; retained queued-call disconnect tests are not an equivalent replacement. Historical commands and results remain historical. Deterministic headed macOS runs launch an isolated Orca desktop server and a separate paired web client. A byte-identical headless run uses an isolated `orca serve` host. Both create six real paired host PTYs with bounded high-output scrollback, prove sustained output while all six client xterms are warm-mounted but hidden causes zero renderer scheduler work, then drive 180 timed real-PTY spinner frames through a second production `session.tabs.subscribeAll` transport and the real Zustand store. Each worktree must publish and apply only its exact initial-working and final-idle titles. Both topologies ordinary-park five xterms without enabling the lossy retention budget, assert bounded cells/heap/timer lag, then restore the bounded authoritative tail exactly once on the original PTY including output produced while parked and continued input/output. The headed oracle additionally keeps every remote target workspace and terminal unmounted in the host renderer before and after client recovery. Production-parity React contracts reproduce and remove the independent cold-park watcher/title feedback loop, including memo-cache discard, StrictMode cleanup replay, detached split-PTY replacement, and the zero-park fast path. A deterministic cross-boundary contract drives 24 real PTY trackers in distinct worktrees through 2,880 decorative spinner and bare-native redraw chunks and counts host publications, serialized bytes, renderer apply calls, and store mutations while preserving exact per-PTY raw chunks and per-worktree semantic transitions. Fake-clock continuation beyond the 30-minute stale boundary requires one deduplicated refresh per worktree every 15 minutes, globally spaced by at least 50 ms, with every mirrored working status still fresh. Exact-identical Pi plus rotating normalized Pi/Grok frames renew coarse working/permission state; rich prompt/tool/question fields retain their original 30-minute lease, and `stateStartedAt`/acknowledgement identity remain stable across title/hook source swaps. A separate headed desktop-client journey relaunches the host main process while retaining the daemon and a daemon-backgrounded PTY, then requires first-observation foreground sync and continued input/output on the same PTY. Unit coverage keeps layout versions out of snapshot output high-waters when a restored snapshot has no output sequence and retries an existing subscriber only after authoritative provider inventory proves the retained PTY exists. Separate headed/headless ACK-starvation tests recover one stalled stream without replacing its PTY. A headed output-drop oracle proves a successful snapshot probe cannot certify a stale live stream when the authoritative PTY sequence advanced beyond the client high-water. Unit coverage requires an unsequenced client to establish a first-probe baseline, remain attached at the same sequence, and recover only after a later probe advances. A capability-disabled run proves legacy hosts retain the prior lossy limit/TTL fallback. Unit tests cover exact-owner capability routing, raw-stream release, singleton side-effect facts with timed handoff cleanup, 64 simultaneous synthetic-title sources with zero decorative client events after convergence, per-client late-subscribe recovery, semantic bell/title transitions, local animation-frame preservation, legacy no-output-pause delivery gating with exact snapshot restore, provider-authoritative snapshots, 128 active streams plus retry after a 129th-stream capacity rejection, capacity-pressure backoff, full split-leaf remint reconciliation, truncation, and manual-disconnect queue fencing. Linux, Windows, live SSH, and production-scale paired hosts remain gaps. The audit removed the E2E parking override/debug-handle suite. Override exposure guards, delay/retention independence, TTL filtering and debug-handle forwarding alarms are lost. Retained real parking journeys do not establish equivalent test-harness configuration coverage. The test-value audit removes separate responsive-stream, intervening-control-frame and capacity-error classification examples. Retained multiplexer checks use fake clocks and captured transport callbacks; their per-stream isolation, deadline and probe-baseline assertions do not prove an actual host restart or equivalent replacement coverage. Historical run commands and results remain historical. The test-value audit removes the standalone retained/live metadata projection and additive-preference negative example from runtime-client-events.test.ts. Its remaining case checks partial-authority event admission through a captured callback; it does not establish full-pair projection, actual peer delivery or equivalent replacement coverage. Historical commands and results remain historical. The isolated accepted-handle-events observer suite is removed. Its runtime/worktree/pane membership, once-only delivery and listener-release ledger alarms are lost. Live hidden-retention evidence does not establish equivalent observer coverage. Audit1292: The entire host-session mirror empty-inventory settle suite is removed. Live-unpublished versus genuinely-empty hydration, same-ID revision response/in-flight fencing and cleared-tracking pending-probe invalidation alarms are lost. The singleton store and inventories were mocked; no real host census or resume delivery or equivalent replacement coverage is claimed. Audit1302: src/main/runtime/session-tabs-inventory-publication.test.ts: Keep actual runtime public inventory authority across renderer epochs/resync, fallback, aborts and invalid graph publishers. Remove copied nonempty publication, private scan counters/collector and known-host replacement, fake refresh that performs the restoration itself, environment capability flag, and private resume-store characterization whose fixture supplies reservation/rollback ordering. Lose isolated refresh/churn/receiver/capability and copied-payload wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1346 removes the entire private-state-injected session-tabs rich-status boundary suite. Its stale task/question, neutral-title preservation, owner-change and provider-generation alarms are intentionally lost. Retained real terminal journeys do not establish equivalent replacement coverage. The prior mixed 42-contract execution receipt is historical and must not validate the reduced current selector; fresh validation remains required. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1396: src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.test.ts reduced. Retire standalone reconcile set output and positive untouchedFreshSpawn/workspaceOwner copying alarms; no native watcher execution claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts reduced. Loses FIFO fairness/spacing, semantic bypass/cancellation, delayed-boundary scheduling and teardown timer-cleanup alarms. Retained fixed emission cases do not replace those outcomes. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3342 removes three supplied activation/inventory fallback and same-handle retry examples; their fallback/retry alarms are intentionally lost without equivalent replacement. The exact mounted-HUB pending old-stream-end versus replacement-snapshot registration and its assertion remain. Unrelated dated macOS receipts retain only their original scope; no fresh runtime, provider, performance, mobile, mixed-version or cross-platform validation is claimed. NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts, src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-stall-recovery.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence. Historical prior account (preserved verbatim): Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: restarts only the stream whose renderer delivery credit never settles — An unreturned renderer delivery credit stalls only its stream, leaving healthy sibling/shared transport alive. Fake-clock deadline plus real multiplexer unsubscribe isolates recovery ownership.; probes then restarts a stream when an entered command receives no frames — Entered command produces no output; actual multiplexer must probe then close only its stalled stream after probe timeout. Distinct response liveness from parser credit.; establishes a probe baseline before recovering an unsequenced stream — 142-line manual five-probe baseline/regression sequence derives request IDs from encoded mock traffic and checks repeated no-close/close choreography. Oversized algorithm/state-machine example; no actual renderer/host command or recovery delivery. Retires unsequenced/unchanged/regressed baseline classification alarms.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces remote-runtime-pty-transport-unpublished-host-graph.test.ts, retiring its direct published-empty-graph omission-to-pane-exit alarm. The unchanged bounded unpublished-frame/pushed-recovery and stale-handle park/manual-retry cases are narrower, not equivalent replacements. Both complete three-case Linux receipts dated 2026-11-04 are archived as historical, including source heads; they do not validate this reduced selector. Remaining fourteen active receipts are macOS only. No fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2162: Reduced inventory-authority source intentionally loses the examples recorded in knownGaps; historical execution is not validation of changed bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Module ownership cleanup retires the modeled cold-park private watcher/render/work-count suites under the current test policy. Their assertions are no longer active evidence. Retained lifecycle tests and headed/headless journeys do not establish equivalent coverage for those removed harness alarms. Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/terminal-cold-park-verdict-loop.test.tsx: Loses modeled React oscillation alarm; real pane/watchers are not exercised. deletes src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts: Loses delayed credit until parsing, malformed frame/unknown stream handling, discarded transformed output recovery and failed ACK rearm alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser response-after-manual-disconnect example. Its distinct in-flight response fencing alarm is lost; retained queued-call disconnect tests are not an equivalent replacement. Historical commands and results remain historical. Deterministic headed macOS runs launch an isolated Orca desktop server and a separate paired web client. A byte-identical headless run uses an isolated `orca serve` host. Both create six real paired host PTYs with bounded high-output scrollback, prove sustained output while all six client xterms are warm-mounted but hidden causes zero renderer scheduler work, then drive 180 timed real-PTY spinner frames through a second production `session.tabs.subscribeAll` transport and the real Zustand store. Each worktree must publish and apply only its exact initial-working and final-idle titles. Both topologies ordinary-park five xterms without enabling the lossy retention budget, assert bounded cells/heap/timer lag, then restore the bounded authoritative tail exactly once on the original PTY including output produced while parked and continued input/output. The headed oracle additionally keeps every remote target workspace and terminal unmounted in the host renderer before and after client recovery. Production-parity React contracts reproduce and remove the independent cold-park watcher/title feedback loop, including memo-cache discard, StrictMode cleanup replay, detached split-PTY replacement, and the zero-park fast path. A deterministic cross-boundary contract drives 24 real PTY trackers in distinct worktrees through 2,880 decorative spinner and bare-native redraw chunks and counts host publications, serialized bytes, renderer apply calls, and store mutations while preserving exact per-PTY raw chunks and per-worktree semantic transitions. Fake-clock continuation beyond the 30-minute stale boundary requires one deduplicated refresh per worktree every 15 minutes, globally spaced by at least 50 ms, with every mirrored working status still fresh. Exact-identical Pi plus rotating normalized Pi/Grok frames renew coarse working/permission state; rich prompt/tool/question fields retain their original 30-minute lease, and `stateStartedAt`/acknowledgement identity remain stable across title/hook source swaps. A separate headed desktop-client journey relaunches the host main process while retaining the daemon and a daemon-backgrounded PTY, then requires first-observation foreground sync and continued input/output on the same PTY. Unit coverage keeps layout versions out of snapshot output high-waters when a restored snapshot has no output sequence and retries an existing subscriber only after authoritative provider inventory proves the retained PTY exists. Separate headed/headless ACK-starvation tests recover one stalled stream without replacing its PTY. A headed output-drop oracle proves a successful snapshot probe cannot certify a stale live stream when the authoritative PTY sequence advanced beyond the client high-water. Unit coverage requires an unsequenced client to establish a first-probe baseline, remain attached at the same sequence, and recover only after a later probe advances. A capability-disabled run proves legacy hosts retain the prior lossy limit/TTL fallback. Unit tests cover exact-owner capability routing, raw-stream release, singleton side-effect facts with timed handoff cleanup, 64 simultaneous synthetic-title sources with zero decorative client events after convergence, per-client late-subscribe recovery, semantic bell/title transitions, local animation-frame preservation, legacy no-output-pause delivery gating with exact snapshot restore, provider-authoritative snapshots, 128 active streams plus retry after a 129th-stream capacity rejection, capacity-pressure backoff, full split-leaf remint reconciliation, truncation, and manual-disconnect queue fencing. Linux, Windows, live SSH, and production-scale paired hosts remain gaps. The audit removed the E2E parking override/debug-handle suite. Override exposure guards, delay/retention independence, TTL filtering and debug-handle forwarding alarms are lost. Retained real parking journeys do not establish equivalent test-harness configuration coverage. The test-value audit removes separate responsive-stream, intervening-control-frame and capacity-error classification examples. Retained multiplexer checks use fake clocks and captured transport callbacks; their per-stream isolation, deadline and probe-baseline assertions do not prove an actual host restart or equivalent replacement coverage. Historical run commands and results remain historical. The test-value audit removes the standalone retained/live metadata projection and additive-preference negative example from runtime-client-events.test.ts. Its remaining case checks partial-authority event admission through a captured callback; it does not establish full-pair projection, actual peer delivery or equivalent replacement coverage. Historical commands and results remain historical. The isolated accepted-handle-events observer suite is removed. Its runtime/worktree/pane membership, once-only delivery and listener-release ledger alarms are lost. Live hidden-retention evidence does not establish equivalent observer coverage. Audit1292: The entire host-session mirror empty-inventory settle suite is removed. Live-unpublished versus genuinely-empty hydration, same-ID revision response/in-flight fencing and cleared-tracking pending-probe invalidation alarms are lost. The singleton store and inventories were mocked; no real host census or resume delivery or equivalent replacement coverage is claimed. Audit1302: src/main/runtime/session-tabs-inventory-publication.test.ts: Keep actual runtime public inventory authority across renderer epochs/resync, fallback, aborts and invalid graph publishers. Remove copied nonempty publication, private scan counters/collector and known-host replacement, fake refresh that performs the restoration itself, environment capability flag, and private resume-store characterization whose fixture supplies reservation/rollback ordering. Lose isolated refresh/churn/receiver/capability and copied-payload wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1346 removes the entire private-state-injected session-tabs rich-status boundary suite. Its stale task/question, neutral-title preservation, owner-change and provider-generation alarms are intentionally lost. Retained real terminal journeys do not establish equivalent replacement coverage. The prior mixed 42-contract execution receipt is historical and must not validate the reduced current selector; fresh validation remains required. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1396: src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.test.ts reduced. Retire standalone reconcile set output and positive untouchedFreshSpawn/workspaceOwner copying alarms; no native watcher execution claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts reduced. Loses FIFO fairness/spacing, semantic bypass/cancellation, delayed-boundary scheduling and teardown timer-cleanup alarms. Retained fixed emission cases do not replace those outcomes. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/8652", "https://github.com/stablyai/orca/pull/10625" ], "invariant": "A host advertising terminal.paired-parking.v1 keeps the PTY and bounded authoritative history alive while an ordinary hidden-view park destroys the client xterm and releases its raw per-PTY stream. Reveal must restore up to the requested 5,000 rows, parked-time side effects/output, the same PTY identity, and continued input/output. Parked watcher synchronization compares parking semantics rather than fresh object identity, owns setup and cleanup across StrictMode replay, reconciles real PTY/layout changes, and performs no terminal-state scan when nothing is parked. After a host main-process relaunch, unknown local delivery-sync state must not be treated as proof that a surviving daemon PTY is already foregrounded. An empty headed session-tab inventory is authoritative only after the current renderer graph generation publishes a complete inventory and every execution host answers the PTY census; unpublished, resync-pending, transport-failed, and partially scoped inventories remain unverifiable, while genuinely authoritative empty and non-empty inventories settle and a scope-less legacy empty keeps its pre-authority best-effort settle so outdated hosts retain agent auto-resume. The unpublished-empty regression must keep the resume dispatch parked with exactly one daemon process/writer; restoring unconditional empty hydration must release one dispatch and create two live writers. If subscription precedes provider readiness, authoritative inventory must reconsider that existing subscriber without spawning, resizing, or changing reconnect state. A snapshot without an output high-water must keep it unknown rather than borrowing a layout version that can suppress newer live output. Hosts without the capability must gate hidden raw output before xterm scheduling and repaint from the authoritative snapshot on reveal while retaining the existing limit/TTL force-parking fallback. After the first semantic title state, decorative spinner frequency must add zero paired client-event frames and zero full session-tabs work between status-freshness leases regardless of hidden worktree count. Continuous working or permission evidence may refresh each affected worktree once per 15 minutes through one globally spaced FIFO so current and legacy viewers do not decay before 30 minutes; sibling PTYs share that worktree refresh, while local title animation, raw output, and semantic title, status, bell, completion, and query facts remain intact. A paired terminal stream whose delivery credits stop progressing must replace only that stream; command silence first probes authoritative state and replaces the stream if the probe times out or proves the PTY advanced beyond the client's delivered output sequence. When no comparable delivery high-water exists, the first sequenced probe establishes a baseline and only later advancement proves staleness. A same-sequence snapshot remains valid proof of a responsive silent command. A successful status probe may replace a pre-ready shared-control socket without rejecting or duplicating calls already waiting for that transport. Manual disconnect must retain pairing while preventing queued or passive calls and subscriptions from recreating transport until explicit Connect. A paired pane reconnecting to a relaunched host that has not yet published its window graph (an unpublished frame, bare or client-projected) must stay in recovery rather than retire, and the host's first published snapshot carrying the surface must reattach it; a published frame lacking the surface still retires it. The placeholder is only ever sent before the host's graph first publishes; afterwards a worktree with no tabs gets a real empty answer, pushed once to any client that asked during startup, so a paired client opening a never-opened host worktree still gets its first terminal.", - "oracle": "Audit3342 removes three supplied activation/inventory fallback and same-handle retry examples; their fallback/retry alarms are intentionally lost without equivalent replacement. The exact mounted-HUB pending old-stream-end versus replacement-snapshot registration and its assertion remain. Unrelated dated macOS receipts retain only their original scope; no fresh runtime, provider, performance, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: restarts only the stream whose renderer delivery credit never settles — An unreturned renderer delivery credit stalls only its stream, leaving healthy sibling/shared transport alive. Fake-clock deadline plus real multiplexer unsubscribe isolates recovery ownership.; probes then restarts a stream when an entered command receives no frames — Entered command produces no output; actual multiplexer must probe then close only its stalled stream after probe timeout. Distinct response liveness from parser credit.; establishes a probe baseline before recovering an unsequenced stream — 142-line manual five-probe baseline/regression sequence derives request IDs from encoded mock traffic and checks repeated no-close/close choreography. Oversized algorithm/state-machine example; no actual renderer/host command or recovery delivery. Retires unsequenced/unchanged/regressed baseline classification alarms.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces remote-runtime-pty-transport-unpublished-host-graph.test.ts, retiring its direct published-empty-graph omission-to-pane-exit alarm. The unchanged bounded unpublished-frame/pushed-recovery and stale-handle park/manual-retry cases are narrower, not equivalent replacements. Both complete three-case Linux receipts dated 2026-11-04 are archived as historical, including source heads; they do not validate this reduced selector. Remaining fourteen active receipts are macOS only. No fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Run one byte-identical six-terminal oracle against an isolated headed desktop host and an isolated headless `orca serve` host. Stage at least 1,000,000 xterm cells, hide all six warm managers, emit an initial working title followed by 30 timed real-PTY spinner frames and a final idle title per worktree, and observe a second real session-tabs subscription plus the production renderer store. Require exactly two transport envelopes and two title mutations per worktree, no decorative title crossing either boundary, and positive decoded-envelope bytes. Enable ordinary parking with the lossy retention budget disabled, require exactly one mounted manager and five parked tabs, at most 45% retained cells, no more than 16 MiB heap growth, and under 500 ms timer drift. In headed mode, require the host renderer to remain on its original workspace with zero target terminal managers mounted throughout client park, reveal, and live I/O. While a tab is parked, require authoritative terminal.read to observe new PTY output; reveal it and require the original PTY, a marker within the requested 5,000-row history, the parked marker, and post-reveal input/output. Drive 24 real PTY title trackers in distinct worktrees through 40 decorative spinner frames each, then 40 spinner frames alternating with Cursor's bare native identity redraw, using fake clocks. Require all 2,880 raw chunks exactly and zero host session-tabs publications, serialized bytes, renderer apply calls, and renderer store mutations. Continue decorative evidence beyond 30 minutes, require exactly one refresh per worktree per 15-minute lease through a FIFO spaced by at least 50 ms, and require all 24 viewer statuses to remain working and fresh; then require one exact semantic idle transition and one visible-output chunk per PTY. Require ordinary and interior-Braille title changes to publish. Drive 64 host PTYs through ten 80 ms synthetic title frames, require zero paired client events after the first frame per PTY while all 640 local frames remain observable, attach a late client and require one current frame per PTY, then require semantic bell and idle transitions on both clients. Reconstruct a legacy subscribed stream with no outputPause capability, hide a chatty pane, require no hidden xterm writes, reveal it, and require one authoritative snapshot plus continued live output. Drop and acknowledge output only for one original paired-client stream, prove the fixture process consumed input while the host model advanced and the client stayed stale, then require the command snapshot probe to replace that stream, repaint exact fixture output, preserve authoritative PTY identity and target-tab cardinality, and resume live I/O. For a client without a delivered sequence, require the first numeric probe to establish a baseline without replacement, a same-sequence probe to remain attached, and a later advanced probe to replace only that stream. Withhold the first encrypted shared-control ready frame, start one RPC, trigger a status-probe refresh, and require two connections, one host delivery, successful response, and zero retained request bytes. Admit 128 active streams, reject the 129th as retryable, release one stream, then require the retry to attach and publish a snapshot without multiplying retained subscribers. Disable terminal.paired-parking.v1 and require the same oracle to fail before parking, while the legacy limit-one fallback separately passes. Also preserve truncated first paint, ACK-starved same-PTY recovery, responsive silent-command snapshot probes, dead-stream probe timeout recovery, and queued manual-disconnect fencing.", + "oracle": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3342 removes three supplied activation/inventory fallback and same-handle retry examples; their fallback/retry alarms are intentionally lost without equivalent replacement. The exact mounted-HUB pending old-stream-end versus replacement-snapshot registration and its assertion remain. Unrelated dated macOS receipts retain only their original scope; no fresh runtime, provider, performance, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: restarts only the stream whose renderer delivery credit never settles — An unreturned renderer delivery credit stalls only its stream, leaving healthy sibling/shared transport alive. Fake-clock deadline plus real multiplexer unsubscribe isolates recovery ownership.; probes then restarts a stream when an entered command receives no frames — Entered command produces no output; actual multiplexer must probe then close only its stalled stream after probe timeout. Distinct response liveness from parser credit.; establishes a probe baseline before recovering an unsequenced stream — 142-line manual five-probe baseline/regression sequence derives request IDs from encoded mock traffic and checks repeated no-close/close choreography. Oversized algorithm/state-machine example; no actual renderer/host command or recovery delivery. Retires unsequenced/unchanged/regressed baseline classification alarms.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces remote-runtime-pty-transport-unpublished-host-graph.test.ts, retiring its direct published-empty-graph omission-to-pane-exit alarm. The unchanged bounded unpublished-frame/pushed-recovery and stale-handle park/manual-retry cases are narrower, not equivalent replacements. Both complete three-case Linux receipts dated 2026-11-04 are archived as historical, including source heads; they do not validate this reduced selector. Remaining fourteen active receipts are macOS only. No fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Run one byte-identical six-terminal oracle against an isolated headed desktop host and an isolated headless `orca serve` host. Stage at least 1,000,000 xterm cells, hide all six warm managers, emit an initial working title followed by 30 timed real-PTY spinner frames and a final idle title per worktree, and observe a second real session-tabs subscription plus the production renderer store. Require exactly two transport envelopes and two title mutations per worktree, no decorative title crossing either boundary, and positive decoded-envelope bytes. Enable ordinary parking with the lossy retention budget disabled, require exactly one mounted manager and five parked tabs, at most 45% retained cells, no more than 16 MiB heap growth, and under 500 ms timer drift. In headed mode, require the host renderer to remain on its original workspace with zero target terminal managers mounted throughout client park, reveal, and live I/O. While a tab is parked, require authoritative terminal.read to observe new PTY output; reveal it and require the original PTY, a marker within the requested 5,000-row history, the parked marker, and post-reveal input/output. Drive 24 real PTY title trackers in distinct worktrees through 40 decorative spinner frames each, then 40 spinner frames alternating with Cursor's bare native identity redraw, using fake clocks. Require all 2,880 raw chunks exactly and zero host session-tabs publications, serialized bytes, renderer apply calls, and renderer store mutations. Continue decorative evidence beyond 30 minutes, require exactly one refresh per worktree per 15-minute lease through a FIFO spaced by at least 50 ms, and require all 24 viewer statuses to remain working and fresh; then require one exact semantic idle transition and one visible-output chunk per PTY. Require ordinary and interior-Braille title changes to publish. Drive 64 host PTYs through ten 80 ms synthetic title frames, require zero paired client events after the first frame per PTY while all 640 local frames remain observable, attach a late client and require one current frame per PTY, then require semantic bell and idle transitions on both clients. Reconstruct a legacy subscribed stream with no outputPause capability, hide a chatty pane, require no hidden xterm writes, reveal it, and require one authoritative snapshot plus continued live output. Drop and acknowledge output only for one original paired-client stream, prove the fixture process consumed input while the host model advanced and the client stayed stale, then require the command snapshot probe to replace that stream, repaint exact fixture output, preserve authoritative PTY identity and target-tab cardinality, and resume live I/O. For a client without a delivered sequence, require the first numeric probe to establish a baseline without replacement, a same-sequence probe to remain attached, and a later advanced probe to replace only that stream. Withhold the first encrypted shared-control ready frame, start one RPC, trigger a status-probe refresh, and require two connections, one host delivery, successful response, and zero retained request bytes. Admit 128 active streams, reject the 129th as retryable, release one stream, then require the retry to attach and publish a snapshot without multiplying retained subscribers. Disable terminal.paired-parking.v1 and require the same oracle to fail before parking, while the legacy limit-one fallback separately passes. Also preserve truncated first paint, ACK-starved same-PTY recovery, responsive silent-command snapshot probes, dead-stream probe timeout recovery, and queued manual-disconnect fencing.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts", "ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", @@ -8284,7 +8262,7 @@ "ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-lifecycle/publication/mobile-session-tabs-agent-status-heartbeat.test.ts tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts --maxWorkers=1", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-view-parking.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-worktree-retention.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-view-parking.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-worktree-retention.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts", @@ -8318,8 +8296,6 @@ "src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts", "tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts", "src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts", - "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts", - "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts", "src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-worktree-retention.test.ts", "src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-view-parking.test.ts", "src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts", @@ -8447,13 +8423,6 @@ "reserves PTY wait capacity independently from active streams" ] }, - { - "file": "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts", - "assertions": [ - "pauses capable paired output while hidden and restores exactly on reveal", - "locally gates hidden paired output when a legacy host cannot pause it" - ] - }, { "file": "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts", "assertions": [ @@ -8747,7 +8716,9 @@ "Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: restarts only the stream whose renderer delivery credit never settles — An unreturned renderer delivery credit stalls only its stream, leaving healthy sibling/shared transport alive. Fake-clock deadline plus real multiplexer unsubscribe isolates recovery ownership.; probes then restarts a stream when an entered command receives no frames — Entered command produces no output; actual multiplexer must probe then close only its stalled stream after probe timeout. Distinct response liveness from parser credit.; establishes a probe baseline before recovering an unsequenced stream — 142-line manual five-probe baseline/regression sequence derives request IDs from encoded mock traffic and checks repeated no-close/close choreography. Oversized algorithm/state-machine example; no actual renderer/host command or recovery delivery. Retires unsequenced/unchanged/regressed baseline classification alarms.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed.", "NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts, src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-stall-recovery.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence.", "NEXT46 historical original active selector fields (verbatim JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts\",\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\",\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-lifecycle/publication/mobile-session-tabs-agent-status-heartbeat.test.ts tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts --maxWorkers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts --maxWorkers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-view-parking.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-worktree-retention.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-reconciliation.test.ts src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-stall-recovery.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts --maxWorkers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"ORCA_E2E_FORWARD_APP_LOGS=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=10 --max-failures=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_DISABLE_PAIRED_TERMINAL_PARKING=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-parked-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n ]\ntestFiles: [\n \"src/main/runtime/session-lifecycle/publication/mobile-session-tabs-agent-status-heartbeat.test.ts\",\n \"tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts\",\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/renderer/src/web/web-preload-api-runtime-environment.test.ts\",\n \"src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts\",\n \"src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts\",\n \"src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts\",\n \"src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts\",\n \"src/main/runtime/rpc/terminal-subscribe-buffer.test.ts\",\n \"src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts\",\n \"src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts\",\n \"src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts\",\n \"tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-worktree-retention.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-view-parking.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-reconciliation.test.ts\",\n \"src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-stall-recovery.test.ts\",\n \"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts\",\n \"tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts\",\n \"tests/e2e/paired-remote-terminal-stall-recovery.spec.ts\",\n \"tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts\",\n \"tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts\",\n \"tests/e2e/paired-remote-terminal-retention-memory.spec.ts\",\n \"tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts\",\n \"tests/e2e/terminal-parked-memory.spec.ts\",\n \"tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts\",\n \"tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts\",\n \"src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\",\n \"tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts\",\n \"assertions\": [\n \"2,880 decorative spinner and bare-native real-PTY OSC chunks publish zero session-tabs snapshots or serialized bytes after semantic convergence\",\n \"the viewer performs zero snapshot applies and zero store mutations during decorative activity\",\n \"after 30 minutes, one globally spaced refresh per worktree keeps every mirrored working status fresh\",\n \"exact Pi and rotating normalized Pi/Grok frames renew explicit and fallback status without changing stateStartedAt or acknowledgement semantics\",\n \"matching title evidence renews retained OSC hook status without resetting stateStartedAt, then drops unverifiable prompt metadata after the hook row expires\",\n \"renderer-authored rich status keeps its original lease, then renews only coarse title-confirmed state and provider identity\",\n \"ordinary-shell title transitions replace working stateStartedAt with the completion transition time\",\n \"decorative heartbeats remain blocked until unknown foreground ownership resolves, then resume at the bounded interval\",\n \"tracked terminal state reset clears delayed foreground ownership markers\",\n \"raw chunks, semantic idle transitions, and visible output remain exact\"\n ]\n },\n {\n \"file\": \"src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"assertions\": [\"retries an existing subscriber when provider inventory becomes ready\"]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts\",\n \"assertions\": [\n \"creation and removal at the census release edge are subsumed once, and a delayed pre-boundary change is not replayed\",\n \"post-boundary creation and removal replay after the initial snapshot in sequence order\",\n \"create/remove/recreate transitions are preserved without collapse\",\n \"a post-boundary projected-state change is delivered without a new snapshot revision\",\n \"an older coalesced callback cannot overwrite a newer immediate change\",\n \"initialization churn publishes only the latest projected state and repeated structural overflow fails after bounded recollection\",\n \"disconnect aborts the census and removes the real runtime listener\"\n ]\n },\n {\n \"file\": \"tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts\",\n \"assertions\": [\n \"unpublished empty inventory keeps resume dispatch at zero with the original daemon session, process id, and writer as the sole live writer\",\n \"an authoritative empty inventory settles the mirror and releases exactly one resume dispatch with zero liveness probes\",\n \"re-enabling unconditional empty hydration makes the identical oracle red with one resume dispatch, two session ids, two process ids, and two writer calls\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts\",\n \"assertions\": [\n \"preserves daemon PID and target PTY identity across the paired host relaunch\",\n \"foregrounds the daemon-backgrounded target on its first post-relaunch remote observation\",\n \"delivers target and post-relaunch control terminal input and live output\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts\",\n \"assertions\": [\"replaces a stale paired stream when the PTY snapshot advanced\"]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-stall-recovery.spec.ts\",\n \"assertions\": [\n \"restarts one ACK-starved paired terminal stream without replacing its PTY\"\n ]\n },\n {\n \"file\": \"tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts\",\n \"assertions\": [\"recovers an ACK-starved stream from an isolated headless Orca host\"]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts\",\n \"assertions\": [\n \"a nonempty lossy initial snapshot paints exactly once on a paired client\",\n \"the authoritative host cursor advances and live output resumes exactly once\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts\",\n \"assertions\": [\n \"paints a paired remote terminal when only its retained text tail overflowed\",\n \"legacy paired hosts retain the lossy hidden-manager budget fallback\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-retention-memory.spec.ts\",\n \"assertions\": [\n \"ordinary-parks paired terminals and restores authoritative host scrollback\",\n \"warm-mounted hidden paired streams schedule zero renderer output work under sustained host output\",\n \"six hidden real PTYs publish and apply only exact working and idle title transitions across paired transport\",\n \"client recovery completes while every target terminal remains unmounted in the host renderer\"\n ]\n },\n {\n \"file\": \"tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts\",\n \"assertions\": [\n \"ordinary-parks paired terminals against an isolated headless Orca host\",\n \"cold-activates only visible paired terminals against an isolated headless host\",\n \"the headless host bounds real-PTY decorative title transport and production store application\",\n \"the headless host shares the zero-hidden-renderer-work and exact-restoration contract\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-parked-memory.spec.ts\",\n \"assertions\": [\n \"releases un-parkable hidden worktree buffers only once the retention budget engages\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts\",\n \"assertions\": [\n \"admits 128 active streams, rejects the 129th, and reuses released capacity\",\n \"reserves PTY wait capacity independently from active streams\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"assertions\": [\n \"pauses capable paired output while hidden and restores exactly on reveal\",\n \"locally gates hidden paired output when a legacy host cannot pause it\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts\",\n \"assertions\": [\n \"keeps a mounted HUB mirror alive when the old stream ends before the replacement snapshot\"\n ]\n },\n {\n \"file\": \"src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-stall-recovery.test.ts\",\n \"assertions\": [\n \"keeps the oldest pending delivery deadline anchored while later frames settle\"\n ]\n },\n {\n \"file\": \"src/renderer/src/web/web-preload-api-runtime-environment.test.ts\",\n \"assertions\": [\n \"keeps pairing while manual disconnect fences passive reconnects\",\n \"returns a disconnect envelope when a queued active runtime call disconnects\",\n \"returns a disconnect envelope when a queued selected environment call disconnects\"\n ]\n }\n ]", - "Audit3342 removes three supplied activation/inventory fallback and same-handle retry examples; their fallback/retry alarms are intentionally lost without equivalent replacement. The exact mounted-HUB pending old-stream-end versus replacement-snapshot registration and its assertion remain. Unrelated dated macOS receipts retain only their original scope; no fresh runtime, provider, performance, mobile, mixed-version or cross-platform validation is claimed." + "Audit3342 removes three supplied activation/inventory fallback and same-handle retry examples; their fallback/retry alarms are intentionally lost without equivalent replacement. The exact mounted-HUB pending old-stream-end versus replacement-snapshot registration and its assertion remain. Unrelated dated macOS receipts retain only their original scope; no fresh runtime, provider, performance, mobile, mixed-version or cross-platform validation is claimed.", + "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts\",\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\",\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-lifecycle/publication/mobile-session-tabs-agent-status-heartbeat.test.ts tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts --maxWorkers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts --maxWorkers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal-subscribe-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-view-parking.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-worktree-retention.test.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts --maxWorkers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"ORCA_E2E_FORWARD_APP_LOGS=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=10 --max-failures=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_DISABLE_PAIRED_TERMINAL_PARKING=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-parked-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n ]\ntestFiles: [\n \"src/main/runtime/session-lifecycle/publication/mobile-session-tabs-agent-status-heartbeat.test.ts\",\n \"tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts\",\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/renderer/src/web/web-preload-api-runtime-environment.test.ts\",\n \"src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts\",\n \"src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts\",\n \"src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts\",\n \"src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts\",\n \"src/main/runtime/rpc/terminal-subscribe-buffer.test.ts\",\n \"src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts\",\n \"src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts\",\n \"src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts\",\n \"tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-worktree-retention.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-view-parking.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts\",\n \"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts\",\n \"tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts\",\n \"tests/e2e/paired-remote-terminal-stall-recovery.spec.ts\",\n \"tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts\",\n \"tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts\",\n \"tests/e2e/paired-remote-terminal-retention-memory.spec.ts\",\n \"tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts\",\n \"tests/e2e/terminal-parked-memory.spec.ts\",\n \"tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts\",\n \"tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts\",\n \"src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\",\n \"tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts\",\n \"assertions\": [\n \"2,880 decorative spinner and bare-native real-PTY OSC chunks publish zero session-tabs snapshots or serialized bytes after semantic convergence\",\n \"the viewer performs zero snapshot applies and zero store mutations during decorative activity\",\n \"after 30 minutes, one globally spaced refresh per worktree keeps every mirrored working status fresh\",\n \"exact Pi and rotating normalized Pi/Grok frames renew explicit and fallback status without changing stateStartedAt or acknowledgement semantics\",\n \"matching title evidence renews retained OSC hook status without resetting stateStartedAt, then drops unverifiable prompt metadata after the hook row expires\",\n \"renderer-authored rich status keeps its original lease, then renews only coarse title-confirmed state and provider identity\",\n \"ordinary-shell title transitions replace working stateStartedAt with the completion transition time\",\n \"decorative heartbeats remain blocked until unknown foreground ownership resolves, then resume at the bounded interval\",\n \"tracked terminal state reset clears delayed foreground ownership markers\",\n \"raw chunks, semantic idle transitions, and visible output remain exact\"\n ]\n },\n {\n \"file\": \"src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"assertions\": [\"retries an existing subscriber when provider inventory becomes ready\"]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts\",\n \"assertions\": [\n \"creation and removal at the census release edge are subsumed once, and a delayed pre-boundary change is not replayed\",\n \"post-boundary creation and removal replay after the initial snapshot in sequence order\",\n \"create/remove/recreate transitions are preserved without collapse\",\n \"a post-boundary projected-state change is delivered without a new snapshot revision\",\n \"an older coalesced callback cannot overwrite a newer immediate change\",\n \"initialization churn publishes only the latest projected state and repeated structural overflow fails after bounded recollection\",\n \"disconnect aborts the census and removes the real runtime listener\"\n ]\n },\n {\n \"file\": \"tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts\",\n \"assertions\": [\n \"unpublished empty inventory keeps resume dispatch at zero with the original daemon session, process id, and writer as the sole live writer\",\n \"an authoritative empty inventory settles the mirror and releases exactly one resume dispatch with zero liveness probes\",\n \"re-enabling unconditional empty hydration makes the identical oracle red with one resume dispatch, two session ids, two process ids, and two writer calls\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts\",\n \"assertions\": [\n \"preserves daemon PID and target PTY identity across the paired host relaunch\",\n \"foregrounds the daemon-backgrounded target on its first post-relaunch remote observation\",\n \"delivers target and post-relaunch control terminal input and live output\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts\",\n \"assertions\": [\"replaces a stale paired stream when the PTY snapshot advanced\"]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-stall-recovery.spec.ts\",\n \"assertions\": [\n \"restarts one ACK-starved paired terminal stream without replacing its PTY\"\n ]\n },\n {\n \"file\": \"tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts\",\n \"assertions\": [\"recovers an ACK-starved stream from an isolated headless Orca host\"]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts\",\n \"assertions\": [\n \"a nonempty lossy initial snapshot paints exactly once on a paired client\",\n \"the authoritative host cursor advances and live output resumes exactly once\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts\",\n \"assertions\": [\n \"paints a paired remote terminal when only its retained text tail overflowed\",\n \"legacy paired hosts retain the lossy hidden-manager budget fallback\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-retention-memory.spec.ts\",\n \"assertions\": [\n \"ordinary-parks paired terminals and restores authoritative host scrollback\",\n \"warm-mounted hidden paired streams schedule zero renderer output work under sustained host output\",\n \"six hidden real PTYs publish and apply only exact working and idle title transitions across paired transport\",\n \"client recovery completes while every target terminal remains unmounted in the host renderer\"\n ]\n },\n {\n \"file\": \"tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts\",\n \"assertions\": [\n \"ordinary-parks paired terminals against an isolated headless Orca host\",\n \"cold-activates only visible paired terminals against an isolated headless host\",\n \"the headless host bounds real-PTY decorative title transport and production store application\",\n \"the headless host shares the zero-hidden-renderer-work and exact-restoration contract\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-parked-memory.spec.ts\",\n \"assertions\": [\n \"releases un-parkable hidden worktree buffers only once the retention budget engages\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal-multiplex-pty-wait-capacity.test.ts\",\n \"assertions\": [\n \"admits 128 active streams, rejects the 129th, and reuses released capacity\",\n \"reserves PTY wait capacity independently from active streams\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"assertions\": [\n \"pauses capable paired output while hidden and restores exactly on reveal\",\n \"locally gates hidden paired output when a legacy host cannot pause it\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts\",\n \"assertions\": [\n \"keeps a mounted HUB mirror alive when the old stream ends before the replacement snapshot\"\n ]\n },\n {\n \"file\": \"src/renderer/src/web/web-preload-api-runtime-environment.test.ts\",\n \"assertions\": [\n \"keeps pairing while manual disconnect fences passive reconnects\",\n \"returns a disconnect envelope when a queued active runtime call disconnects\",\n \"returns a disconnect envelope when a queued selected environment call disconnects\"\n ]\n }\n ]", + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged." ], "demotionRule": "Keep experimental or demote to protection none if decorative title frequency changes paired client-event or session-tabs publication volume after convergence, a semantic fact is dropped, paired first paint is blank, passive work reconnects after manual disconnect, a capable hidden paired manager survives ordinary parking, a legacy hidden pane schedules raw xterm output or bypasses its fallback, reveal loses requested bounded history or live PTY identity, retained buffer cells do not fall, or either headed/headless scenario flakes." }, @@ -8818,7 +8789,8 @@ "Audit1301 retires this complete dated receipt because a source in its selector was deleted or reduced. It does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-10-06\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"result\": \"passed\",\n \"command\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty-startup-barrier-and-listing.test.ts src/renderer/src/components/status-bar/use-resource-session-inventory.test.tsx src/renderer/src/components/status-bar/resource-session-inventory.test.ts --maxWorkers=2 --reporter=dot\",\n \"currentCommand\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty/pty-startup-barrier-and-listing.test.ts src/renderer/src/components/status-bar/use-resource-session-inventory.test.tsx src/renderer/src/components/status-bar/resource-session-inventory.test.ts --maxWorkers=2 --reporter=dot\",\n \"durationSeconds\": 8.736,\n \"summary\": \"After removing source-text tests, the retained behavioral cohort passed 28 tests. No fresh native desktop, Docker, or hosted run is claimed. Historical evidence before the test removal (original commands were executed then, not rerun now): [{\\\"date\\\":\\\"2026-07-22\\\",\\\"runner\\\":\\\"local\\\",\\\"platform\\\":\\\"macos\\\",\\\"command\\\":\\\"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty/pty-startup-barrier-and-listing.test.ts src/renderer/src/components/status-bar/use-resource-session-inventory.test.tsx src/renderer/src/components/status-bar/resource-session-inventory.test.ts src/renderer/src/components/status-bar/ResourceUsageStatusSegment.session-polling.test.ts\\\",\\\"result\\\":\\\"passed\\\",\\\"durationSeconds\\\":4.3,\\\"summary\\\":\\\"4 files and 358 tests passed, covering readiness seed/recovery, zero interval polling, bounded unknown-spawn reconciliation, concurrent provider starts, exit fencing, cleanup, and out-of-order refresh fencing.\\\"}]\"\n }", "Audit1301 historical assertion inventory for deleted/reduced sources; not current validated assertions:\n[\n {\n \"file\": \"src/renderer/src/components/status-bar/use-resource-session-inventory.test.tsx\",\n \"assertions\": [\n \"the false-to-true workspace readiness transition performs one daemon inventory seed\",\n \"a failed readiness seed surfaces an error and a later inventory refresh recovers\",\n \"known-session reattach signals perform zero additional inventory reads\",\n \"multiple unknown background spawn signals coalesce to one inventory read\",\n \"spawn signals during a slow inventory read never overlap provider-wide scans and cause at most one required follow-up\",\n \"unknown sessions that exit before reconciliation cancel their queued inventory read\",\n \"unmount during a slow inventory read cannot schedule follow-up work\",\n \"exit and out-of-order refresh races cannot resurrect stale sessions\",\n \"an explicit daemon-management invalidation performs exactly one inventory read, and none before readiness or after unmount\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/status-bar/resource-session-inventory.test.ts\",\n \"assertions\": [\n \"daemon inventory construction copies its source and preserves count parity\",\n \"single and batch removals preserve unrelated sessions and no-op references\"\n ]\n }\n]", "Audit1302: src/main/ai-vault/parse-cache/session-parse-cache-persistence.test.ts: Keep real filesystem/SQLite persistence, reopen/restart hits, changed-file invalidation, legacy/corrupt-cache recovery, concurrent scope replacement and optional-cache write failure isolation. Remove configuration/sidecar copy inventories, write-call-only timing/row counts, a wall-clock polling case with an internally hung parser, synthetic UNC aging/stat inventory and a no-op mock pretending to be failed database deletion. Lose these private configuration/scheduling/sidecar/UNC/fault wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.", - "Audit1302 retired the complete dated receipt after source coverage changed. Its result does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-10-02\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/ai-vault-tab-title-sync.test.ts src/main/ai-vault/session-scanner-service-client.test.ts src/main/ai-vault/session-title-file-reader.test.ts src/main/ai-vault/session-parse-cache-persistence.test.ts src/main/ipc/ai-vault.test.ts src/main/runtime/rpc/methods/ai-vault.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 5.3,\n \"summary\": \"The focused run passed 138 tests across 7 files, proving exact-title-only renderer requests, provider-isolated batching, per-lane scanner-service lifecycle and fault recovery, exact transcript identity, host routing, mixed-version degradation, and zero broad-scan fallback.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/ai-vault-tab-title-sync.test.ts src/main/ai-vault/scan-service/session-scanner-service-client.test.ts src/main/ai-vault/session-titles/session-title-file-reader.test.ts src/main/ai-vault/parse-cache/session-parse-cache-persistence.test.ts src/main/ipc/ai-vault/ai-vault.test.ts src/main/runtime/rpc/methods/ai-vault.test.ts\"\n }" + "Audit1302 retired the complete dated receipt after source coverage changed. Its result does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-10-02\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/ai-vault-tab-title-sync.test.ts src/main/ai-vault/session-scanner-service-client.test.ts src/main/ai-vault/session-title-file-reader.test.ts src/main/ai-vault/session-parse-cache-persistence.test.ts src/main/ipc/ai-vault.test.ts src/main/runtime/rpc/methods/ai-vault.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 5.3,\n \"summary\": \"The focused run passed 138 tests across 7 files, proving exact-title-only renderer requests, provider-isolated batching, per-lane scanner-service lifecycle and fault recovery, exact transcript identity, host routing, mixed-version degradation, and zero broad-scan fallback.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/ai-vault-tab-title-sync.test.ts src/main/ai-vault/scan-service/session-scanner-service-client.test.ts src/main/ai-vault/session-titles/session-title-file-reader.test.ts src/main/ai-vault/parse-cache/session-parse-cache-persistence.test.ts src/main/ipc/ai-vault/ai-vault.test.ts src/main/runtime/rpc/methods/ai-vault.test.ts\"\n }", + "Renderer direct-owner cleanup retires the complete ai-vault-tab-title-sync suite (seven registrations), already referenced only by dormant historical metadata here. Its sleeping-title retention, kind normalization, late-host precedence, identity invalidation, wire serialization/concurrency, transcript-path retry and refresh-pacing alarms are lost without equivalent replacement. The retained freshness queued closed-tab case exercises public batch admission only and supplies no polling-budget, transport/provider/native UI or measured-performance result. No current gate evidence/selector is added; existing historical entries retain their original scope." ], "demotionRule": "Cannot promote if the test allows broad listing in any hot interaction path." }, @@ -8910,7 +8882,7 @@ "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Local macOS evidence covers main-process pending-output and projection-admission caps, saturated-tail wait detection, direct-SSH source retention/accounting, always-on V1 negotiation with legacy peer fallback, exact provider-generation pause ownership, renderer exit/data ordering, decoder input bounds, bounded reconnect scheduling, and WSL stdio transport settlement through deterministic unit contracts. A joined main/runtime oracle exercises renderer-sourced headed semantics and headless-model snapshot semantics without launching a live paired server. Separately, a macOS-hosted Docker OpenSSH run exercises only the deployed Linux relay and direct SSH provider with an exact 256 KiB source-credit plateau, concurrent PTY typing, fixed-size filesystem frames, Git churn, and owner-lease reconnect. Neither deterministic topology labels nor Docker SSH constitute live headed desktop, headless orca serve, or physical WSL evidence; local/daemon, prior-version daemons, Windows named pipes/ConPTY, folder workspaces, and mixed-version clients also remain uncovered. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Local macOS evidence covers main-process pending-output and projection-admission caps, saturated-tail wait detection, direct-SSH source retention/accounting, always-on V1 negotiation with legacy peer fallback, exact provider-generation pause ownership, renderer exit/data ordering, decoder input bounds, bounded reconnect scheduling, and WSL stdio transport settlement through deterministic unit contracts. A joined main/runtime oracle exercises renderer-sourced headed semantics and headless-model snapshot semantics without launching a live paired server. Separately, a macOS-hosted Docker OpenSSH run exercises only the deployed Linux relay and direct SSH provider with an exact 256 KiB source-credit plateau, concurrent PTY typing, fixed-size filesystem frames, Git churn, and owner-lease reconnect. Neither deterministic topology labels nor Docker SSH constitute live headed desktop, headless orca serve, or physical WSL evidence; local/daemon, prior-version daemons, Windows named pipes/ConPTY, folder workspaces, and mixed-version clients also remain uncovered. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6836", "https://github.com/stablyai/orca/pull/6858", @@ -8918,7 +8890,7 @@ "https://github.com/stablyai/orca/pull/7054" ], "invariant": "High-volume terminal output must stay bounded across daemon socket writes, SSH relay writer/decoder/source retention/reconnect, main model and projection admission, runtime metadata, detectors, and tail checks, main-to-renderer in-flight bytes, renderer scheduler queues, and hidden-output restore without starving focused input. Every new SSH session offers V1 and every same-build relay supports it; legacy delivery is reachable only when capability negotiation proves the peer cannot use V1. Negotiated SSH spans remain exact and contiguous through activation, exit, cancellation, recovery, desktop projection, and required remote replacement; provisional activation data cannot project, reconnect may release it only into the exact attempt's private recovery quarantine after contract validation, and exit seals that quarantine against later same-token frames until ordered admission or exact cancellation proof. Reconnect checkpoint capture freezes exact provider-generation/PTy admission, cancels queued old work, and waits for the running raw completion before exposing its accepted checkpoint; timeout or failure detaches only that PTy's old model, makes the checkpoint unavailable, and releases the bounded fence without closing the shared provider, while the same failure outside an active exact migration remains generation-fatal and overlapping reconnects preserve any earlier outstanding fence. Pending renderer projection IDs are capped and compacted across split remainders, exit preparation owns its renderer fence through finalization, exit-time cancellation transfers published projections before proof commit, generation close fences late proof while draining exact projection waiters, closed-generation identity compacts without weakening stale rejection, canceled source-delivery retirement retains at most one ordered token per PTY, and pause/resume targets only the exact provider generation. Additional subscribers cannot stall the owner, while the required legacy primary retains backpressure.", - "oracle": "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The current executable slice injects main-process renderer backlog pressure, then asserts ordinary terminal-wait detection without a joined-tail allocation and with full prompt-family continuity, per-PTY and total pending-output caps, a 1,024-ID projection cap with split-remainder compaction, preserved sequenced-tail metadata, active-pending protection ahead of background trimming, exact provider-generation pause ownership, renderer exit/data ordering, and ACK-gated in-flight bounds. The negotiation seam proves every initial connection and reconnect offers V1, the same-build relay advertises V1 without launch flags, old clients remain token-free, and method-not-found peers fall back without installing source ACK publication. The joined source-intake/multiplex oracle blocks renderer or headless serialization, admits one snapshot-covered span and one trailing span, requires replacement reservation only after the authoritative sequence is known, advances upstream ACK eligibility exactly to the covered boundary after SnapshotEnd, and delivers then ACKs the trailing span through the ordinary live path without cancellation. Source-range ledger and multiplex seams additionally require cumulative byte ACK 40 then 100 for one 100-byte frame to release exact byte credit without early source settlement, admit a contiguous higher-generation recovered token while the prior token remains unsettled, and reject stale stream or source generations without releasing in-flight byte credit. Replacement reservation rolls back every earlier span on a later failure, commit requires the exact frozen transfer states, and an authoritatively reclaimed covered span rejects commit without local trim authority while rollback removes the reservation idempotently. The exit-deadline oracle publishes a source-backed desktop projection, advances a fake clock to cancellation, and requires one projection transfer, proof commit, preparation, and final exit with no provider close, retained obligation, duplicate finalization, or process-lifetime cancellation tombstone; a second controlled proof remains pending across generation close and must never publish final exit, while both paths release the renderer preparation lease exactly once. The model-migration oracle accepts span A, blocks span B's raw emulator completion, begins disconnect migration, and proves no checkpoint or reconnect attach can remain at A; releasing B advances the exact checkpoint to B and projects B once. Its fake-clock arm reaches the 10-second deadline, requires checkpoint-unavailable, one exact model reset, zero retained admission charge and timers, and no effect from late raw settlement. Its two-PTY failure arm rejects one running raw callback under an active exact migration and requires one checkpoint-unavailable result, one model reset, zero provider closes, retained sibling checkpoint and transport liveness, zero charges and timers, and an unaffected other generation; a non-migrating sibling oracle still requires generation close. The intake additionally closes 2,048 sequential provider generations into one exact range, rejects stale events across that range, and preserves an out-of-order live gap until its own close. Direct-SSH contracts additionally prove activation-response settlement before the first source frame, claim-gated projection under same-decoder-turn response/data delivery, exact early-ACK reservation through send settlement or same-token retry, recovery completion visible before lease-held frames transfers those frames only into the private quarantine and admits no output until exact checkpoint-to-recoveryEnd coverage, invalid-checkpoint restore retention through response settlement followed by fresh-token retry and one live source frame, isolated saturated-subscriber eviction with healthy owner liveness, preserved legacy-primary backpressure, one-write ownership across write(false)/drain, control selection ahead of queued ordinary PTY input with FIFO lanes and bounded fairness, liveness rebasing, failed-exit retention through late ACK or exact recovery, response-settlement cancellation authority, token-scoped exit cancellation, exact checkpoint-to-recoveryEnd continuity, stale-owner one-shot retry, no physical PTY teardown on recovery failure, exact provider-generation closure and once-only cleanup when recovery cancellation publication or proof rejects, 16 MiB-plus-1 MiB decoder caps, charged per-PTY/session retention budgets, and eight-wide isolated reattach. The live Electron perf oracle adds hidden-output floods, renderer scheduler queue depth, dropped-output-zero normal scenarios, and active key latency budgets before promotion.", + "oracle": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Module layout SSH policy: Retire the multiplexer private-clock saturation registration, the writer saturation transition-count registration and the changed-source dated writer/backpressure receipt. Retained byte delivery, lane order, fairness, settlement and cancellation cases are unvalidated by that historical receipt. No equivalent replacement, new execution, measured performance, live SSH/WSL or cross-platform proof is claimed. The unchanged WSL protocol receipt retains only its original command scope. Historical prior account (preserved verbatim): Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/ssh/ssh-multiplexer-transport-writer.test.ts: reports saturated epochs and their drain boundary exactly once. src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. The historical receipt/currentCommand selecting src/main/ssh/ssh-multiplexer-transport-writer.test.ts remains historical and is not a passing result for the reduced current command. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete tail-wait memo suite: its sole current authored callback checks supplied fromTail/blocked field values. Retire all three broader memoization/equivalence/eviction assertion aliases; they are not backed by retained source callbacks. No scan-work budget, sustained output, physical terminal or resource measurement is assigned to this removed test. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The current executable slice injects main-process renderer backlog pressure, then asserts ordinary terminal-wait detection without a joined-tail allocation and with full prompt-family continuity, per-PTY and total pending-output caps, a 1,024-ID projection cap with split-remainder compaction, preserved sequenced-tail metadata, active-pending protection ahead of background trimming, exact provider-generation pause ownership, renderer exit/data ordering, and ACK-gated in-flight bounds. The negotiation seam proves every initial connection and reconnect offers V1, the same-build relay advertises V1 without launch flags, old clients remain token-free, and method-not-found peers fall back without installing source ACK publication. The joined source-intake/multiplex oracle blocks renderer or headless serialization, admits one snapshot-covered span and one trailing span, requires replacement reservation only after the authoritative sequence is known, advances upstream ACK eligibility exactly to the covered boundary after SnapshotEnd, and delivers then ACKs the trailing span through the ordinary live path without cancellation. Source-range ledger and multiplex seams additionally require cumulative byte ACK 40 then 100 for one 100-byte frame to release exact byte credit without early source settlement, admit a contiguous higher-generation recovered token while the prior token remains unsettled, and reject stale stream or source generations without releasing in-flight byte credit. Replacement reservation rolls back every earlier span on a later failure, commit requires the exact frozen transfer states, and an authoritatively reclaimed covered span rejects commit without local trim authority while rollback removes the reservation idempotently. The exit-deadline oracle publishes a source-backed desktop projection, advances a fake clock to cancellation, and requires one projection transfer, proof commit, preparation, and final exit with no provider close, retained obligation, duplicate finalization, or process-lifetime cancellation tombstone; a second controlled proof remains pending across generation close and must never publish final exit, while both paths release the renderer preparation lease exactly once. The model-migration oracle accepts span A, blocks span B's raw emulator completion, begins disconnect migration, and proves no checkpoint or reconnect attach can remain at A; releasing B advances the exact checkpoint to B and projects B once. Its fake-clock arm reaches the 10-second deadline, requires checkpoint-unavailable, one exact model reset, zero retained admission charge and timers, and no effect from late raw settlement. Its two-PTY failure arm rejects one running raw callback under an active exact migration and requires one checkpoint-unavailable result, one model reset, zero provider closes, retained sibling checkpoint and transport liveness, zero charges and timers, and an unaffected other generation; a non-migrating sibling oracle still requires generation close. The intake additionally closes 2,048 sequential provider generations into one exact range, rejects stale events across that range, and preserves an out-of-order live gap until its own close. Direct-SSH contracts additionally prove activation-response settlement before the first source frame, claim-gated projection under same-decoder-turn response/data delivery, exact early-ACK reservation through send settlement or same-token retry, recovery completion visible before lease-held frames transfers those frames only into the private quarantine and admits no output until exact checkpoint-to-recoveryEnd coverage, invalid-checkpoint restore retention through response settlement followed by fresh-token retry and one live source frame, isolated saturated-subscriber eviction with healthy owner liveness, preserved legacy-primary backpressure, one-write ownership across write(false)/drain, control selection ahead of queued ordinary PTY input with FIFO lanes and bounded fairness, liveness rebasing, failed-exit retention through late ACK or exact recovery, response-settlement cancellation authority, token-scoped exit cancellation, exact checkpoint-to-recoveryEnd continuity, stale-owner one-shot retry, no physical PTY teardown on recovery failure, exact provider-generation closure and once-only cleanup when recovery cancellation publication or proof rejects, 16 MiB-plus-1 MiB decoder caps, charged per-PTY/session retention budgets, and eight-wide isolated reattach. The live Electron perf oracle adds hidden-output floods, renderer scheduler queue depth, dropped-output-zero normal scenarios, and active key latency budgets before promotion.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts", @@ -9092,7 +9064,11 @@ "Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope.", "Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope.", "Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope.", - "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes." + "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes.", + "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/wsl-guest/protocol-backpressure.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/wsl-guest/dispatcher.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer.test.ts src/wsl-guest/dispatcher-client-writer.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts src/wsl-guest/dispatcher-client-writer.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts --reporter=dot\"\n ]\ntestFiles: [\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/wsl-guest/protocol-backpressure.test.ts\",\n \"src/wsl-guest/dispatcher.test.ts\",\n \"src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts\",\n \"src/main/ssh/protocol/ssh-channel-multiplexer.test.ts\",\n \"src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts\",\n \"src/wsl-guest/dispatcher-client-writer.test.ts\",\n \"src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/wsl-guest/dispatcher.test.ts\",\n \"assertions\": [\n \"a saturated legacy primary remains required backpressure and is never detached as an additional subscriber\"\n ]\n },\n {\n \"file\": \"src/wsl-guest/protocol-backpressure.test.ts\",\n \"assertions\": [\n \"relay decoder accepts one maximum frame plus 1 MiB partial input and rejects one extra byte\",\n \"a throwing continuation clears retained input, releases one pause epoch, and publishes one typed ownership error\"\n ]\n },\n {\n \"file\": \"src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts\",\n \"assertions\": [\n \"write(false) owns one frame and later ordinary traffic waits for drain\",\n \"queued control is selected before ordinary PTY backlog at drain while each lane remains FIFO\",\n \"four-control fairness guarantees ordinary progress without starving control\",\n \"one coalesced liveness bypass is allowed per saturated epoch\"\n ]\n },\n {\n \"file\": \"src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts\",\n \"assertions\": [\n \"source ACK, cancellation, exit, request, and response control frames precede queued pasted PTY input after drain\",\n \"control and ordinary frames preserve lane FIFO while ordinary input progresses after four control writes\"\n ]\n },\n {\n \"file\": \"src/wsl-guest/dispatcher-client-writer.test.ts\",\n \"assertions\": [\n \"encoded producer frames stay below high-water-minus-reserve capacity\",\n \"one fixed-size filesystem compatibility frame is admitted only on an empty sink\",\n \"control remains reserved while producer retention stays bounded\"\n ]\n },\n {\n \"file\": \"src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts\",\n \"assertions\": [\n \"WSL stdin forwards write(false), callback settlement, and drain without claiming a live WSL topology\"\n ]\n }\n ]", + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged.", + "Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. All previous note strings, dated receipts, archived raw receipts and prior gap entries retain their original scopes.", + "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. All earlier notes and dated/archived evidence retain original scopes." ], "demotionRule": "Cannot promote without metric artifacts and bounded-byte assertions." }, @@ -9328,7 +9304,7 @@ "providers": ["ssh", "remote-runtime", "wsl"], "coveredPlatforms": ["linux"], "coveredProviders": ["ssh", "remote-runtime"], - "coverageNotes": "Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires whole host-surface-replacement and create-handoff suites, removing their compound unit command tokens, test-file entries and assertion references. Fake polling/deadline/subscription, supplied stale-handle ownership, close and replacement examples are intentionally lost without equivalent replacement. The unrelated Linux paired multi-pane reconnect receipt stays verbatim with its original scope. No fresh SSH/provider/network/PTY recovery, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3342 retires the complete client create-outcome identity/options/recovery suite and the malformed-or-contradictory repo-owner response matrix. Client replay identity, options, no-downgrade, quiescence/budget/manual retry, authoritative probe-error and malformed-owner refusal alarms are intentionally lost without equivalent replacement. Remaining repo-owner late catalog and old-host re-adoption boundaries do not replace them. The unrelated Linux paired-reconnect receipt stays verbatim with its original scope. Surviving selectors are unexecuted here; no fresh SSH/provider/process-deduplication, mobile, mixed-version or cross-platform validation is claimed. Audit3329 execution amendment: the reduced one-suite reconnect selector passed on Linux (1 case). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only this one local deterministic unit case, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS and two-case Linux receipts remain archived verbatim. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: keeps a sidebar row for every still-live pane after a long sleep — Whole suite: 279 lines manually replay renderer ownership registry/status writes, snapshot patch/set, six-pane fixture inventory, and sidebar selectors/builders; expected pane IDs are production-computed. Does not run sleep/wake/transport or actual sidebar entry. Retires reconnect row-preservation assembly alarm.; still retires the regular TUI surface after an explicit terminal exit — Ordinary explicit-exit callback/map cleanup is repeated in the stale/new stream lifecycle case below. Retires separate regular-TUI baseline; keeper is not equivalent process/UI proof.; asks the HUB to recover an expired SSH pane and rebinds the host identity — Expired SSH owner error must ask the owning HUB to recover, then adopt fixed replacement handle, resubscribe and report rebind; actual transport dispatch and handle state prevent wrong-client recovery.; does not recover a pane whose relay reply was an identity mismatch — Identity mismatch means a different live PTY, so actual transport must surface refusal without recover/create, keeping original identity. Prevents destructive duplicate agent recovery.; fails closed when an older HUB cannot recover an expired SSH pane — Old HUB method_not_found is scripted mock refusal/error echo with no actual skewed host; repeats generic recovery failure propagation. Retires old-host recovery fallback refusal example.; names a held recovery's stopped WSL distro in readable copy, not the raw hold code — Pins exact WSL stopped-distro error prose after mock code; translation/copy assertion with no actual held recovery behavior. Retires readable-copy alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces runtime-environment-ssh-state.test.ts, intentionally losing metadata membership-pruning/new-target-only-read and other-environment/local-bucket isolation alarms. Preserve generation/failed-full-refresh assertion and unknown-target authoritative-list reread; these narrower cases are not equivalent replacements. The unchanged active two-case Linux reconnect materialization/sidebar receipt and covered platform retain their exact scope and do not validate the reduced SSH state selector. Preserve unrelated SSH assertions, selectors and archived history. No fresh SSH discovery, provider/PTY/network, rendered, mobile, mixed-version, cross-platform or full-gate execution is claimed. Audit3315 execution amendment: the reduced two-suite reconnect selector passed on Linux (2 cases). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only these two local deterministic unit cases, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS receipt remains archived verbatim. Audit 3312 retires the ordinary six-pane distinct-live-handle reconnect/resubscription alarm from paired-reconnect-multi-pane-materialization.test.ts. The unchanged parked-pane activation/rematerialization case remains narrower and is not an equivalent replacement. The complete prior seven-contract macOS receipt is archived as historical evidence; it does not validate the reduced selector. No fresh socket, PTY, sleep/wake, provider, platform, mobile, mixed-version or rendered execution is claimed. Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed. Audit3086: retire the destroyed fresh-session fallback settlement/non-destructive reattach alias and its direct selector; retain the detach/attach selector and assertion unchanged. The retained admission cases cover adopt-before-data and explicitly buffered-death admission without a new spawn, without replacing fallback retirement. July 28 evidence was already archived by audit3077; no duplicate retirement or new execution is claimed. Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/ssh/connection/ssh-connection-manager.test.ts: tears a failed startup down quietly, so its error is not replaced by a disconnect; marks a dial that never reached the host, so setup reports SSH’s reason; removes the registration when bulk teardown fails; leaves a connection whose own reconnect is asking the user alone; clears the pool entry when the closed connection is still the registered one; still reuses a connection that is already up; dials a user's connection test. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the terminal-create idempotency forwarding suite and its prospective selector. Preserve2 unrelated receipts without claiming the lost forwarding alarm was replaced. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the sole supplied public-SSH-state spread/sanitized-error projection and its provider-authority-pair alias. Also delete the complete tiny one-shot split-startup wrapper suite: callback-visible temporary field/reset, sequential payload and thrown-sentinel reset alarms disappear. No SSH provider epoch handoff, connection, process startup or actual terminal split was performed by either deleted suite. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer coverage proves retained native and runtime SSH payloads are admitted through production routes only with valid complete authority, stale cleanup cannot unregister a replacement runtime terminal, direct SSH Git and folder panes keep their PTY bindings through disconnect and reconnect, one authority chain stops after two automatic attempts even when each timeout exceeds the rolling window, rejected acknowledgements mutate no store maps, and one shared exact attempt admits every concurrent split-pane spawn and reattach while preserving the first PTY as the tab fallback. A later sibling failure rotates the tab once, stale callbacks from the prior attempt mutate no state, split remount activity suppression is counted per leaf, primary PTY exit promotes a bound survivor or preserves an empty continuation gap for a late sibling, and primary, non-primary, or null-PTY detach preserves exact authority on both resulting tabs. Intentional pane disposal cancels its settlement timer without breaking StrictMode remount timeout ownership. A mounted remote-runtime terminal survives repeated transport partitions without changing PTY identity. A real encrypted-WebSocket oracle proves a successful reachability probe can replace a pre-ready shared-control socket without rejecting or duplicating the waiting RPC. Direct SSH coordinator tests cover immediate terminal finalization, hydration correction, damping, bounded retry, and telemetry non-interference. Client/server heartbeat tests cover timer suspension, socket generations fence stale callbacks, cold restored-terminal attachment retries, cached pixels remain unhealthy until authoritative replay, automatic retries stop after one minute, manual reconnect preserves the PTY, and pane closure releases recovery UI state. Current-transport recovery clears every error that transport surfaced without clearing or displaying a sibling pane's errors, while transport suppression, pane retention, and the rendered surface are independently bounded. Current macOS Electron journeys against an ephemeral Linux Docker SSH target cover exact-authority repo/worktree hydration, live terminal recovery after disconnect/reconnect, and eager six-terminal remount after renderer reload. A Windows remote-runtime smoke covers reachability and PTY round-trip. Multi-target live fanout, paired-close, WSL, and patched live partition journeys remain gaps. The test-value audit narrowed resolved-worktree-execution-host.test.ts to cache reuse and invalidation. Its direct hydrated-worktree, missing-folder, restored-owner, host-stamp and empty-runtime selection alarms are lost. Other routing and recovery suites do not establish equivalent selector coverage; historical run commands and results remain historical. The test-value audit removes standalone unwritten/released renderer-authority and cross-scope request-count examples. The retained synthetic mirror/store/sidebar and pending-inventory checks do not establish real PTY byte ownership, SSH reconnection or equivalent replacement coverage; historical commands and results remain historical. The test-value audit removes direct join/label ledgers, immediate failure and negative-only stale/removal/partial-authority examples, plus the standalone retained/live event projection. Retained synthetic store/hydration compositions do not establish real SSH continuity, remote authority delivery or equivalent replacement alarms. Historical commands and results remain historical. The renderer scheduling fixture retains in-flight coalescing only. Its immediate publication and negative stale-SSH-cleanup call ledgers were removed; the retained SSH recovery evidence does not replace those alarms. The accepted-handle-events observer suite is removed, including its scoped listener and settlement-release assertions. These observer alarms are lost; retained SSH/transport journeys are not equivalent replacement coverage. The test-value audit removed repeated remote-handle rotation inventories and snapshot-first pending-restart migration examples from terminal-pty-identity-replacement.test.ts, plus direct foreground metadata setter, confirmation, evidence-enum, and prefix/worktree cleanup examples. Those rotation, pending-restart, snapshot-first migration, and foreground scalar-update alarms are lost. The retained replacement case observes pane and tab identities in one subscriber publication; it does not establish equivalent migration, process-evidence, or input-routing coverage. Historical commands and results remain historical. The test-value audit narrows terminals-hydration.test.ts to a real reconnect batch with one measured store publication and hydration-seeded history consumed by a subsequent visit/Back check. Direct split-layout, runtime/folder/floating restoration, dead-leaf focus, cold/known-absent SSH deferral, title, default-tab marker, navigation initialization, and hydrationSucceeded scalar examples are removed; those specific alarms are lost. No actual target-removal transition, live SSH connection, session writer, or persisted restart is exercised by the retained cases. The old target-scoped/snapshot assertion references are retired because the current file does not contain those oracles. Other suites and historical runs do not establish equivalent replacement coverage. Audit1299 removes tests/e2e/terminal-cold-activation-deferral.spec.ts. Private-state/work-budget/assembled-fixture alarms are intentionally lost; retained suites are not equivalent replacement coverage. No new runtime/platform evidence is claimed. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/hooks/ipc-events/direct-ssh-connect-reply-routing.test.ts removed. Initial and event-triggered partial-authority hydration fixture alarms disappear. src/renderer/src/components/terminal-pane/terminal-error-accumulation.test.ts removed. Multiline dedup/storm bounds, resource classification/collision, scoped clear/reconnect strip and1000-pane map count alarms disappear. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/main/ipc/ssh/ssh.test.ts reduced. Lose trivial missing target and mocked publication inventory. Preexisting unresolved ../ssh/ssh-port-scanner mock is recorded, not fixed. src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts reduced. Removes three no-op/work-count registrations; retains externally observed ownership consistency. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1743 removes the standalone line-height clamp/default and pane cwd fallback helper tests (5 authored cases). These trivial-helper alarms are intentionally lost, with no equivalent replacement. Only current commands/testFiles lose the deleted selectors; historical receipts and evidenceRuns remain unchanged and do not validate the reduced commands.", + "coverageNotes": "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires whole host-surface-replacement and create-handoff suites, removing their compound unit command tokens, test-file entries and assertion references. Fake polling/deadline/subscription, supplied stale-handle ownership, close and replacement examples are intentionally lost without equivalent replacement. The unrelated Linux paired multi-pane reconnect receipt stays verbatim with its original scope. No fresh SSH/provider/network/PTY recovery, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3342 retires the complete client create-outcome identity/options/recovery suite and the malformed-or-contradictory repo-owner response matrix. Client replay identity, options, no-downgrade, quiescence/budget/manual retry, authoritative probe-error and malformed-owner refusal alarms are intentionally lost without equivalent replacement. Remaining repo-owner late catalog and old-host re-adoption boundaries do not replace them. The unrelated Linux paired-reconnect receipt stays verbatim with its original scope. Surviving selectors are unexecuted here; no fresh SSH/provider/process-deduplication, mobile, mixed-version or cross-platform validation is claimed. Audit3329 execution amendment: the reduced one-suite reconnect selector passed on Linux (1 case). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only this one local deterministic unit case, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS and two-case Linux receipts remain archived verbatim. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: keeps a sidebar row for every still-live pane after a long sleep — Whole suite: 279 lines manually replay renderer ownership registry/status writes, snapshot patch/set, six-pane fixture inventory, and sidebar selectors/builders; expected pane IDs are production-computed. Does not run sleep/wake/transport or actual sidebar entry. Retires reconnect row-preservation assembly alarm.; still retires the regular TUI surface after an explicit terminal exit — Ordinary explicit-exit callback/map cleanup is repeated in the stale/new stream lifecycle case below. Retires separate regular-TUI baseline; keeper is not equivalent process/UI proof.; asks the HUB to recover an expired SSH pane and rebinds the host identity — Expired SSH owner error must ask the owning HUB to recover, then adopt fixed replacement handle, resubscribe and report rebind; actual transport dispatch and handle state prevent wrong-client recovery.; does not recover a pane whose relay reply was an identity mismatch — Identity mismatch means a different live PTY, so actual transport must surface refusal without recover/create, keeping original identity. Prevents destructive duplicate agent recovery.; fails closed when an older HUB cannot recover an expired SSH pane — Old HUB method_not_found is scripted mock refusal/error echo with no actual skewed host; repeats generic recovery failure propagation. Retires old-host recovery fallback refusal example.; names a held recovery's stopped WSL distro in readable copy, not the raw hold code — Pins exact WSL stopped-distro error prose after mock code; translation/copy assertion with no actual held recovery behavior. Retires readable-copy alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces runtime-environment-ssh-state.test.ts, intentionally losing metadata membership-pruning/new-target-only-read and other-environment/local-bucket isolation alarms. Preserve generation/failed-full-refresh assertion and unknown-target authoritative-list reread; these narrower cases are not equivalent replacements. The unchanged active two-case Linux reconnect materialization/sidebar receipt and covered platform retain their exact scope and do not validate the reduced SSH state selector. Preserve unrelated SSH assertions, selectors and archived history. No fresh SSH discovery, provider/PTY/network, rendered, mobile, mixed-version, cross-platform or full-gate execution is claimed. Audit3315 execution amendment: the reduced two-suite reconnect selector passed on Linux (2 cases). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only these two local deterministic unit cases, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS receipt remains archived verbatim. Audit 3312 retires the ordinary six-pane distinct-live-handle reconnect/resubscription alarm from paired-reconnect-multi-pane-materialization.test.ts. The unchanged parked-pane activation/rematerialization case remains narrower and is not an equivalent replacement. The complete prior seven-contract macOS receipt is archived as historical evidence; it does not validate the reduced selector. No fresh socket, PTY, sleep/wake, provider, platform, mobile, mixed-version or rendered execution is claimed. Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed. Audit3086: retire the destroyed fresh-session fallback settlement/non-destructive reattach alias and its direct selector; retain the detach/attach selector and assertion unchanged. The retained admission cases cover adopt-before-data and explicitly buffered-death admission without a new spawn, without replacing fallback retirement. July 28 evidence was already archived by audit3077; no duplicate retirement or new execution is claimed. Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/ssh/connection/ssh-connection-manager.test.ts: tears a failed startup down quietly, so its error is not replaced by a disconnect; marks a dial that never reached the host, so setup reports SSH’s reason; removes the registration when bulk teardown fails; leaves a connection whose own reconnect is asking the user alone; clears the pool entry when the closed connection is still the registered one; still reuses a connection that is already up; dials a user's connection test. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the terminal-create idempotency forwarding suite and its prospective selector. Preserve2 unrelated receipts without claiming the lost forwarding alarm was replaced. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the sole supplied public-SSH-state spread/sanitized-error projection and its provider-authority-pair alias. Also delete the complete tiny one-shot split-startup wrapper suite: callback-visible temporary field/reset, sequential payload and thrown-sentinel reset alarms disappear. No SSH provider epoch handoff, connection, process startup or actual terminal split was performed by either deleted suite. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer coverage proves retained native and runtime SSH payloads are admitted through production routes only with valid complete authority, stale cleanup cannot unregister a replacement runtime terminal, direct SSH Git and folder panes keep their PTY bindings through disconnect and reconnect, one authority chain stops after two automatic attempts even when each timeout exceeds the rolling window, rejected acknowledgements mutate no store maps, and one shared exact attempt admits every concurrent split-pane spawn and reattach while preserving the first PTY as the tab fallback. A later sibling failure rotates the tab once, stale callbacks from the prior attempt mutate no state, split remount activity suppression is counted per leaf, primary PTY exit promotes a bound survivor or preserves an empty continuation gap for a late sibling, and primary, non-primary, or null-PTY detach preserves exact authority on both resulting tabs. Intentional pane disposal cancels its settlement timer without breaking StrictMode remount timeout ownership. A mounted remote-runtime terminal survives repeated transport partitions without changing PTY identity. A real encrypted-WebSocket oracle proves a successful reachability probe can replace a pre-ready shared-control socket without rejecting or duplicating the waiting RPC. Direct SSH coordinator tests cover immediate terminal finalization, hydration correction, damping, bounded retry, and telemetry non-interference. Client/server heartbeat tests cover timer suspension, socket generations fence stale callbacks, cold restored-terminal attachment retries, cached pixels remain unhealthy until authoritative replay, automatic retries stop after one minute, manual reconnect preserves the PTY, and pane closure releases recovery UI state. Current-transport recovery clears every error that transport surfaced without clearing or displaying a sibling pane's errors, while transport suppression, pane retention, and the rendered surface are independently bounded. Current macOS Electron journeys against an ephemeral Linux Docker SSH target cover exact-authority repo/worktree hydration, live terminal recovery after disconnect/reconnect, and eager six-terminal remount after renderer reload. A Windows remote-runtime smoke covers reachability and PTY round-trip. Multi-target live fanout, paired-close, WSL, and patched live partition journeys remain gaps. The test-value audit narrowed resolved-worktree-execution-host.test.ts to cache reuse and invalidation. Its direct hydrated-worktree, missing-folder, restored-owner, host-stamp and empty-runtime selection alarms are lost. Other routing and recovery suites do not establish equivalent selector coverage; historical run commands and results remain historical. The test-value audit removes standalone unwritten/released renderer-authority and cross-scope request-count examples. The retained synthetic mirror/store/sidebar and pending-inventory checks do not establish real PTY byte ownership, SSH reconnection or equivalent replacement coverage; historical commands and results remain historical. The test-value audit removes direct join/label ledgers, immediate failure and negative-only stale/removal/partial-authority examples, plus the standalone retained/live event projection. Retained synthetic store/hydration compositions do not establish real SSH continuity, remote authority delivery or equivalent replacement alarms. Historical commands and results remain historical. The renderer scheduling fixture retains in-flight coalescing only. Its immediate publication and negative stale-SSH-cleanup call ledgers were removed; the retained SSH recovery evidence does not replace those alarms. The accepted-handle-events observer suite is removed, including its scoped listener and settlement-release assertions. These observer alarms are lost; retained SSH/transport journeys are not equivalent replacement coverage. The test-value audit removed repeated remote-handle rotation inventories and snapshot-first pending-restart migration examples from terminal-pty-identity-replacement.test.ts, plus direct foreground metadata setter, confirmation, evidence-enum, and prefix/worktree cleanup examples. Those rotation, pending-restart, snapshot-first migration, and foreground scalar-update alarms are lost. The retained replacement case observes pane and tab identities in one subscriber publication; it does not establish equivalent migration, process-evidence, or input-routing coverage. Historical commands and results remain historical. The test-value audit narrows terminals-hydration.test.ts to a real reconnect batch with one measured store publication and hydration-seeded history consumed by a subsequent visit/Back check. Direct split-layout, runtime/folder/floating restoration, dead-leaf focus, cold/known-absent SSH deferral, title, default-tab marker, navigation initialization, and hydrationSucceeded scalar examples are removed; those specific alarms are lost. No actual target-removal transition, live SSH connection, session writer, or persisted restart is exercised by the retained cases. The old target-scoped/snapshot assertion references are retired because the current file does not contain those oracles. Other suites and historical runs do not establish equivalent replacement coverage. Audit1299 removes tests/e2e/terminal-cold-activation-deferral.spec.ts. Private-state/work-budget/assembled-fixture alarms are intentionally lost; retained suites are not equivalent replacement coverage. No new runtime/platform evidence is claimed. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/hooks/ipc-events/direct-ssh-connect-reply-routing.test.ts removed. Initial and event-triggered partial-authority hydration fixture alarms disappear. src/renderer/src/components/terminal-pane/terminal-error-accumulation.test.ts removed. Multiline dedup/storm bounds, resource classification/collision, scoped clear/reconnect strip and1000-pane map count alarms disappear. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/main/ipc/ssh/ssh.test.ts reduced. Lose trivial missing target and mocked publication inventory. Preexisting unresolved ../ssh/ssh-port-scanner mock is recorded, not fixed. src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts reduced. Removes three no-op/work-count registrations; retains externally observed ownership consistency. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1743 removes the standalone line-height clamp/default and pane cwd fallback helper tests (5 authored cases). These trivial-helper alarms are intentionally lost, with no equivalent replacement. Only current commands/testFiles lose the deleted selectors; historical receipts and evidenceRuns remain unchanged and do not validate the reduced commands.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-3107", "https://github.com/stablyai/orca/pull/12664", @@ -9343,13 +9319,13 @@ "https://github.com/stablyai/orca/issues/12902" ], "invariant": "SSH, WSL, and remote-runtime restore paths must treat provider listing failures and unknown liveness as unknown, not dead, while still avoiding duplicate spawn and clearing expired relay leases exactly once. Direct SSH disconnect, reconnect, and wake must keep PTY bindings and relay identity, and target snapshot hydration/reconnect cannot reset sibling SSH, local, WSL, or runtime-owned state. Every restored remote terminal must preserve its provider PTY identity, including the authoritative incarnation returned by a successful session-ID reattach. After a recoverable partition the same authenticated runtime must reattach the same PTY, reject detached input, apply the latest viewport, and report healthy only after authoritative replay. A successful one-shot reachability probe may replace a pre-ready shared-control socket, but waiting RPCs must continue onto the replacement under their original deadline without duplicate host delivery or retained request bytes. Automatic PTY recovery stops after one bounded minute without a fatal terminal error; a manual reconnect starts a newly fenced epoch against the same PTY, and closed panes retain no recovery UI state. Successful current-transport recovery must clear every stale error surfaced for that pane without clearing or displaying a sibling pane's error; a later genuine failure must remain visible. Each transport retains at most eight suppressed messages, each pane retains at most eight distinct messages, and the rendered surface retains at most 24 lines and 4,000 characters. One capability-gated terminal-create mutation must produce at most one host PTY across an unknown response outcome, remain manually retryable after cutoff, and never let a stale completion replace a newer pane lifecycle. Reconnect must alternate exact activation with authoritative inventory so neither a stale activation response nor an activation failure can strand or retire a pane, and activating a parked surface whose persisted binding was already retired must respawn it rather than report a changed owner after signalling its exit.", - "oracle": "Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires whole host-surface-replacement and create-handoff suites, removing their compound unit command tokens, test-file entries and assertion references. Fake polling/deadline/subscription, supplied stale-handle ownership, close and replacement examples are intentionally lost without equivalent replacement. The unrelated Linux paired multi-pane reconnect receipt stays verbatim with its original scope. No fresh SSH/provider/network/PTY recovery, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3342 retires the complete client create-outcome identity/options/recovery suite and the malformed-or-contradictory repo-owner response matrix. Client replay identity, options, no-downgrade, quiescence/budget/manual retry, authoritative probe-error and malformed-owner refusal alarms are intentionally lost without equivalent replacement. Remaining repo-owner late catalog and old-host re-adoption boundaries do not replace them. The unrelated Linux paired-reconnect receipt stays verbatim with its original scope. Surviving selectors are unexecuted here; no fresh SSH/provider/process-deduplication, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: keeps a sidebar row for every still-live pane after a long sleep — Whole suite: 279 lines manually replay renderer ownership registry/status writes, snapshot patch/set, six-pane fixture inventory, and sidebar selectors/builders; expected pane IDs are production-computed. Does not run sleep/wake/transport or actual sidebar entry. Retires reconnect row-preservation assembly alarm.; still retires the regular TUI surface after an explicit terminal exit — Ordinary explicit-exit callback/map cleanup is repeated in the stale/new stream lifecycle case below. Retires separate regular-TUI baseline; keeper is not equivalent process/UI proof.; asks the HUB to recover an expired SSH pane and rebinds the host identity — Expired SSH owner error must ask the owning HUB to recover, then adopt fixed replacement handle, resubscribe and report rebind; actual transport dispatch and handle state prevent wrong-client recovery.; does not recover a pane whose relay reply was an identity mismatch — Identity mismatch means a different live PTY, so actual transport must surface refusal without recover/create, keeping original identity. Prevents destructive duplicate agent recovery.; fails closed when an older HUB cannot recover an expired SSH pane — Old HUB method_not_found is scripted mock refusal/error echo with no actual skewed host; repeats generic recovery failure propagation. Retires old-host recovery fallback refusal example.; names a held recovery's stopped WSL distro in readable copy, not the raw hold code — Pins exact WSL stopped-distro error prose after mock code; translation/copy assertion with no actual held recovery behavior. Retires readable-copy alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces runtime-environment-ssh-state.test.ts, intentionally losing metadata membership-pruning/new-target-only-read and other-environment/local-bucket isolation alarms. Preserve generation/failed-full-refresh assertion and unknown-target authoritative-list reread; these narrower cases are not equivalent replacements. The unchanged active two-case Linux reconnect materialization/sidebar receipt and covered platform retain their exact scope and do not validate the reduced SSH state selector. Preserve unrelated SSH assertions, selectors and archived history. No fresh SSH discovery, provider/PTY/network, rendered, mobile, mixed-version, cross-platform or full-gate execution is claimed. Audit 3312 retires the ordinary six-pane distinct-live-handle reconnect/resubscription alarm from paired-reconnect-multi-pane-materialization.test.ts. The unchanged parked-pane activation/rematerialization case remains narrower and is not an equivalent replacement. The complete prior seven-contract macOS receipt is archived as historical evidence; it does not validate the reduced selector. No fresh socket, PTY, sleep/wake, provider, platform, mobile, mixed-version or rendered execution is claimed. Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed. Audit3086: retire the destroyed fresh-session fallback settlement/non-destructive reattach alias and its direct selector; retain the detach/attach selector and assertion unchanged. The retained admission cases cover adopt-before-data and explicitly buffered-death admission without a new spawn, without replacing fallback retirement. July 28 evidence was already archived by audit3077; no duplicate retirement or new execution is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/ssh/connection/ssh-connection-manager.test.ts: tears a failed startup down quietly, so its error is not replaced by a disconnect; marks a dial that never reached the host, so setup reports SSH’s reason; removes the registration when bulk teardown fails; leaves a connection whose own reconnect is asking the user alone; clears the pool entry when the closed connection is still the registered one; still reuses a connection that is already up; dials a user's connection test. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the terminal-create idempotency forwarding suite and its prospective selector. Preserve2 unrelated receipts without claiming the lost forwarding alarm was replaced. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the sole supplied public-SSH-state spread/sanitized-error projection and its provider-authority-pair alias. Also delete the complete tiny one-shot split-startup wrapper suite: callback-visible temporary field/reset, sequential payload and thrown-sentinel reset alarms disappear. No SSH provider epoch handoff, connection, process startup or actual terminal split was performed by either deleted suite. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Deterministic tests cover bounded stale-handle replacement, suspended heartbeat clocks, cold and established subscription failure, ten partition/recovery cycles, automatic-recovery cutoff, manual reconnect, and direct SSH binding retention. They assert SSH state changes leave PTY bindings in place, relay identity survives, and another target/local/WSL/runtime panes remain byte-identical through target snapshot hydration and reconnect. Both remount callbacks consume split-count activity suppression, intentional dispose emits no failure/timeout, and a same-attempt StrictMode remount still owns one timeout. Hydration clears an untrusted PTY hint without clearing its current pending owner, healthy current-authority bindings suppress correction, hydration finalizes once, and reconnect emits no paired close lifecycle. A provider-level session-ID reattach returns an incarnation, then a legacy exit without an incarnation must resolve to that returned identity rather than minting a fallback identity. The shared-control oracle withholds the first encrypted ready frame, starts one RPC, triggers the successful-probe refresh, then requires exactly two client connections, one host request, a successful response, zero pending calls, and zero retained request bytes. Tests also assert one unsubscribe per remote-runtime epoch, observable recovery phases, stable PTY identity, resumed snapshot/output/input, no healthy state before replay, no retry or input after cutoff, a new manual epoch against the same PTY, quiet recovery UI with an explicit Reconnect action, pane-close state cleanup, one stable create mutation id, old-runtime no-retry behavior, cross-process PTY adoption, and bounded in-flight coordination. A focused recovery oracle surfaces two distinct failures through one transport, completes authoritative replay, and requires both matching clear callbacks; pane-state tests require only the active pane's error to render, matching-pane recovery to preserve sibling and unrelated errors, dismissal to re-admit later failures, and distinct storms to retain only the newest eight messages within 24 lines and 4,000 characters. The retained store replacement assertion observes one atomic pane/tab subscriber publication; repeated rotations and snapshot-first pending-restart migration no longer have their direct store examples.", + "oracle": "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires whole host-surface-replacement and create-handoff suites, removing their compound unit command tokens, test-file entries and assertion references. Fake polling/deadline/subscription, supplied stale-handle ownership, close and replacement examples are intentionally lost without equivalent replacement. The unrelated Linux paired multi-pane reconnect receipt stays verbatim with its original scope. No fresh SSH/provider/network/PTY recovery, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3342 retires the complete client create-outcome identity/options/recovery suite and the malformed-or-contradictory repo-owner response matrix. Client replay identity, options, no-downgrade, quiescence/budget/manual retry, authoritative probe-error and malformed-owner refusal alarms are intentionally lost without equivalent replacement. Remaining repo-owner late catalog and old-host re-adoption boundaries do not replace them. The unrelated Linux paired-reconnect receipt stays verbatim with its original scope. Surviving selectors are unexecuted here; no fresh SSH/provider/process-deduplication, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: keeps a sidebar row for every still-live pane after a long sleep — Whole suite: 279 lines manually replay renderer ownership registry/status writes, snapshot patch/set, six-pane fixture inventory, and sidebar selectors/builders; expected pane IDs are production-computed. Does not run sleep/wake/transport or actual sidebar entry. Retires reconnect row-preservation assembly alarm.; still retires the regular TUI surface after an explicit terminal exit — Ordinary explicit-exit callback/map cleanup is repeated in the stale/new stream lifecycle case below. Retires separate regular-TUI baseline; keeper is not equivalent process/UI proof.; asks the HUB to recover an expired SSH pane and rebinds the host identity — Expired SSH owner error must ask the owning HUB to recover, then adopt fixed replacement handle, resubscribe and report rebind; actual transport dispatch and handle state prevent wrong-client recovery.; does not recover a pane whose relay reply was an identity mismatch — Identity mismatch means a different live PTY, so actual transport must surface refusal without recover/create, keeping original identity. Prevents destructive duplicate agent recovery.; fails closed when an older HUB cannot recover an expired SSH pane — Old HUB method_not_found is scripted mock refusal/error echo with no actual skewed host; repeats generic recovery failure propagation. Retires old-host recovery fallback refusal example.; names a held recovery's stopped WSL distro in readable copy, not the raw hold code — Pins exact WSL stopped-distro error prose after mock code; translation/copy assertion with no actual held recovery behavior. Retires readable-copy alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces runtime-environment-ssh-state.test.ts, intentionally losing metadata membership-pruning/new-target-only-read and other-environment/local-bucket isolation alarms. Preserve generation/failed-full-refresh assertion and unknown-target authoritative-list reread; these narrower cases are not equivalent replacements. The unchanged active two-case Linux reconnect materialization/sidebar receipt and covered platform retain their exact scope and do not validate the reduced SSH state selector. Preserve unrelated SSH assertions, selectors and archived history. No fresh SSH discovery, provider/PTY/network, rendered, mobile, mixed-version, cross-platform or full-gate execution is claimed. Audit 3312 retires the ordinary six-pane distinct-live-handle reconnect/resubscription alarm from paired-reconnect-multi-pane-materialization.test.ts. The unchanged parked-pane activation/rematerialization case remains narrower and is not an equivalent replacement. The complete prior seven-contract macOS receipt is archived as historical evidence; it does not validate the reduced selector. No fresh socket, PTY, sleep/wake, provider, platform, mobile, mixed-version or rendered execution is claimed. Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed. Audit3086: retire the destroyed fresh-session fallback settlement/non-destructive reattach alias and its direct selector; retain the detach/attach selector and assertion unchanged. The retained admission cases cover adopt-before-data and explicitly buffered-death admission without a new spawn, without replacing fallback retirement. July 28 evidence was already archived by audit3077; no duplicate retirement or new execution is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/ssh/connection/ssh-connection-manager.test.ts: tears a failed startup down quietly, so its error is not replaced by a disconnect; marks a dial that never reached the host, so setup reports SSH’s reason; removes the registration when bulk teardown fails; leaves a connection whose own reconnect is asking the user alone; clears the pool entry when the closed connection is still the registered one; still reuses a connection that is already up; dials a user's connection test. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the terminal-create idempotency forwarding suite and its prospective selector. Preserve2 unrelated receipts without claiming the lost forwarding alarm was replaced. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the sole supplied public-SSH-state spread/sanitized-error projection and its provider-authority-pair alias. Also delete the complete tiny one-shot split-startup wrapper suite: callback-visible temporary field/reset, sequential payload and thrown-sentinel reset alarms disappear. No SSH provider epoch handoff, connection, process startup or actual terminal split was performed by either deleted suite. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Deterministic tests cover bounded stale-handle replacement, suspended heartbeat clocks, cold and established subscription failure, ten partition/recovery cycles, automatic-recovery cutoff, manual reconnect, and direct SSH binding retention. They assert SSH state changes leave PTY bindings in place, relay identity survives, and another target/local/WSL/runtime panes remain byte-identical through target snapshot hydration and reconnect. Both remount callbacks consume split-count activity suppression, intentional dispose emits no failure/timeout, and a same-attempt StrictMode remount still owns one timeout. Hydration clears an untrusted PTY hint without clearing its current pending owner, healthy current-authority bindings suppress correction, hydration finalizes once, and reconnect emits no paired close lifecycle. A provider-level session-ID reattach returns an incarnation, then a legacy exit without an incarnation must resolve to that returned identity rather than minting a fallback identity. The shared-control oracle withholds the first encrypted ready frame, starts one RPC, triggers the successful-probe refresh, then requires exactly two client connections, one host request, a successful response, zero pending calls, and zero retained request bytes. Tests also assert one unsubscribe per remote-runtime epoch, observable recovery phases, stable PTY identity, resumed snapshot/output/input, no healthy state before replay, no retry or input after cutoff, a new manual epoch against the same PTY, quiet recovery UI with an explicit Reconnect action, pane-close state cleanup, one stable create mutation id, old-runtime no-retry behavior, cross-process PTY adoption, and bounded in-flight coordination. A focused recovery oracle surfaces two distinct failures through one transport, completes authoritative replay, and requires both matching clear callbacks; pane-state tests require only the active pane's error to render, matching-pane recovery to preserve sibling and unrelated errors, dismissal to re-admit later failures, and distinct storms to retain only the newest eight messages within 24 lines and 4,000 characters. The retained store replacement assertion observes one atomic pane/tab subscriber publication; repeated rotations and snapshot-first pending-restart migration no longer have their direct store examples.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime/remote-runtime-client-error-classification.test.ts src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts --reporter=dot", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/ssh/ssh.test.ts src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/preload/ssh-authority-forwarding.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts src/shared/ssh-retained-payload-admission.test.ts --reporter=dot", "pnpm exec electron-vite build --mode e2e", "pnpm run build:web-from-renderer", @@ -9360,7 +9336,6 @@ "src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts", "src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts", "src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts", - "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts", "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts", "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts", "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts", @@ -9459,12 +9434,6 @@ "an unknown target triggers an authoritative list reread" ] }, - { - "file": "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts", - "assertions": [ - "a StrictMode remount joins the pending spawn instead of starting a second one" - ] - }, { "file": "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts", "assertions": [ @@ -9584,7 +9553,8 @@ "Audit3359 historical original assertionRefs object, preserved verbatim; retired claims are not active evidence or replacement coverage:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-host-surface-replacement.test.ts\",\n \"assertions\": [\n \"a stale web-mirror handle polls until a different ready handle is published without resubscribing the stale handle\",\n \"replacement does not emit pane exit or disconnect callbacks and explicit terminal exit still retires the mirror\",\n \"replacement polling and each in-flight request share a 15-second deadline, then accepted snapshots own recovery without input re-arming polling\"\n ]\n }", "Audit3359 historical original assertionRefs object, preserved verbatim; retired claims are not active evidence or replacement coverage:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-create-handoff.test.ts\",\n \"assertions\": [\n \"a stale create completion cannot replace or close a newer attachment, including when two runtimes use the same raw handle\"\n ]\n }", "Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed.", - "Audit3368 historical original assertionRefs object, preserved verbatim; retired claims are not active evidence or replacement coverage:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\n \"assertions\": [\n \"recovery exposes connecting, recovering, backoff, connected, and fatal-offline phases with fenced epochs\",\n \"ten partition cycles retain one PTY identity, reject detached input, and unsubscribe each epoch exactly once\",\n \"automatic retries stop after one minute with no fatal error, no further requests, and no stale input\",\n \"manual reconnect starts a new epoch, resubscribes the same PTY exactly once, and becomes healthy only after its snapshot\"\n ]\n }" + "Audit3368 historical original assertionRefs object, preserved verbatim; retired claims are not active evidence or replacement coverage:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\n \"assertions\": [\n \"recovery exposes connecting, recovering, backoff, connected, and fatal-offline phases with fenced epochs\",\n \"ten partition cycles retain one PTY identity, reject detached input, and unsubscribe each epoch exactly once\",\n \"automatic retries stop after one minute with no fatal error, no further requests, and no stale input\",\n \"manual reconnect starts a new epoch, resubscribes the same PTY exactly once, and becomes healthy only after its snapshot\"\n ]\n }", + "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime/remote-runtime-client-error-classification.test.ts src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/ssh/ssh.test.ts src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/preload/ssh-authority-forwarding.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts src/shared/ssh-retained-payload-admission.test.ts --reporter=dot\",\n \"pnpm exec electron-vite build --mode e2e\",\n \"pnpm run build:web-from-renderer\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\n \"src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts\",\n \"src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/one-shot-park-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts\",\n \"src/renderer/src/store/terminals/terminal-pty-identity-replacement.test.ts\",\n \"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts\",\n \"src/shared/remote-runtime/remote-runtime-client-error-classification.test.ts\",\n \"src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts\",\n \"src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\n \"tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts\",\n \"src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts\",\n \"src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts\",\n \"src/main/ipc/ssh/ssh.test.ts\",\n \"src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts\",\n \"src/main/ssh/connection/ssh-connection-manager.test.ts\",\n \"src/main/ssh/connection/ssh-connection.test.ts\",\n \"src/preload/ssh-authority-forwarding.test.ts\",\n \"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\n \"src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts\",\n \"src/shared/ssh-retained-payload-admission.test.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\n \"assertions\": [\n \"a pane parked while the client slept is authoritatively activated and rematerialized without leaving any pane handle null\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\n \"assertions\": [\n \"ten synthetic partition cycles retain one PTY identity, deliver each held detached input exactly once and release each epoch subscription exactly once; decoded live input/output remains current\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/remote-runtime-pty-recovery-state.test.ts\",\n \"assertions\": [\n \"the automatic-recovery deadline cancels pending backoff and a manual retry owns a new epoch\"\n ]\n },\n {\n \"file\": \"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\n \"assertions\": [\n \"a suspended client receives a fresh probe deadline after resume and post-resume activity clears it\"\n ]\n },\n {\n \"file\": \"src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\n \"assertions\": [\n \"one authenticated client/worktree mutation derives a stable server-owned terminal handle\",\n \"an unknown-outcome retry adopts the same provider PTY after runtime-process restart without rerunning startup\",\n \"retry inventory failure, missing same-worktree identity metadata, or ownership mismatch fails closed without spawning\",\n \"in-flight mutation coordination is bounded and releases capacity after settlement\"\n ]\n },\n {\n \"file\": \"src/main/ssh/connection/ssh-connection-manager.test.ts\",\n \"assertions\": [\n \"disconnect invalidates a pending transport attempt immediately so late rejection or resolution cannot remove the replacement\"\n ]\n },\n {\n \"file\": \"src/main/ssh/connection/ssh-connection.test.ts\",\n \"assertions\": [\n \"late ssh2 ready and startup error events after disconnect cannot resurrect or overwrite disconnected state\"\n ]\n },\n {\n \"file\": \"src/preload/ssh-authority-forwarding.test.ts\",\n \"assertions\": [\n \"full authority crosses Electron IPC without loss\",\n \"partial authority becomes unknown for bounded reconciliation and malformed full authority is dropped\",\n \"variable-form host-qualified worktree requests retain fail-closed outcomes in their return type\"\n ]\n },\n {\n \"file\": \"src/shared/ssh-retained-payload-admission.test.ts\",\n \"assertions\": [\n \"retained connection states reject partial or malformed authority\",\n \"only partial compatibility authority can normalize to unknown for bounded direct-SSH reconciliation\",\n \"shared direct SSH authority admission requires bounded identifiers and a non-negative safe generation\"\n ]\n },\n {\n \"file\": \"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\n \"assertions\": [\n \"partial runtime authority is rejected through the captured subscription callback before environment state receives it\"\n ]\n },\n {\n \"file\": \"src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts\",\n \"assertions\": [\n \"held replies from an old generation cannot replace a newer generation; failed full refresh preserves live state behind queued metadata\",\n \"an unknown target triggers an authoritative list reread\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts\",\n \"assertions\": [\n \"a StrictMode remount joins the pending spawn instead of starting a second one\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\n \"assertions\": [\n \"abandoning an obsolete reattach drops its data, replay, write-unavailable, and exit handlers without killing the durable PTY\"\n ]\n }\n ]" ], "demotionRule": "Cannot promote if provider failure can close panes or if the oracle is screenshot-only." }, @@ -9803,7 +9773,7 @@ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts src/shared/terminal/input/terminal-composer-draft.test.ts src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge-kitty-bytes.test.ts src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/ipc/terminal-preview-output-stream.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/preload/app-restart-checkpoint-routing.test.ts src/renderer/src/web/web-preload-api-ui.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/preload/app-restart-checkpoint-routing.test.ts src/renderer/src/web/web-preload-api-ui.test.ts", "pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts", "pnpm run test:e2e -- tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts", "pnpm run test:e2e -- tests/e2e/terminal-option-composed-ascii.spec.ts" @@ -9818,7 +9788,6 @@ "src/shared/terminal/input/terminal-composer-draft.test.ts", "src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts", "src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts", - "src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts", "src/main/ipc/macos-keyboard-layout-change-notifications.test.ts", "src/preload/app-restart-checkpoint-routing.test.ts", "src/renderer/src/web/web-preload-api-ui.test.ts", @@ -10003,7 +9972,8 @@ "Audit1888 removes the entire candidate-key-release-guard and composition-tracker suites. Direct candidate predicate/map, held-repeat, expiry, changed-modifier and overlapping-release alarms, plus composition active/stale/trailing-guard/reset alarms, are intentionally lost. It reduces placeholder-mask: frame/lookalike/stock-draft inventories and simple end/dispose cleanup alarms are lost; real xterm draft visibility, blur without end/repaint, live reclassification and newest-session ownership remain. Native-text-forwarder loses structural claim, direct forwarding/encoding inventories, early-keyup/modifier/tombstone/transaction/disposal examples; only NumLock press-pinned release identity, swallowed-repeat release obligation and negotiation-pop suppression remain. The standalone Mac remap expected-text case is removed; captured remap plus an explicitly DERIVED neighbour remains. Four pre-audit assertionRefs are retired below as historical inventory, with no equivalent replacement claim. Retained tests use simulated events, flags, frames and transport; this is not native IME/substitution, real host/PTY, focus, soak or measured-budget validation. All five active IME receipts remain raw unchanged because their exact selectors are unaffected: four Electron receipts and the byte-exact unchanged fcitx4 replay suite/currentCommand. Other active selectors/assertions, coverage/maturity accounting, and all prior notes remain unchanged.", "Audit1888 historical assertion inventory for removed/reduced suites; not current validated assertions. Original raw assertion objects follow:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-candidate-key-release-guard.test.ts\",\n \"assertions\": [\n \"suppressed candidate keydown arms only the matching keypress/keyup release guard\",\n \"held-key repeat keydowns stay guarded until their keyup, even past expiry\",\n \"fresh keydowns, other keys, modified keys, and expired keypresses are not guarded, and a fresh press drops a stale pending release\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composition-tracker.test.ts\",\n \"assertions\": [\n \"empty Sogou-style compositionupdate keeps composition active\",\n \"stale composition state expires so editing keys cannot stay suppressed indefinitely\",\n \"post-composition candidate guard is armed only by Sogou-style empty updates and clears after real typing\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts\",\n \"assertions\": [\n \"a bold Codex prompt row with a dimmed model footer below a blank gap, and a framed Claude prompt, acquire the mask class only while composing\",\n \"the same placeholder text without its footer or frame, and arbitrary dimmed output, acquire nothing\",\n \"a row carrying typed text acquires no mask even while the stock placeholder is still rendered to its right\",\n \"the class is gone after composition end, after a blur with no session end behind it, and after disposal\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts\",\n \"assertions\": [\n \"native text commits route once to the intended PTY\",\n \"composition/preedit bookkeeping does not leak premature text\",\n \"multi-codepoint committed text is reported independently from physical key identity\"\n ]\n }", "Audit1896 removes the entire synthetic local-echo trailing-preedit suite, CSI-u encoding table, Option-compose scalar policy, non-Mac/Mac bypass matrices and runtime-prefix projection suite. Their direct overlay, scalar key/flag encoding, bypass/suppression and environment-projection alarms are intentionally lost. The removed paste-runtime suite only projects supplied PTY-prefix/runtime-environment values; runtime-environment selection does not validate payload forwarding or deduplication. Its retired duplicate-payload assertion overstated that test and is preserved verbatim only as historical inventory. It reduces midline-preedit-tail to competing final-cell caret/candidate anchor owners with supplied geometry and actual xterm buffer repaint under an open preedit: arbitrary dimmed-output, simple cleanup, other row-tail/style inventories and nearby geometry cases are lost. Resumed-preedit-visibility retains only commit/cleanup of an update-inferred transaction; recorded/ordinary-neighbour reactivation examples are removed. Option-kitty-release retains only first-sender ownership across autorepeat versus fresh-press replacement of an orphaned owner: live modifier/layout/NumLock identity, native dead-key and negotiation/mode-pop inventories are lost. Three complete assertionRefs are retired and three narrowed; all six prior raw objects are archived below as historical inventory. Tests use synthetic DOM events, supplied geometry/state and callback/transport sinks, with no native IME/keyboard, current device, real PTY, ConPTY, remote runtime, focus/app, soak or measured-budget validation. No equivalent replacement is claimed. All five active IME receipts retain exact unaffected selectors and raw objects; all230 current receipts, prior knownGap literals and unrelated accounting/fields are preserved. This note records scope loss only and promotes no new execution evidence.", - "Audit1896 historical assertion inventory for three retired and three narrowed refs; not current validated assertions. Original raw assertion objects follow:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-trailing-preedit-occlusion.test.ts\",\n \"assertions\": [\n \"rolling Korean input keeps only the uncommitted trailing syllable in the themed overlay\",\n \"the overlay remains anchored to the live cursor cell and clears after commit\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/keyboard/xterm-bypass-policy-non-mac.test.ts\",\n \"assertions\": [\n \"standalone Linux 229 keydowns reach xterm while Windows 229 keydowns stay suppressed\",\n \"candidate Space/digit selectors are suppressed only while candidate guards are active\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/paste/terminal-paste-runtime.test.ts\",\n \"assertions\": [\"paste/runtime forwarding avoids duplicate terminal payloads\"]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-midline-preedit-tail.test.ts\",\n \"assertions\": [\n \"a mid-line preedit reproduces committed cells hidden by its opaque overlay and refreshes that tail after terminal renders\",\n \"arbitrary fully dimmed output remains visible even at column zero\",\n \"the final-column caret stays visible and the textarea candidate anchor shifts left with an over-wide preedit\",\n \"cancel, empty resumed updates, and disposal remove transient overlay state\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"assertions\": [\n \"recorded Windows Korean compositionupdate-without-compositionstart traces reactivate a visible preedit transaction\",\n \"the resumed transaction commits exactly once and cleans up normally\",\n \"the ordinary Linux compositionstart sequence remains unchanged\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"assertions\": [\n \"owned releases use live Shift and Option state and current alternate-key flags\",\n \"owned releases retain the delivered press identity across layout, Shift, and NumLock changes\",\n \"a native dead-key keyup is consumed without inventing an unmatched protocol release\",\n \"event-type pop consumes without bytes and repeat keydowns cannot replace the original release owner\"\n ]\n }" + "Audit1896 historical assertion inventory for three retired and three narrowed refs; not current validated assertions. Original raw assertion objects follow:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-trailing-preedit-occlusion.test.ts\",\n \"assertions\": [\n \"rolling Korean input keeps only the uncommitted trailing syllable in the themed overlay\",\n \"the overlay remains anchored to the live cursor cell and clears after commit\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/keyboard/xterm-bypass-policy-non-mac.test.ts\",\n \"assertions\": [\n \"standalone Linux 229 keydowns reach xterm while Windows 229 keydowns stay suppressed\",\n \"candidate Space/digit selectors are suppressed only while candidate guards are active\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/paste/terminal-paste-runtime.test.ts\",\n \"assertions\": [\"paste/runtime forwarding avoids duplicate terminal payloads\"]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-midline-preedit-tail.test.ts\",\n \"assertions\": [\n \"a mid-line preedit reproduces committed cells hidden by its opaque overlay and refreshes that tail after terminal renders\",\n \"arbitrary fully dimmed output remains visible even at column zero\",\n \"the final-column caret stays visible and the textarea candidate anchor shifts left with an over-wide preedit\",\n \"cancel, empty resumed updates, and disposal remove transient overlay state\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"assertions\": [\n \"recorded Windows Korean compositionupdate-without-compositionstart traces reactivate a visible preedit transaction\",\n \"the resumed transaction commits exactly once and cleans up normally\",\n \"the ordinary Linux compositionstart sequence remains unchanged\"\n ]\n }\n{\n \"file\": \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"assertions\": [\n \"owned releases use live Shift and Option state and current alternate-key flags\",\n \"owned releases retain the delivered press identity across layout, Shift, and NumLock changes\",\n \"a native dead-key keyup is consumed without inventing an unmatched protocol release\",\n \"event-type pop consumes without bytes and repeat keydowns cannot replace the original release owner\"\n ]\n }", + "Renderer direct-owner cleanup retires the complete layout-base-character suite (one registration). Lost alarm: layout invalidation blocks focus refresh, fences an older snapshot, and accepts the new-generation character. The removed case consumed private snapshot/reset state and internal refresh-count accounting. No equivalent replacement or new execution is claimed. Remaining IME/keyboard/provider sources and the unchanged fcitx4 receipt retain their existing bounded qualifications; this removal does not validate their selectors. Historical removed active mappings (verbatim semantic values; no longer active): [{\"field\":\"testFiles\",\"previous\":[\"src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts\"]},{\"field\":\"commands\",\"previous\":[\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/preload/app-restart-checkpoint-routing.test.ts src/renderer/src/web/web-preload-api-ui.test.ts\"]}]" ], "demotionRule": "Cannot promote if success is based only on DOM text without PTY byte/cell evidence." }, @@ -10303,7 +10273,7 @@ "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.", + "coverageNotes": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-3800", "https://linear.app/stably/issue/STA-3904", @@ -10313,7 +10283,7 @@ "https://github.com/stablyai/orca/issues/14347" ], "invariant": "Injected orchestration task prompts for recognized agent CLIs must send the prompt body inside one bracketed-paste frame, sanitize embedded ESC bytes, preserve chunk boundaries without losing the frame, and submit exactly once only after the agent can accept Enter. Local worker-start with supported observation must preserve an unobserved turn as start_unknown without revoking authority, closing questions, or triggering a rescue Enter; a worker report during observation must settle normally. Claude and Codex must emit a post-paste composer marker and then settle, or reach the bounded fallback first; every other agent retains the platform delay.", - "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", + "oracle": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/shared/agent-launch/startup/agent-prompt-injection.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/orchestration/runs/tasks-dispatch.test.ts src/main/runtime/orchestration/coordinator/coordinator.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/worker-start-prompt-contract.test.ts --reporter=dot", @@ -10415,7 +10385,8 @@ "Audit2090 (sources2088/2089): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/mobile-session-tabs-windowless-sleep-resume.spec.ts: keeps the recorded permission flags of the launch it resumes; still refuses a session another pane also records; resumes in the pane with a window present too: main is the one executor; keeps the original provider and current retry intent through a refused main start; resumes once; a second open after it finished attaches to the same terminal; a reloaded window's open attaches to the terminal main started, never a second resume. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-05.spec.ts: defers live workers without exact controller identity evidence; defers an SSH folder legacy worker while its folder path is unavailable. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence.", "Audit2095 current-parent preparation2126 (approved2092/2093 removals; source refresh2109/independent2112): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts: rejects exact terminal stop for multiple expected PTYs before stopping anything; omits stale renderer leaves when fresh PTY liveness is required; omits unbound renderer placeholders when fresh PTY liveness is required; captures the event method before the nested sleep receipt changes it; returns the close receipt without requiring a PTY stop; uses the same stop result as an empty explicit stop. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts: builds a compact worktree summary from persisted and live runtime state; reads the linked-PR state from the renderer repoId-keyed GitHub cache; carries persisted worktree host ownership in mobile summaries; emits only instance- and boundary-validated lineage parents in mobile summaries; resolves WSL platforms only for repos represented in mobile summaries; omits worktrees hidden by the host visibility policy from mobile summaries; applies linked-checkout source visibility to mobile summaries. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts: routes runtime GitHub PR details and actions through the selected WSL project runtime; passes SSH connection context through hosted review creation flows; routes local WSL project hosted review flows through runtime git options; treats SSH worktree drift as unknown without local git probes. src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts: emits one mobile session terminal tab per live PTY even if two tabs resolve to it; resolves projected split authority from the parent layout PTY binding; keeps explicit-id terminal lists from resolving all worktrees; keeps explicit-id cold-cache terminal lists from classifying unrelated same-repo worktrees; keeps unknown bare terminal-list ids on the no-scan exact-id path; matches explicit-id cwd PTYs for folder workspace instance IDs; routes PTY output through the PTY leaf index in large terminal graphs. src/main/runtime/orca-runtime-tests/window-authority.spec.ts: claims the first window as authoritative and ignores later windows; transfers authority from the headless sentinel to the first real window; relays terminal browser launches only while headless owns the graph; marks live headless PTYs for renderer reattach before desktop promotion; reports the activation gate state while no desktop window is available; bumps the epoch and enters reloading when the authoritative window reloads; can mark the graph ready for the authoritative window; drops back to unavailable and clears authority when the window disappears; hands the graph back to headless when a promoted serve window closes (#27292); keeps a crashed promoted serve renderer on its own window while the window is open; stays unavailable during initial loads before a graph is published. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts, src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts, src/main/runtime/orca-runtime-tests/window-authority.spec.ts. Unresolved local/computed edges remain explicit debt.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts. Unresolved local/computed edges remain explicit debt.", - "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites." + "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites.", + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged." ], "demotionRule": "Demote or quarantine if the live harness flakes without a product bug or harness bug filed to the terminal-input owner." }, @@ -10534,7 +10505,7 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.", + "coverageNotes": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/11107#discussion_r3663321387", "https://github.com/stablyai/orca/issues/13858", @@ -10544,7 +10515,7 @@ "https://linear.app/stably/issue/STA-4022" ], "invariant": "Starting a worker in the coordinator's current workspace must materialize one inactive terminal tab before worker-start returns, preserve coordinator focus, and remain exactly once after workspace re-entry. After an app update or restart, an exact live legacy worker must fence automatic provider resume, adopt its original PTY into its original background pane, retain readable output, and clear the resume record without spawning, writing, signalling, interrupting, replacing, or focusing the worker. A current-contract worker whose renderer graph identity is temporarily absent must retain its Dispatch capability and settle exactly once from exact hook-attested handle, pane, and process evidence; otherwise only an exact attested coordinator may take over. A worker_done caller may report success only after the owning runtime returns an explicit lifecycle verdict or authoritative reads prove that the exact Task, Dispatch, and worker report receipt settled the expected outcome. Federated terminal settlement must remain replay-eligible until the worker durably acknowledges it, and identical same-outcome retries must converge idempotently. Independently updated clients and worker servers must preserve the negotiated protocol: current peers use Run-home lifecycle settlement, while protocol v1/v2 peers retain their legacy completion path without receiving newer-only fields. A federated worker may accept only the authority defined by its negotiated protocol. An exact existing target workspace must receive a discoverable tab without stealing coordinator focus; if renderer reveal fails, worker-start must expose that the live worker remains background-only. Run and Dispatch checks must resolve through the caller's stable pane identity when a terminal handle is reminted, while a live handle outranks mismatched pane metadata. A nested worker's creator edge requires the current creator pane, process incarnation, and owning Run generation; reminting and rebinding that pane to another Run must remove the stale edge. Explicit legacy terminal inspection remains handle-scoped, and remote or headless worker presentation remains background-only.", - "oracle": "Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", + "oracle": "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", "commands": [ "ORCA_BACKGROUND_LAUNCH=1 npx vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration.test.ts src/cli/handlers/orchestration-check-identity.test.ts src/cli/handlers/orchestration-worker-cli.test.ts src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts", @@ -10748,7 +10719,9 @@ "Audit2090 (sources2088/2089): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/mobile-session-tabs-windowless-sleep-resume.spec.ts: keeps the recorded permission flags of the launch it resumes; still refuses a session another pane also records; resumes in the pane with a window present too: main is the one executor; keeps the original provider and current retry intent through a refused main start; resumes once; a second open after it finished attaches to the same terminal; a reloaded window's open attaches to the terminal main started, never a second resume. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-05.spec.ts: defers live workers without exact controller identity evidence; defers an SSH folder legacy worker while its folder path is unavailable. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence.", "Audit2095 current-parent preparation2126 (approved2092/2093 removals; source refresh2109/independent2112): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts: rejects exact terminal stop for multiple expected PTYs before stopping anything; omits stale renderer leaves when fresh PTY liveness is required; omits unbound renderer placeholders when fresh PTY liveness is required; captures the event method before the nested sleep receipt changes it; returns the close receipt without requiring a PTY stop; uses the same stop result as an empty explicit stop. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts: builds a compact worktree summary from persisted and live runtime state; reads the linked-PR state from the renderer repoId-keyed GitHub cache; carries persisted worktree host ownership in mobile summaries; emits only instance- and boundary-validated lineage parents in mobile summaries; resolves WSL platforms only for repos represented in mobile summaries; omits worktrees hidden by the host visibility policy from mobile summaries; applies linked-checkout source visibility to mobile summaries. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts: routes runtime GitHub PR details and actions through the selected WSL project runtime; passes SSH connection context through hosted review creation flows; routes local WSL project hosted review flows through runtime git options; treats SSH worktree drift as unknown without local git probes. src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts: emits one mobile session terminal tab per live PTY even if two tabs resolve to it; resolves projected split authority from the parent layout PTY binding; keeps explicit-id terminal lists from resolving all worktrees; keeps explicit-id cold-cache terminal lists from classifying unrelated same-repo worktrees; keeps unknown bare terminal-list ids on the no-scan exact-id path; matches explicit-id cwd PTYs for folder workspace instance IDs; routes PTY output through the PTY leaf index in large terminal graphs. src/main/runtime/orca-runtime-tests/window-authority.spec.ts: claims the first window as authoritative and ignores later windows; transfers authority from the headless sentinel to the first real window; relays terminal browser launches only while headless owns the graph; marks live headless PTYs for renderer reattach before desktop promotion; reports the activation gate state while no desktop window is available; bumps the epoch and enters reloading when the authoritative window reloads; can mark the graph ready for the authoritative window; drops back to unavailable and clears authority when the window disappears; hands the graph back to headless when a promoted serve window closes (#27292); keeps a crashed promoted serve renderer on its own window while the window is open; stays unavailable during initial loads before a graph is published. tests/e2e/automation-terminal-launch.unit.test.ts: launches explicit Chat for %s through the common entry and keeps its actual fallback; does not apply stored Terminal extras to Chat; forwards only complete Chat-consumed values, with no Terminal startup base; refuses an expired admission without minting another launch identity; records the actual chat identity and delegates new workspace setup and provenance. tests/e2e/github-project-provider-columns.unit.test.ts: renders %s through one bounded items request on a named cloud host; preserves zero and complete counters: %j; preserves populated and legacy rows through shared sorting, grouping and cells. tests/e2e/structured-agent-session-launch-continuation.unit.test.ts: carries renderer lifetime through host intent to the real %s provider builders. tests/e2e/terminal-account-restart.unit.test.ts: replaces a tombstoned owner while its persisted pane binding has not yet been cleared; paired restart retains the old owner (host authority: %s). tests/e2e/terminal-hidden-view-parking.spec.ts: does not park excluded tabs; reproduces a static frame byte-for-byte across 25 park/reveal cycles. tests/e2e/terminal-long-table-scroll-restore.spec.ts: reproduces long markdown table artifacts after workspace switch and scroll; keeps narrow wrapped signer markdown table coherent after restore and scroll; keeps real emoji markdown table right edge clean after restore and scroll. tests/e2e/terminal-long-table-fixtures.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-paste-ownership.spec.ts: Windows multiline keyboard paste normalizes terminal newlines with one PTY owner; right-click paste sends clipboard text to the focused terminal exactly once. tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts: uses WebGL by default for ordinary terminal output when available @terminal-rendering-golden. tests/e2e/terminal-windows-shell-paste-ownership.spec.ts: cmd.exe default terminal keyboard paste preserves exact content with one PTY owner; Git Bash default terminal keyboard paste preserves POSIX-shaped content with one PTY owner; WSL terminal keyboard paste preserves Linux shell content with one PTY owner. tests/e2e/workspace-board-lane-virtualization.spec.ts: mounts a window of cards for a large lane and keeps lane indexes; renders later lane indexes after the lane scrolls. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts, src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts, src/main/runtime/orca-runtime-tests/window-authority.spec.ts, tests/e2e/automation-terminal-launch.unit.test.ts, tests/e2e/github-project-provider-columns.unit.test.ts, tests/e2e/structured-agent-session-launch-continuation.unit.test.ts, tests/e2e/terminal-account-restart.unit.test.ts, tests/e2e/terminal-hidden-view-parking.spec.ts, tests/e2e/terminal-long-table-scroll-restore.spec.ts, tests/e2e/terminal-long-table-fixtures.ts, tests/e2e/terminal-paste-ownership.spec.ts, tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts, tests/e2e/terminal-windows-shell-paste-ownership.spec.ts, tests/e2e/workspace-board-lane-virtualization.spec.ts. Unresolved local/computed edges remain explicit debt. Complete dated receipts with direct selectors or current literal graph reaching tests/e2e/automation-terminal-launch.unit.test.ts, tests/e2e/github-project-provider-columns.unit.test.ts, tests/e2e/structured-agent-session-launch-continuation.unit.test.ts, tests/e2e/terminal-account-restart.unit.test.ts, tests/e2e/terminal-hidden-view-parking.spec.ts, tests/e2e/terminal-long-table-scroll-restore.spec.ts, tests/e2e/terminal-long-table-fixtures.ts, tests/e2e/terminal-paste-ownership.spec.ts, tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts, tests/e2e/terminal-windows-shell-paste-ownership.spec.ts, tests/e2e/workspace-board-lane-virtualization.spec.ts are retired below as historical raw objects; their counts do not validate reduced commands. Historical retired receipt verbatim:\n{\n \"date\": \"2026-07-28\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm run test:e2e -- tests/e2e/orchestration-worker-terminal-visibility.spec.ts --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 8.3,\n \"summary\": \"The isolated Electron journey passed with one live fake-agent spawn, no interruption events, stable PTY/incarnation/tab/leaf/worktree/Task/Dispatch identity, immediate inactive presentation, pane-stable ACK delivery, and exactly one tab after workspace re-entry.\"\n } Historical retired receipt verbatim:\n{\n \"date\": \"2026-07-28\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm run test:e2e -- tests/e2e/orchestration-legacy-worker-restart-recovery.spec.ts --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 12.6,\n \"summary\": \"The restart journey retained one daemon PTY and PID, adopted its exact original background pane, preserved readable ACK output and Task/Dispatch authority, cleared all resume state, and recorded no second spawn, resume argv, input, signal, interruption, or duplicate after workspace re-entry.\"\n }", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. tests/e2e/claude-agent-row-view.unit.test.ts: updates a mounted compact workflow description through the subscribed production parent; bounds upstream active-SSH visits for $population records, fallback=$fallback; derives %s destinations without requiring type or a workflow child ID; terminates a $path parent $status with no third request or intermediate toast; does not recover a first child %s. tests/e2e/cross-version-wire/agent-permission-legacy-spawn.unit.test.ts: keeps exact legacy ordering when structured creation cannot express afterTabId; can create a terminal without selecting the target worktree; preserves the legacy fresh-agent path when host authority is unavailable. tests/e2e/paired-instant-browser-tab.spec.ts: shows a paired browser tab before its create RPC resolves, then keeps it as one tab; adopts a paired browser tab without rebuilding its chrome. tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts: bounds host publication and renderer application across remote worktrees; globally caps decorative freshness while every working status stays fresh. tests/e2e/session-tabs/mobile-session-active-performance.unit.test.ts: bounds saved-order publication selection at N and 10N without rematerializing navigation; bounds admitted placement reconciliation during supported reads at N and 10N; bounds selection input visits at 50 and 500 rows, including unavailable-target projection; keeps publication scoped to a changed worktree and shared by listeners at N and 10N; bounds preserved-chat merge and runtime-owned hydration at N and 10N (legacy=%s); bounds actual native retirement and shared delivery work at N and 10N. tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts: does not substitute a preserved row for an unavailable explicit legacy selection; resolves main-layout group selection %s (omitted group=%s). tests/e2e/structured-agent-session-launch-admission.unit.test.ts: opens a direct caller's terminal with the caller's own CLI arguments on a decline; opens the chat on the server that admitted it; opens only the terminal when this machine declines, without a notice; opens a new agent tab's terminal with the typed prompt when the caller names none; opens the chat, not a terminal, when this machine cannot resolve a new workspace yet; keeps its terminal fallback, as before. tests/e2e/structured-attention-prompt-relay.unit.test.ts: settles once per relayed prompt, not on every later status update. tests/e2e/structured-attention-read-retirement.unit.test.ts: Mark read on a chat never opened withdraws the prompt alert it surfaced; Mark read on a chat hidden since an earlier view covers the newer prompt it surfaced; reads a newly accepted visible prompt without sending an RPC for text-only updates. tests/e2e/structured-chat-tab-lifetime-cost.unit.test.ts: counts real raw stores, unrelated window publications and captured cleanup at %i chats; counts complete supplied-member sweep and separate final retirement at S=%i N=%i. tests/e2e/structured-session-workspace-authority.unit.test.ts: bounds actual target reveal across %i repo roots and metadata aliases. tests/e2e/terminal-agent-pane-launch.unit.test.ts: starts the host's planned command once, at the pane's size, and says it started; plans a pane whose prompt the window submits without the startup update prompt; preserves caller shell-ready delivery only for a connection-scoped adapter ($connectionId); starts no shell on plan failure (original failure: $returnLaunchFailure); cannot confirm a start whose provider answer was lost. tests/e2e/terminal-parked-memory.spec.ts: releases renderer terminal memory when hidden tabs park. tests/e2e/terminal-shortcuts.spec.ts: @headful Codex-like background output stays visible without disabling WebGL in auto mode; Shift with Russian layout text reaches the PTY as Cyrillic under kitty keyboard reporting. tests/e2e/terminal-split-activation-latency.spec.ts: records attributed CWD, spawn, bind, fixture-ready, input, and echo phases. tests/e2e/terminal-split-activation-latency-phases.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-main-probe.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-artifact.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-split-activation-latency-report.ts: dedicated zero-case helper retirement; no authored test credit. tests/e2e/terminal-tab-switch-visual-restore.spec.ts: restores skipped hidden Grok output on light tab resume. tests/e2e/web-runtime-session-terminal-host-authority.unit.test.ts: delivers independent %s effort through the real prepared web callback; keeps same-ID local and runtime worktrees on the selected runtime owner; creates paired web agents through host authority so activation is mirrored; delivers generated continuation context after host-authoritative creation; seeds the chat composer for a draft that rode in on the launch command. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts, tests/e2e/claude-agent-row-view.unit.test.ts, tests/e2e/cross-version-wire/agent-permission-legacy-spawn.unit.test.ts, tests/e2e/paired-instant-browser-tab.spec.ts, tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts, tests/e2e/session-tabs/mobile-session-active-performance.unit.test.ts, tests/e2e/session-tabs/mobile-session-active-publication.unit.test.ts, tests/e2e/structured-agent-session-launch-admission.unit.test.ts, tests/e2e/structured-attention-prompt-relay.unit.test.ts, tests/e2e/structured-attention-read-retirement.unit.test.ts, tests/e2e/structured-chat-tab-lifetime-cost.unit.test.ts, tests/e2e/structured-session-workspace-authority.unit.test.ts, tests/e2e/terminal-agent-pane-launch.unit.test.ts, tests/e2e/terminal-parked-memory.spec.ts, tests/e2e/terminal-shortcuts.spec.ts, tests/e2e/terminal-split-activation-latency.spec.ts, tests/e2e/terminal-split-activation-latency-phases.ts, tests/e2e/terminal-split-activation-latency-main-probe.ts, tests/e2e/terminal-split-activation-latency-artifact.ts, tests/e2e/terminal-split-activation-latency-report.ts, tests/e2e/terminal-tab-switch-visual-restore.spec.ts, tests/e2e/web-runtime-session-terminal-host-authority.unit.test.ts. Unresolved local/computed edges remain explicit debt.", - "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites." + "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites.", + "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"ORCA_BACKGROUND_LAUNCH=1 npx vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration.test.ts src/cli/handlers/orchestration-check-identity.test.ts src/cli/handlers/orchestration-worker-cli.test.ts src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration-lifecycle-rejection.test.ts src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts\",\n \"pnpm run test:e2e -- tests/e2e/orchestration-worker-terminal-visibility.spec.ts --workers=1\",\n \"pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/cli/handlers/orchestration.test.ts\",\n \"src/cli/handlers/orchestration-lifecycle-rejection.test.ts\",\n \"src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts\",\n \"src/cli/handlers/orchestration-check-identity.test.ts\",\n \"src/cli/handlers/orchestration-worker-cli.test.ts\",\n \"src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts\",\n \"src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts\",\n \"src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\n \"src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts\",\n \"src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts\",\n \"src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts\",\n \"tests/e2e/orchestration-worker-terminal-visibility.spec.ts\",\n \"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\n \"assertions\": [\n \"replays the coordinator instruction and takes its ack after the app restarts\",\n \"files loopback mail once under the local Dispatch Run without replacing its owner\"\n ]\n },\n {\n \"file\": \"src/cli/handlers/orchestration-lifecycle-rejection.test.ts\",\n \"assertions\": [\n \"an explicit current worker_done verdict completes without a compatibility read\",\n \"a worker_done response without a lifecycle verdict checks the exact authoritative Dispatch and report receipt\",\n \"legacy succeeded and failed reports require matching terminal Task and Dispatch state\",\n \"stopped or stale Dispatches cannot impersonate report settlement\",\n \"an idempotent retry accepts the first authoritative report from the same worker\",\n \"a Run-home relay rejection reaches the CLI error boundary\"\n ]\n },\n {\n \"file\": \"src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts\",\n \"assertions\": [\"a rejected lifecycle verdict is emitted as a JSON ok=false envelope\"]\n },\n {\n \"file\": \"src/cli/handlers/orchestration-check-identity.test.ts\",\n \"assertions\": [\n \"implicit check carries the caller pane key with a potentially stale environment handle\",\n \"explicit legacy terminal inspection does not inherit the caller pane key\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts\",\n \"assertions\": [\n \"Run delivery resolves through a stable coordinator pane after handle remint\",\n \"a live handle cannot be retargeted by mismatched pane metadata\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\n \"assertions\": [\n \"Dispatch delivery resolves through a stable worker pane after handle remint\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts\",\n \"assertions\": [\n \"a remote worker_done waits for Run-home settlement even when an older CLI omits the wait hint\",\n \"a current Run home still completes reports from legacy protocol v1/v2 worker servers\",\n \"persisted protocol v1/v2 workers retain legacy-compatible completion after their worker server updates\",\n \"preexisting same-outcome terminal ACK batches settle atomically while conflicting outcomes acknowledge nothing\",\n \"an aborted settlement wait returns operation_unknown instead of accepted success\",\n \"a Run-home terminal verdict settles the remote attachment and revokes its capability\",\n \"a terminal verdict cannot settle an unrelated relay item\",\n \"a terminal verdict cannot contradict the exact queued worker report outcome\",\n \"a rejected report replays its exact verdict without mutating durable rejection mail twice\"\n ]\n },\n {\n \"file\": \"src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts\",\n \"assertions\": [\n \"a v26 database gains a zeroed durable home-to-worker acknowledgment watermark\",\n \"a complete v26 database starts migration at v26 rather than replaying v7-v26\",\n \"the migration advances schema version without losing the imported relay cursor\"\n ]\n },\n {\n \"file\": \"tests/e2e/orchestration-worker-terminal-visibility.spec.ts\",\n \"assertions\": [\n \"worker-start exposes one inactive worker tab before workspace navigation\",\n \"the coordinator tab remains active\",\n \"ACK delivery reaches a stable coordinator pane through a stale handle\",\n \"one spawn remains live with no interruption event\",\n \"PTY/incarnation, tab, leaf, worktree, Task, and Dispatch identities remain stable\",\n \"workspace re-entry does not duplicate the worker tab or print Conversation interrupted\"\n ]\n },\n {\n \"file\": \"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\",\n \"assertions\": [\n \"a compiled CLI worker_done with the wrong identity exits nonzero with ok=false\",\n \"the exact Task and Dispatch remain dispatched after rejection\",\n \"the correct worker identity receives an explicit completed lifecycle verdict\",\n \"an independent runtime read observes the Dispatch completed\"\n ]\n }\n ]", + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged." ], "demotionRule": "Keep experimental or demote if either Electron journey flakes without a product or harness defect, if local worker-start can return before tab materialization without an explicit reveal warning, if focus moves to the worker, if restart or workspace re-entry spawns/resumes/duplicates/interferes with the worker, if retained output becomes unreadable, or if pane-stable delivery reads the wrong mailbox." }, @@ -11958,29 +11931,20 @@ "providers": ["local", "daemon", "ssh", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": ["local"], - "coverageNotes": "Audit3349 retires the whole terminal-render-desync-sentinel suite, including the same-cells persistence/recovery alarm, without equivalent replacement. Its unit command selector, test-file selector and assertion reference are removed prospectively. Earlier global-effects/window-wake retirements and the retired dated sentinel receipt remain historical verbatim. Two unrelated macOS document-visibility E2E receipts remain verbatim; the frozen static closure does not select changed tests through their literal roots. No fresh GPU/rendered UI, runtime, historical-import, mobile, mixed-version or cross-platform validation is claimed. NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence. Historical prior account (preserved verbatim): Audit3335 retires the complete mocked window-wake recovery suite (11 authored registrations/12 expanded cases), intentionally losing fullscreen atlas-preservation, wake callback ordering, deferred-DPR deduplication/repair and private frame-budget alarms without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/GPU/focus, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: recovers visible terminal rendering and input when the window regains focus — Whole suite: fake React useEffect immediately invokes bodies and ignores cleanup/deps; fake useRef/store hooks plus mocked pane manager only assert callback choreography. Does not exercise window focus, actual input or pixels. Retires focus wake wiring alarm.; clears WebGL texture atlases when the OS resumes — Whole suite: same fake-hook harness invokes captured OS resume callback and counts mocked atlas-clear/repaint methods. No GPU, actual OS resume, or real hook lifetime. Retires atlas clear wiring alarm.; preserves WebGL texture atlases when the active terminal document becomes visible — Whole suite: direct fake document visibility listener and mock-call absence/presence under fake hooks cannot establish real WebGL preservation or cleanup. Retires visibility wake wiring alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer contracts require foreground renderer-risk, synchronized, hidden, and alternate-screen PTY output to stay on pane-local repaint paths without a global atlas reset. Separate contracts preserve explicit paste, reveal, visibility-resume, system-resume, and confirmed-desync recovery. A macOS Electron run verifies that a document visibility cycle preserves real WebGL atlases and terminal pixels; the candidate has not been rerun against an isolated live paired server. The test-value audit removed registry recovery fanout, visibility, ordering and failure-isolation assertions. The remaining registry test constrains diagnostic sampling only and is excluded from this gate. No equivalent recovery coverage is claimed. Completed settled tab-reveal repaint execution is not covered after removal of pane-reveal-repaint.test.ts. The separate terminal-visibility-resume tests assert mocked scheduling and presentation calls; they do not establish completed repaint execution. Audit1342: src/renderer/src/lib/pane-manager/pane-webgl-context-recovery.test.ts removed. Context resume/reveal retry and deferred rebuild mock-pane alarms disappear. No equivalent replacement coverage is claimed. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result.", + "coverageNotes": "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3349 retires the whole terminal-render-desync-sentinel suite, including the same-cells persistence/recovery alarm, without equivalent replacement. Its unit command selector, test-file selector and assertion reference are removed prospectively. Earlier global-effects/window-wake retirements and the retired dated sentinel receipt remain historical verbatim. Two unrelated macOS document-visibility E2E receipts remain verbatim; the frozen static closure does not select changed tests through their literal roots. No fresh GPU/rendered UI, runtime, historical-import, mobile, mixed-version or cross-platform validation is claimed. NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence. Historical prior account (preserved verbatim): Audit3335 retires the complete mocked window-wake recovery suite (11 authored registrations/12 expanded cases), intentionally losing fullscreen atlas-preservation, wake callback ordering, deferred-DPR deduplication/repair and private frame-budget alarms without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/GPU/focus, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: recovers visible terminal rendering and input when the window regains focus — Whole suite: fake React useEffect immediately invokes bodies and ignores cleanup/deps; fake useRef/store hooks plus mocked pane manager only assert callback choreography. Does not exercise window focus, actual input or pixels. Retires focus wake wiring alarm.; clears WebGL texture atlases when the OS resumes — Whole suite: same fake-hook harness invokes captured OS resume callback and counts mocked atlas-clear/repaint methods. No GPU, actual OS resume, or real hook lifetime. Retires atlas clear wiring alarm.; preserves WebGL texture atlases when the active terminal document becomes visible — Whole suite: direct fake document visibility listener and mock-call absence/presence under fake hooks cannot establish real WebGL preservation or cleanup. Retires visibility wake wiring alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer contracts require foreground renderer-risk, synchronized, hidden, and alternate-screen PTY output to stay on pane-local repaint paths without a global atlas reset. Separate contracts preserve explicit paste, reveal, visibility-resume, system-resume, and confirmed-desync recovery. A macOS Electron run verifies that a document visibility cycle preserves real WebGL atlases and terminal pixels; the candidate has not been rerun against an isolated live paired server. The test-value audit removed registry recovery fanout, visibility, ordering and failure-isolation assertions. The remaining registry test constrains diagnostic sampling only and is excluded from this gate. No equivalent recovery coverage is claimed. Completed settled tab-reveal repaint execution is not covered after removal of pane-reveal-repaint.test.ts. The separate terminal-visibility-resume tests assert mocked scheduling and presentation calls; they do not establish completed repaint execution. Audit1342: src/renderer/src/lib/pane-manager/pane-webgl-context-recovery.test.ts removed. Context resume/reveal retry and deferred rebuild mock-pane alarms disappear. No equivalent replacement coverage is claimed. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/7054", "https://github.com/stablyai/orca/pull/7604", "https://github.com/stablyai/orca/issues/12094" ], "invariant": "Ordinary PTY output must never clear the shared WebGL glyph atlas, including synchronized frames, hidden output, renderer-risk glyphs, and alternate-screen entry, redraw, or exit. Affected visible panes still receive pane-local refresh after parsing. Explicit paste, reveal, visibility-resume, system-resume, context-loss, and confirmed-desync recovery remain available and may reset visible renderers.", - "oracle": "Audit3349 retires the whole terminal-render-desync-sentinel suite, including the same-cells persistence/recovery alarm, without equivalent replacement. Its unit command selector, test-file selector and assertion reference are removed prospectively. Earlier global-effects/window-wake retirements and the retired dated sentinel receipt remain historical verbatim. Two unrelated macOS document-visibility E2E receipts remain verbatim; the frozen static closure does not select changed tests through their literal roots. No fresh GPU/rendered UI, runtime, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3335 retires the complete mocked window-wake recovery suite (11 authored registrations/12 expanded cases), intentionally losing fullscreen atlas-preservation, wake callback ordering, deferred-DPR deduplication/repair and private frame-budget alarms without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/GPU/focus, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: recovers visible terminal rendering and input when the window regains focus — Whole suite: fake React useEffect immediately invokes bodies and ignores cleanup/deps; fake useRef/store hooks plus mocked pane manager only assert callback choreography. Does not exercise window focus, actual input or pixels. Retires focus wake wiring alarm.; clears WebGL texture atlases when the OS resumes — Whole suite: same fake-hook harness invokes captured OS resume callback and counts mocked atlas-clear/repaint methods. No GPU, actual OS resume, or real hook lifetime. Retires atlas clear wiring alarm.; preserves WebGL texture atlases when the active terminal document becomes visible — Whole suite: direct fake document visibility listener and mock-call absence/presence under fake hooks cannot establish real WebGL preservation or cleanup. Retires visibility wake wiring alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Parse foreground renderer-risk, synchronized, hidden, and alternate-screen PTY output and require pane-local refresh where needed with zero calls to shared reset-and-refresh recovery. Require the atlas-recovery module to expose only explicit lifecycle entry points, then verify paste recovery. Completed settled tab-reveal repaint is not verified by the remaining unit evidence. Dispatch a visible document visibilitychange and require atlas-preserving wake recovery. Separately, drive an Electron visibility cycle with two real WebGL panes, require zero atlas clears, and retain at least 85% of each pane's baseline ink pixels.", + "oracle": "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3349 retires the whole terminal-render-desync-sentinel suite, including the same-cells persistence/recovery alarm, without equivalent replacement. Its unit command selector, test-file selector and assertion reference are removed prospectively. Earlier global-effects/window-wake retirements and the retired dated sentinel receipt remain historical verbatim. Two unrelated macOS document-visibility E2E receipts remain verbatim; the frozen static closure does not select changed tests through their literal roots. No fresh GPU/rendered UI, runtime, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3335 retires the complete mocked window-wake recovery suite (11 authored registrations/12 expanded cases), intentionally losing fullscreen atlas-preservation, wake callback ordering, deferred-DPR deduplication/repair and private frame-budget alarms without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/GPU/focus, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: recovers visible terminal rendering and input when the window regains focus — Whole suite: fake React useEffect immediately invokes bodies and ignores cleanup/deps; fake useRef/store hooks plus mocked pane manager only assert callback choreography. Does not exercise window focus, actual input or pixels. Retires focus wake wiring alarm.; clears WebGL texture atlases when the OS resumes — Whole suite: same fake-hook harness invokes captured OS resume callback and counts mocked atlas-clear/repaint methods. No GPU, actual OS resume, or real hook lifetime. Retires atlas clear wiring alarm.; preserves WebGL texture atlases when the active terminal document becomes visible — Whole suite: direct fake document visibility listener and mock-call absence/presence under fake hooks cannot establish real WebGL preservation or cleanup. Retires visibility wake wiring alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Parse foreground renderer-risk, synchronized, hidden, and alternate-screen PTY output and require pane-local refresh where needed with zero calls to shared reset-and-refresh recovery. Require the atlas-recovery module to expose only explicit lifecycle entry points, then verify paste recovery. Completed settled tab-reveal repaint is not verified by the remaining unit evidence. Dispatch a visible document visibilitychange and require atlas-preserving wake recovery. Separately, drive an Electron visibility cycle with two real WebGL panes, require zero atlas clears, and retain at least 85% of each pane's baseline ink pixels.", "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts", "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1" ], - "testFiles": [ - "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts", - "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts", - "tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts" - ], + "testFiles": ["tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts"], "assertionRefs": [ - { - "file": "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts", - "assertions": ["keeps hidden synchronized output off the global atlas recovery path"] - }, { "file": "tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts", "assertions": [ @@ -12056,7 +12020,8 @@ "Audit3349 retires the whole terminal-render-desync-sentinel suite, including the same-cells persistence/recovery alarm, without equivalent replacement. Its unit command selector, test-file selector and assertion reference are removed prospectively. Earlier global-effects/window-wake retirements and the retired dated sentinel receipt remain historical verbatim. Two unrelated macOS document-visibility E2E receipts remain verbatim; the frozen static closure does not select changed tests through their literal roots. No fresh GPU/rendered UI, runtime, historical-import, mobile, mixed-version or cross-platform validation is claimed.", "Audit3349 historical original commands object, preserved verbatim; retired source claims are not active evidence or replacement coverage:\n\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/render-health/terminal-render-desync-sentinel.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts\"", "Audit3349 historical original testFiles object, preserved verbatim; retired source claims are not active evidence or replacement coverage:\n\"src/renderer/src/components/terminal-pane/render-health/terminal-render-desync-sentinel.test.ts\"", - "Audit3349 historical original assertionRefs object, preserved verbatim; retired source claims are not active evidence or replacement coverage:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/render-health/terminal-render-desync-sentinel.test.ts\",\n \"assertions\": [\"persists and recovers after the same cells stay missing twice\"]\n }" + "Audit3349 historical original assertionRefs object, preserved verbatim; retired source claims are not active evidence or replacement coverage:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/render-health/terminal-render-desync-sentinel.test.ts\",\n \"assertions\": [\"persists and recovers after the same cells stay missing twice\"]\n }", + "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts\",\n \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n ]\ntestFiles: [\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts\",\n \"tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"assertions\": [\"keeps hidden synchronized output off the global atlas recovery path\"]\n },\n {\n \"file\": \"tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts\",\n \"assertions\": [\n \"preserves the WebGL atlas and keeps terminal text painted after document visibility resumes\"\n ]\n }\n ]" ], "demotionRule": "Demote if ordinary PTY output re-enters shared reset/refresh recovery, pane-local redraw coverage regresses, ordinary visibility clears the atlas, real WebGL pixels regress, or the focused Electron test cannot remain deterministic." }, @@ -12405,14 +12370,14 @@ "providers": ["local", "remote-runtime", "ssh"], "coveredPlatforms": ["macos", "linux"], "coveredProviders": ["local", "remote-runtime", "ssh"], - "coverageNotes": "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1516 removes package-electron-runtime-contract.test.mjs, a copied release-workflow platform and marker matrix. Its workflow wiring alarm is intentionally retired; no actual packaged watcher delivery was exercised and no equivalent replacement is claimed. Unaffected dated execution receipts retain their original scope; changed optional selectors have no fresh full-gate execution result. This audit removes the paired-web stopped-during-outage and late-ready direct-branch examples. The retained pre-ready cancellation, failed-unwatch retry and replay-continuity cases are not equivalent replacements for those ordering alarms. Current web-runtime-client.test.ts assertions below name only its retained pre-ready callback case; replay cases remain in their separate suite. Historical commands and results remain historical. Deterministic tests cover one shared healthy child per runtime process plus at most four bounded fault-quarantine children, native desktop, paired-runtime, and WSL snapshot processes sharing the same eight-physical-child reservation with typed serialized event-driven capacity recovery, including recursive re-wait when crash recovery reclaims an announced slot, one quarantine attempt per watch lifetime, generation-scoped cancellation, bounded termination with removable deadline waiters, replacement-crawl errors that cannot be blessed by a late readiness ack, pre-ready paired-web cancellation registered before an unbounded capacity wait, already-resolved and late physical-exit retry of a rejected paired-web teardown, physical desktop-install and local/SSH PTY teardown, stale-generation rejection, per-child stat bounds, final-overflow RPC delivery, and renderer eviction before terminal callbacks can retry. Destructive local and SSH removal fences both ID-derived and resolved-cwd terminal roots, including sibling-root/cwd combinations with reverse admission rollback, closes descendant relay watches before parent deletion, enumerates authoritative provider/cwd ownership, falls back to daemon spawn cwd before OSC 7, and keeps daemon/relay immediate shutdown pending until native exit or a bounded fail-closed error; a dead relay PID discovered during attach also settles concurrent shutdown before its stale entry is reaped, while Windows runtime watcher deadlines retain one removable physical-close waiter, treat Node's error-close path as positive physical-exit proof, and clear root ownership on late close. The relay policy test maps a standard repository's base, Git common directory, and worktree roots to one healthy supervisor, then proves a shared-child failure recovers those roots in separate quarantine supervisors with overflow and resumed events. Abortable capacity, quarantine, runtime-root, relay, SSH, and relay pre-install setup waits attach one reaction to each shared promise and explicitly remove 10,000 cancelled caller closures while one anchor remains. Built-entry macOS harnesses kill the desktop/runtime and SSH relay watcher children, then require automatic resubscription and later events while the host process and relay PTY survive. SSH bundles the child boundary beside relay.js, requires both artifacts for install completeness, and preserves registration-owned same-root cancellation. The test-value audit corrects the active renderer watch command/file reference to the existing runtime-file-client-watch.test.ts, whose three cases are retained unchanged. They observe synthetic subscription retry/fanout and unsubscribe/unwatch calls, not actual preload/main bookkeeping or physical watcher-process cleanup. The separate read/preview client suite loses forwarding, supplied-error and negative-only examples, retaining binary detection and Unicode SVG decoding. Historical evidence commands/results are unchanged. Test-value audit1293 removes src/main/providers/local-pty/local-pty-provider-session-inventory.test.ts (2 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/workspaces/removal/watcher-removal-gate.test.ts reduced. Loses exact removal-error compatibility with renderer predicate under shared message constants. Kept public refusal outcomes do not establish that renderer classification. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1516 removes package-electron-runtime-contract.test.mjs, a copied release-workflow platform and marker matrix. Its workflow wiring alarm is intentionally retired; no actual packaged watcher delivery was exercised and no equivalent replacement is claimed. Unaffected dated execution receipts retain their original scope; changed optional selectors have no fresh full-gate execution result. This audit removes the paired-web stopped-during-outage and late-ready direct-branch examples. The retained pre-ready cancellation, failed-unwatch retry and replay-continuity cases are not equivalent replacements for those ordering alarms. Current web-runtime-client.test.ts assertions below name only its retained pre-ready callback case; replay cases remain in their separate suite. Historical commands and results remain historical. Deterministic tests cover one shared healthy child per runtime process plus at most four bounded fault-quarantine children, native desktop, paired-runtime, and WSL snapshot processes sharing the same eight-physical-child reservation with typed serialized event-driven capacity recovery, including recursive re-wait when crash recovery reclaims an announced slot, one quarantine attempt per watch lifetime, generation-scoped cancellation, bounded termination with removable deadline waiters, replacement-crawl errors that cannot be blessed by a late readiness ack, pre-ready paired-web cancellation registered before an unbounded capacity wait, already-resolved and late physical-exit retry of a rejected paired-web teardown, physical desktop-install and local/SSH PTY teardown, stale-generation rejection, per-child stat bounds, final-overflow RPC delivery, and renderer eviction before terminal callbacks can retry. Destructive local and SSH removal fences both ID-derived and resolved-cwd terminal roots, including sibling-root/cwd combinations with reverse admission rollback, closes descendant relay watches before parent deletion, enumerates authoritative provider/cwd ownership, falls back to daemon spawn cwd before OSC 7, and keeps daemon/relay immediate shutdown pending until native exit or a bounded fail-closed error; a dead relay PID discovered during attach also settles concurrent shutdown before its stale entry is reaped, while Windows runtime watcher deadlines retain one removable physical-close waiter, treat Node's error-close path as positive physical-exit proof, and clear root ownership on late close. The relay policy test maps a standard repository's base, Git common directory, and worktree roots to one healthy supervisor, then proves a shared-child failure recovers those roots in separate quarantine supervisors with overflow and resumed events. Abortable capacity, quarantine, runtime-root, relay, SSH, and relay pre-install setup waits attach one reaction to each shared promise and explicitly remove 10,000 cancelled caller closures while one anchor remains. Built-entry macOS harnesses kill the desktop/runtime and SSH relay watcher children, then require automatic resubscription and later events while the host process and relay PTY survive. SSH bundles the child boundary beside relay.js, requires both artifacts for install completeness, and preserves registration-owned same-root cancellation. The test-value audit corrects the active renderer watch command/file reference to the existing runtime-file-client-watch.test.ts, whose three cases are retained unchanged. They observe synthetic subscription retry/fanout and unsubscribe/unwatch calls, not actual preload/main bookkeeping or physical watcher-process cleanup. The separate read/preview client suite loses forwarding, supplied-error and negative-only examples, retaining binary detection and Unicode SVG decoding. Historical evidence commands/results are unchanged. Test-value audit1293 removes src/main/providers/local-pty/local-pty-provider-session-inventory.test.ts (2 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/workspaces/removal/watcher-removal-gate.test.ts reduced. Loses exact removal-error compatibility with renderer predicate under shared message constants. Kept public refusal outcomes do not establish that renderer classification. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/5308", "https://github.com/stablyai/orca/issues/7547", "https://github.com/stablyai/orca/issues/8212" ], "invariant": "Local runtime and SSH relay roots share one watcher child per host process while healthy and use at most four quarantine children after shard failure; native desktop, paired-runtime, and direct WSL snapshot children consume the same process-wide eight-child reservation and retry transient exhaustion without permanently disabling a root. Cancellation remains owned by its child generation and settles only after acknowledgement or bounded physical exit; paired-web retains cleanup ownership and can cancel before readiness even while capacity is exhausted, retries a failed unwatch after already-resolved or late physical exit without duplicating stream termination, replacements never overlap a still-retiring generation, and aborted or timed-out callers detach immediately even while queued behind same-root relay teardown. Destructive local and SSH cleanup holds one containment-aware watcher/terminal removal fence through descendant watcher and PTY physical exit plus parent Git/filesystem deletion; daemon and relay kill requests retain ownership until the actual subprocess exit callback or an equivalent positive dead-PID proof and propagate rejected signals or a bounded failure otherwise. A crash-fused shared shard moves affected roots into the bounded quarantine pool, a second fused quarantine ends those watch lifetimes, interrupted setup emits overflow after recovery, metadata work stays bounded, and the SSH relay, PTYs, Git, and other filesystem operations never load the watcher native addon or share its fault boundary.", - "oracle": "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Fill the global watcher-child reservation, require native desktop, paired-runtime, and WSL setup to retain typed transient capacity and retry after one serialized release, then cancel pending desktop and paired-client watches and require no retry. Hold one live anchor while aborting 10,000 callers at the capacity, quarantine-assignment, runtime-root, relay-setup, and SSH-registration layers; require exactly one explicit waiter and one base-promise reaction to remain, then zero after settlement. Hold an old relay unsubscribe, queue one same-root setup leader and one anchor, then abort 10,000 joiners; require every cancellation to settle before teardown releases, exactly one anchor waiter, and only one later physical install. Advance the former paired-web callback deadline while capacity remains full, require cancellation ownership to stay live, publish the server token before ready, and require files.unwatch to abort setup before a later slot release can install a native root. Reject the first ready-watch unwatch with a physical-exit promise, resolve that exit later, and require a fresh physical unwatch attempt, registry release, and exactly one stream end. Fill one healthy shared child with multiple roots, map a standard SSH repository's base, Git common directory, and worktree roots to one relay supervisor, then inject IPC disconnect-before-exit, queued and active cancellation, operations during termination, kill-without-exit, repeated unkillable generations, initial and recovery timeouts, and shard failure. During local and SSH deletion, attempt a late terminal spawn whose worktree identity and cwd name different roots, enumerate a non-prefix remote PTY by authoritative worktree ownership, withhold daemon/relay exit callbacks, make attach positively prove a concurrent-shutdown PID dead, and make the provider unavailable; require every acquired admission to roll back on rejection, dead-PID proof to settle physical exit before reaping, timeout to retain ownership, and Git/filesystem deletion never to start. Require bounded watcher process count, physical-exit settlement, healthy-root recovery, stale-generation rejection, overflow plus later events, and fail-closed destructive cleanup. Verify relay build hashes and remote install probes require both relay.js and relay-watcher.js. Launch the built relay with a real PTY and Parcel watch, kill only the watcher child, and require the same relay PID and PTY to answer before a replacement child delivers overflow and a post-crash event.", + "oracle": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts: delivers remote file changes to listeners for the same worktree. src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/mobile-session-tabs-part-14.spec'). src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-03.spec.ts: arms the stale-title timer for a seeded working title; arms the Command Code scrape from the noted spawn command; prefers the tracked title over a stale renderer lastTitle in the hydration seed; writes recent output into the current runtime output map; uses a later title handler replacement with the runtime receiver; calls the current injected listener with the runtime receiver; keeps optional reconciliation lazy after its callback is removed. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-14.spec.ts: lists them, so a paired client can mirror a migrated editor; closes one by retiring it from the host session; keeps an unsaved draft unless the close is forced; shares aggregate work but leaves a replacement pending promise alone; lets a targeted refresh finish while an aggregate refresh waits; refuses a close when the store lacks %s before the guard; keeps a later missing %s on the original caught failure path. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/runtime/files/watching/runtime-file-client-watch.test.ts\",\n \"assertions\": [\n \"terminal watcher error and setup failure evict the shared entry before retrying callbacks run\",\n \"an old stream end cannot evict the replacement stream, which still delivers to its listener\",\n \"two same-worktree listeners share a synthetic subscription until the final stop unsubscribes and sends unwatch\"\n ]\n } Historical prior account (preserved verbatim): Audit1973: Delete the standalone mocked watcher cleanup suite and its entire sole-file prospective command. Retire the removed file-command transport-abort alias; preserve the independent cancellation suite and final-overflow/error/end cleanup callback, and13 unrelated receipt objects. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial runtime files-watch suite retains controlled Windows close-event waiting, shared-client survival, late physical-exit ownership/deadline cleanup and shutdown joining. Its combined Windows close/deadline/late-exit alias remains backed by unchanged callbacks. Retire native-error-close, pre-publication setup ownership and failed-delete rearm aliases; associated delegation, failure forwarding, removal routing and recovery examples are lost. These tests inject watch/subscription seams and do not observe an actual native watcher or physical process. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Partial runtime watcher-host suite loses mocked option/event/overflow/resubscription forwarding, supplied teardown-error propagation, aborted-signal/no-call and private ten-thousand-waiter-count inventories. Retire the 10,000-caller bound and failed-recovery-subscriber-ending assertion aliases. Keep same-root owner cancellation, pre-ready replacement, held root-close join, stale-generation recovery delivery and initial failed-root ownership mappings backed by retained real-host callbacks with injected subscription/error/physical-exit promises. No actual native watcher, process termination or resource bound was observed. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Fill the global watcher-child reservation, require native desktop, paired-runtime, and WSL setup to retain typed transient capacity and retry after one serialized release, then cancel pending desktop and paired-client watches and require no retry. Hold one live anchor while aborting 10,000 callers at the capacity, quarantine-assignment, runtime-root, relay-setup, and SSH-registration layers; require exactly one explicit waiter and one base-promise reaction to remain, then zero after settlement. Hold an old relay unsubscribe, queue one same-root setup leader and one anchor, then abort 10,000 joiners; require every cancellation to settle before teardown releases, exactly one anchor waiter, and only one later physical install. Advance the former paired-web callback deadline while capacity remains full, require cancellation ownership to stay live, publish the server token before ready, and require files.unwatch to abort setup before a later slot release can install a native root. Reject the first ready-watch unwatch with a physical-exit promise, resolve that exit later, and require a fresh physical unwatch attempt, registry release, and exactly one stream end. Fill one healthy shared child with multiple roots, map a standard SSH repository's base, Git common directory, and worktree roots to one relay supervisor, then inject IPC disconnect-before-exit, queued and active cancellation, operations during termination, kill-without-exit, repeated unkillable generations, initial and recovery timeouts, and shard failure. During local and SSH deletion, attempt a late terminal spawn whose worktree identity and cwd name different roots, enumerate a non-prefix remote PTY by authoritative worktree ownership, withhold daemon/relay exit callbacks, make attach positively prove a concurrent-shutdown PID dead, and make the provider unavailable; require every acquired admission to roll back on rejection, dead-PID proof to settle physical exit before reaping, timeout to retain ownership, and Git/filesystem deletion never to start. Require bounded watcher process count, physical-exit settlement, healthy-root recovery, stale-generation rejection, overflow plus later events, and fail-closed destructive cleanup. Verify relay build hashes and remote install probes require both relay.js and relay-watcher.js. Launch the built relay with a real PTY and Parcel watch, kill only the watcher child, and require the same relay PID and PTY to answer before a replacement child delivers overflow and a post-crash event.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/shared/promise-settlement-waiters.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot", @@ -12862,7 +12827,11 @@ "Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope.", "Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope.", "Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope.", - "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes." + "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes.", + "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/shared/promise-settlement-waiters.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/shared/physical-exit-tracker.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts src/main/ipc/worktrees-delete-pty-teardown.test.ts src/main/ipc/worktrees-orphan-directory-cleanup.test.ts src/main/ipc/worktrees-remove-preflight.test.ts src/main/workspaces/removal/watcher-removal-gate.test.ts src/main/runtime/files/watch/orca-runtime-files-watch.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/methods/files/files.test.ts src/renderer/src/web/web-runtime-client.test.ts src/shared/cross-platform-path.test.ts\",\n \"pnpm run build:electron-vite\",\n \"node config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-resource-probe.mjs\",\n \"node config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-fault-harness.mjs\",\n \"ELECTRON_RUN_AS_NODE=1 pnpm exec electron config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-fault-harness.mjs\",\n \"pnpm exec vitest run --config config/vitest.config.ts\"\n ]\ntestFiles: [\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts\",\n \"src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts\",\n \"src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts\",\n \"src/main/ipc/filesystem/watcher-process/parcel-watcher-child-launch.test.ts\",\n \"src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts\",\n \"src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts\",\n \"src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts\",\n \"src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts\",\n \"src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts\",\n \"src/main/ipc/filesystem/watcher-process/parcel-watcher-event-delivery.test.ts\",\n \"src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts\",\n \"src/main/ipc/filesystem/watchers/filesystem-watcher-wsl.test.ts\",\n \"src/main/ipc/worktrees-delete-pty-teardown.test.ts\",\n \"src/main/ipc/worktrees-orphan-directory-cleanup.test.ts\",\n \"src/main/ipc/worktrees-remove-preflight.test.ts\",\n \"src/main/workspaces/removal/watcher-removal-gate.test.ts\",\n \"src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts\",\n \"src/main/providers/local-pty/local-pty-provider-shutdown.test.ts\",\n \"src/main/daemon/pty-subprocess/testing/pty-subprocess.test.ts\",\n \"src/main/daemon/sessions/testing/session.test.ts\",\n \"src/main/daemon/terminal-host/testing/terminal-host.test.ts\",\n \"src/main/daemon/terminal-host/testing/terminal-host-session-reaping-leak.test.ts\",\n \"src/main/runtime/files/watch/orca-runtime-files-watch.test.ts\",\n \"src/main/runtime/workspaces/removal/worktree-teardown.test.ts\",\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/main/runtime/rpc/methods/files/files.test.ts\",\n \"src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts\",\n \"src/renderer/src/web/web-runtime-client.test.ts\",\n \"src/shared/cross-platform-path.test.ts\",\n \"src/shared/physical-exit-tracker.test.ts\",\n \"src/shared/promise-settlement-waiters.test.ts\",\n \"config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-fault-harness.mjs\",\n \"config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-resource-probe.mjs\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/main/ipc/filesystem/watchers/filesystem-watcher.test.ts\",\n \"assertions\": [\n \"a transient WSL child-capacity rejection automatically retries on release and renderer unwatch cancels the wait\",\n \"failed SSH worktree removal restores every live renderer listener, emits overflow, and resumes precise events\"\n ]\n },\n {\n \"file\": \"src/main/ipc/filesystem/watchers/filesystem-watcher-native-capacity.test.ts\",\n \"assertions\": [\n \"typed native child-capacity exhaustion automatically retries after a serialized slot release\",\n \"renderer unwatch cancels a pending native capacity retry before subscription restarts\"\n ]\n },\n {\n \"file\": \"src/main/ipc/filesystem/watcher-process/parcel-watcher-child-registry.test.ts\",\n \"assertions\": [\n \"capacity notification closes the release-before-listen race and serializes reserving waiters per released slot\"\n ]\n },\n {\n \"file\": \"src/shared/physical-exit-tracker.test.ts\",\n \"assertions\": [\n \"timed-out physical-exit waiters detach while active and later retries still settle on exact exit\"\n ]\n },\n {\n \"file\": \"src/shared/promise-settlement-waiters.test.ts\",\n \"assertions\": [\n \"an actual timed-out waiter rejects while a remaining waiter resolves and pending timers are cleared on settlement\",\n \"an already-aborted caller rejects and invokes its ownership-abandon callback\"\n ]\n },\n {\n \"file\": \"src/main/ipc/filesystem/watcher-process/parcel-watcher-process.test.ts\",\n \"assertions\": [\n \"initial-subscribe crashes complete with an interruption refresh\",\n \"watch errors before readiness reject setup and physically cancel the native crawl\",\n \"watch errors during replacement crawl terminate recovery and a late readiness ack cannot revive the failed root\",\n \"IPC disconnect recovery restores every existing root before accepting new setup\",\n \"queued abort removes one request without restarting healthy roots, while active abort or crawl-scoped timeout restores the shard\",\n \"a crash-resubscribe crawl deadline and concurrent unsubscribe settle only after physical shard exit, or report physical-exit failure at the termination deadline\",\n \"a close-only asynchronous spawn failure settles physical termination without waiting for the exit deadline\",\n \"production runtime-pool disposal rejects later subscriptions without forking an overlapping child\",\n \"missing built entries fail closed\"\n ]\n },\n {\n \"file\": \"src/main/ipc/filesystem/watcher-process/parcel-watcher-unsubscribe-timeout.test.ts\",\n \"assertions\": [\n \"a canary-independent native-unsubscribe deadline restarts the shard and restores healthy siblings after physical child exit\",\n \"an unkillable child rejects the native unsubscribe with its retained physical-exit promise only at the bounded exit deadline\"\n ]\n },\n {\n \"file\": \"src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-capacity.test.ts\",\n \"assertions\": [\n \"one released physical slot launches one shared supervisor child for every waiting root, while partial/all cancellation and disposal remove the shared capacity barrier\",\n \"a waiter recursively re-enters the event-driven barrier when crash recovery reclaims its announced slot\"\n ]\n },\n {\n \"file\": \"src/main/ipc/filesystem/watcher-process/parcel-watcher-disconnect-termination.test.ts\",\n \"assertions\": [\n \"pending-crawl cancellation after disconnect remains pending until the exact child exits\",\n \"ready and pending-crawl cancellation force disconnected-child exit even while a healthy sibling root remains\",\n \"a cancellation deadline joins active disconnect termination without duplicate sibling resubscription\",\n \"an exit-deadline failure replaces the early cancellation and remains visible to synchronous unsubscribe until physical exit\"\n ]\n },\n {\n \"file\": \"src/main/ipc/filesystem/watcher-process/runtime-watcher-pending-assignment.test.ts\",\n \"assertions\": [\n \"10,000 cancelled quarantine-assignment callers leave exactly one live anchor and zero waiters after grant\",\n \"an already-aborted first caller synchronously releases pending assignment ownership\"\n ]\n },\n {\n \"file\": \"src/main/ipc/filesystem/watchers/filesystem-watcher-local-unsubscribe.test.ts\",\n \"assertions\": [\n \"worktree deletion physically aborts pending native setup and settles before its crawl resolves\",\n \"a cancelled pending install retains physical-exit failure across an immediate second destructive close\",\n \"desktop terminal failure remains root-owned even when the cleared subscription later unsubscribes cleanly\",\n \"Windows event payloads retain the physical root spelling instead of the comparison key\",\n \"failed local worktree removal restores every live renderer listener and emits overflow\"\n ]\n },\n {\n \"file\": \"src/main/runtime/files/watch/orca-runtime-files-watch.test.ts\",\n \"assertions\": [\n \"Windows runtime cleanup waits for the native close event, fails closed at a bounded deadline, and clears retained ownership on late close without retry listeners\"\n ]\n },\n {\n \"file\": \"src/main/runtime/workspaces/removal/worktree-teardown.test.ts\",\n \"assertions\": [\n \"overlapping runtime, provider, and registry sweeps stay behind one physical PTY-stop promise\",\n \"destructive teardown rejects instead of releasing deletion when physical stop misses its deadline\",\n \"cwd-owned and floating PTYs are swept while legacy rows without cwd retain prefix ownership\",\n \"remote provider enumeration matches authoritative worktree ownership without touching the local-only registry\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/files/files.test.ts\",\n \"assertions\": [\n \"terminal watcher loss flushes a final overflow change before error/end and unregisters cleanup\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts\",\n \"assertions\": [\n \"the server publishes a cleanup token before ready and files.unwatch aborts pending setup without delivering queued crawl events\"\n ]\n },\n {\n \"file\": \"src/shared/cross-platform-path.test.ts\",\n \"assertions\": [\n \"POSIX literal backslashes preserve containment and relative identity\",\n \"Windows drive and UNC roots enforce containment\",\n \"WSL Linux-tail comparisons remain case-sensitive and relative suffix bytes remain exact\"\n ]\n },\n {\n \"file\": \"src/renderer/src/web/web-runtime-client.test.ts\",\n \"assertions\": [\n \"a stopped pre-ready paired-web watch retains its callback beyond the former deadline and uses the early server token to unwatch\"\n ]\n },\n {\n \"file\": \"config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-resource-probe.mjs\",\n \"assertions\": [\n \"five healthy roots share one exact watcher PID within the per-child RSS budget\",\n \"four quarantine roots use exactly four child PIDs and remain within the global eight-child reservation cap\",\n \"CPU and RSS are sampled for every exact child PID and every PID exits during cleanup\",\n \"per-child and aggregate RSS and sampled CPU ceilings fail the probe before the physical child cap can hide excess resource use\"\n ]\n },\n {\n \"file\": \"config/scripts/diagnostics/runtime-watchers/runtime-file-watcher-fault-harness.mjs\",\n \"assertions\": [\n \"the built watcher entry delivers an event before fault injection\",\n \"the harness parent survives watcher-child SIGSEGV\",\n \"the real supervisor automatically replaces the child, resubscribes, and delivers a post-crash event\"\n ]\n }\n ]", + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged.", + "Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. All previous note strings, dated receipts, archived raw receipts and prior gap entries retain their original scopes.", + "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. All earlier notes and dated/archived evidence retain original scopes." ], "demotionRule": "Demote or quarantine if the fault harness flakes without a product or harness bug, if healthy operation exceeds one runtime watcher child, if total physical operation exceeds eight children including retiring generations, if quarantine children outlive their roots or repeat after fusing, if event delivery becomes unbounded, or if metadata/stat work returns to the serve process." }, @@ -14099,10 +14068,10 @@ "providers": ["paired-runtime"], "coveredPlatforms": ["linux"], "coveredProviders": ["paired-runtime"], - "coverageNotes": "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1579 removes workflow/manifest/regex/private binary-header and diagnostic metric inventories, fixture selectors, injected forwarding/platform/signature/process examples, unproven overlap and internal churn counters without equivalent replacement coverage. Retains actual Git trust/diffs; filesystem hash/ELF-region/native discovery; child CLI module repair; compiler/lock/publication/rollback and synthetic Electron install/cache ownership; executable shell quoting/exit; controlled notary/timer cleanup; local patched extractor file/AST freshness; real Chromium/WebKit CSP/sandbox/HTTPS image/referrer/link/preservation controls under parsed Android headers. Five unchanged setup-pnpm/VM request-cleanup definitions reviewed and not rerun. GitHub, installer/archive, OS metric, client, native delegate, compressor, builder and Apple boundaries injected or absent where recorded. No actual native PTY, shipped full/native app, real Actions/cache/npm signature authority, downloaded Electron archive, real objdump/linker/native CLI/AppImage, signing/NSIS/notary/upload/updater or live freeze proof. Historical scope before this audit: Published Linux 1.4.188 desktop against current source in both directions; scheduled weekly and manually runnable. No required PR check.", + "coverageNotes": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1579 removes workflow/manifest/regex/private binary-header and diagnostic metric inventories, fixture selectors, injected forwarding/platform/signature/process examples, unproven overlap and internal churn counters without equivalent replacement coverage. Retains actual Git trust/diffs; filesystem hash/ELF-region/native discovery; child CLI module repair; compiler/lock/publication/rollback and synthetic Electron install/cache ownership; executable shell quoting/exit; controlled notary/timer cleanup; local patched extractor file/AST freshness; real Chromium/WebKit CSP/sandbox/HTTPS image/referrer/link/preservation controls under parsed Android headers. Five unchanged setup-pnpm/VM request-cleanup definitions reviewed and not rerun. GitHub, installer/archive, OS metric, client, native delegate, compressor, builder and Apple boundaries injected or absent where recorded. No actual native PTY, shipped full/native app, real Actions/cache/npm signature authority, downloaded Electron archive, real objdump/linker/native CLI/AppImage, signing/NSIS/notary/upload/updater or live freeze proof. Historical scope before this audit: Published Linux 1.4.188 desktop against current source in both directions; scheduled weekly and manually runnable. No required PR check.", "motivatingLinks": ["https://github.com/stablyai/orca/actions/runs/34069063016"], "invariant": "A paired client and host without client-hosted browser capabilities retain server-hosted browser placement across supported version skew.", - "oracle": "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Require both existing named browser placement scenarios to pass three times with one attempt, zero skips, zero failures, and no report errors.", + "oracle": "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Require both existing named browser placement scenarios to pass three times with one attempt, zero skips, zero failures, and no report errors.", "commands": [ "gh workflow run packaged-browser-e2e.yml", "pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project=electron-headless --workers=1 --repeat-each=3 --retries=0", @@ -14200,7 +14169,11 @@ "Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope.", "Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope.", "Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope.", - "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes." + "Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes.", + "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"gh workflow run packaged-browser-e2e.yml\",\n \"pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project=electron-headless --workers=1 --repeat-each=3 --retries=0\",\n \"gh run view 34069063016 --log\",\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=2 --reporter=dot\"\n ]\ntestFiles: [\"tests/e2e/packaged-mixed-version-browser-placement.spec.ts\"]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/packaged-mixed-version-browser-placement.spec.ts\",\n \"assertions\": [\n \"old client and old host lack client-host and browser-tunnel capabilities\",\n \"browser contents remain owned by the server and the expected snapshot marker is readable\"\n ]\n }\n ]", + "Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Original scope text is retained as the exact suffix of coverageNotes/oracle; historical evidence is unchanged.", + "Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. All previous note strings, dated receipts, archived raw receipts and prior gap entries retain their original scopes.", + "Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. All earlier notes and dated/archived evidence retain original scopes." ], "demotionRule": "Keep experimental if any direction skips or fails; do not extend timeouts or retry to green." }, @@ -14282,12 +14255,12 @@ "providers": ["relay"], "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Audit1572 removes relay predicate/threshold tables, telemetry and route/schema inventories, fake-socket forwarding and simulator-owned diagnostic paths without equivalent replacement claims. Retained production admission queues, placer/reserve-book simulations, reservation lifecycles, bounded Response streams, last-known-good flag state, poller reachability, configuration safety and ledger fences are validated with supplied clocks, network, identity, SQL and socket boundaries. No deployed cell, live Google metadata/storage, PostgreSQL, real socket handshake or authorization proof. Historical scope before this audit: Actual registry queue with controlled store latency plus local WebSocket proof and connection-capacity suites on macOS. No PostgreSQL or live remote host run. PTY, daemon, SSH process state, WSL execution and folder/git workspace behavior are unaffected.", + "coverageNotes": "Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Cloud relay source review intentionally retires95assignment-store examples,23real-process blackbox variants,22headroom examples,17conditionalPostgreSQL examples and25isolated-cell replacement examples. Retain3assignment-store,7blackbox,1headroom,2PostgreSQL and1isolated-cell rollback/log positive-control cases. Two PostgreSQL cases remain conditional on ORCA_RELAY_TEST_POSTGRES_URL; timing-sensitive <300ms threshold remains. These gates already have no active selectors/evidence and protection none; historical receipts remain historical. Audit1572 removes relay predicate/threshold tables, telemetry and route/schema inventories, fake-socket forwarding and simulator-owned diagnostic paths without equivalent replacement claims. Retained production admission queues, placer/reserve-book simulations, reservation lifecycles, bounded Response streams, last-known-good flag state, poller reachability, configuration safety and ledger fences are validated with supplied clocks, network, identity, SQL and socket boundaries. No deployed cell, live Google metadata/storage, PostgreSQL, real socket handshake or authorization proof. Historical scope before this audit: Actual registry queue with controlled store latency plus local WebSocket proof and connection-capacity suites on macOS. No PostgreSQL or live remote host run. PTY, daemon, SSH process state, WSL execution and folder/git workspace behavior are unaffected.", "motivatingLinks": [ "https://github.com/stablyai/orca/blob/main/cloud/apps/relay/src/connections/host-session-registry.ts" ], "invariant": "A closed queued transport starts no durable activation; an already-started activation retains cleanup, and a live successor becomes the indexed control without concurrent same-host activation.", - "oracle": "Queue a closed control before a live retry behind stalled persistence. With controlled 4s store calls, require two total activations, one release for the already-started closed control, and live readiness at 4s. Existing tests retain cleanup when closure happens during I/O.", + "oracle": "Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Cloud relay source review intentionally retires95assignment-store examples,23real-process blackbox variants,22headroom examples,17conditionalPostgreSQL examples and25isolated-cell replacement examples. Retain3assignment-store,7blackbox,1headroom,2PostgreSQL and1isolated-cell rollback/log positive-control cases. Two PostgreSQL cases remain conditional on ORCA_RELAY_TEST_POSTGRES_URL; timing-sensitive <300ms threshold remains. These gates already have no active selectors/evidence and protection none; historical receipts remain historical. Queue a closed control before a live retry behind stalled persistence. With controlled 4s store calls, require two total activations, one release for the already-started closed control, and live readiness at 4s. Existing tests retain cleanup when closure happens during I/O.", "commands": [], "testFiles": [], "assertionRefs": [], @@ -14311,7 +14284,8 @@ "knownGaps": [ "Audit1572 removes relay predicate/threshold tables, telemetry and route/schema inventories, fake-socket forwarding and simulator-owned diagnostic paths without equivalent replacement claims. Retained production admission queues, placer/reserve-book simulations, reservation lifecycles, bounded Response streams, last-known-good flag state, poller reachability, configuration safety and ledger fences are validated with supplied clocks, network, identity, SQL and socket boundaries. No deployed cell, live Google metadata/storage, PostgreSQL, real socket handshake or authorization proof.", "No real PostgreSQL contention benchmark or live remote host/physical mobile run.", - "Windows/Linux execution and CI soak are not recorded; queue cleanup after a never-settling predecessor remains unchanged." + "Windows/Linux execution and CI soak are not recorded; queue cleanup after a never-settling predecessor remains unchanged.", + "Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Cloud relay source review intentionally retires95assignment-store examples,23real-process blackbox variants,22headroom examples,17conditionalPostgreSQL examples and25isolated-cell replacement examples. Retain3assignment-store,7blackbox,1headroom,2PostgreSQL and1isolated-cell rollback/log positive-control cases. Two PostgreSQL cases remain conditional on ORCA_RELAY_TEST_POSTGRES_URL; timing-sensitive <300ms threshold remains. These gates already have no active selectors/evidence and protection none; historical receipts remain historical. All previous note strings, dated receipts, archived raw receipts and prior gap entries retain their original scopes." ], "promotionCriteria": [ "Retain red/green count and latency assertions; collect cross-platform and CI soak evidence." @@ -14330,10 +14304,10 @@ "providers": ["relay"], "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Audit1572 removes relay predicate/threshold tables, telemetry and route/schema inventories, fake-socket forwarding and simulator-owned diagnostic paths without equivalent replacement claims. Retained production admission queues, placer/reserve-book simulations, reservation lifecycles, bounded Response streams, last-known-good flag state, poller reachability, configuration safety and ledger fences are validated with supplied clocks, network, identity, SQL and socket boundaries. No deployed cell, live Google metadata/storage, PostgreSQL, real socket handshake or authorization proof. Historical scope before this audit: Actual assignment store and SQLite tests on macOS. No real PostgreSQL or live remote host/physical phone run. Local/daemon PTY, SSH execution ownership, WSL, folder/git workspace behavior and transport framing are unaffected. Audit1279 removes fake SQL lock-order receipts, diagnostic projections and mocked reserve callback cases from this selector. Their precise local alarms are intentionally lost; retained SQLite headroom/state checks are not claimed as equivalent replacements. The 2026-09-25 receipt is archived as historical data; the shortened selector has no fresh runtime result yet. The remaining six-file selector passed 164 cases on Linux after these removals; this fixture result is separate from the archived dated receipt and does not establish native PostgreSQL behavior. Audit1507 removes the mocked lock-counter suite from the active selector; the 2026-11-04 six-file receipt remains historical and does not validate the shortened five-file selector. Its direct mocked counter alarm is intentionally retired without replacement equivalence.", + "coverageNotes": "Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Cloud relay source review intentionally retires95assignment-store examples,23real-process blackbox variants,22headroom examples,17conditionalPostgreSQL examples and25isolated-cell replacement examples. Retain3assignment-store,7blackbox,1headroom,2PostgreSQL and1isolated-cell rollback/log positive-control cases. Two PostgreSQL cases remain conditional on ORCA_RELAY_TEST_POSTGRES_URL; timing-sensitive <300ms threshold remains. These gates already have no active selectors/evidence and protection none; historical receipts remain historical. Audit1572 removes relay predicate/threshold tables, telemetry and route/schema inventories, fake-socket forwarding and simulator-owned diagnostic paths without equivalent replacement claims. Retained production admission queues, placer/reserve-book simulations, reservation lifecycles, bounded Response streams, last-known-good flag state, poller reachability, configuration safety and ledger fences are validated with supplied clocks, network, identity, SQL and socket boundaries. No deployed cell, live Google metadata/storage, PostgreSQL, real socket handshake or authorization proof. Historical scope before this audit: Actual assignment store and SQLite tests on macOS. No real PostgreSQL or live remote host/physical phone run. Local/daemon PTY, SSH execution ownership, WSL, folder/git workspace behavior and transport framing are unaffected. Audit1279 removes fake SQL lock-order receipts, diagnostic projections and mocked reserve callback cases from this selector. Their precise local alarms are intentionally lost; retained SQLite headroom/state checks are not claimed as equivalent replacements. The 2026-09-25 receipt is archived as historical data; the shortened selector has no fresh runtime result yet. The remaining six-file selector passed 164 cases on Linux after these removals; this fixture result is separate from the archived dated receipt and does not establish native PostgreSQL behavior. Audit1507 removes the mocked lock-counter suite from the active selector; the 2026-11-04 six-file receipt remains historical and does not validate the shortened five-file selector. Its direct mocked counter alarm is intentionally retired without replacement equivalence.", "motivatingLinks": ["https://github.com/stablyai/orca/issues/23035"], "invariant": "A single-cell capacity check reads only that cell while retaining snapshot freshness, incarnation, outstanding reservation and missing-limit policy; new placement retains the full fleet inventory.", - "oracle": "With 32 capped cells, an existing active host stays on its pinned cell and reads one headroom row; new placement reads all 32. Missing, expired or prior-incarnation snapshots, capacity exhaustion and outstanding debt still refuse the active pinned host; an uncapped cell remains admissible.", + "oracle": "Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Cloud relay source review intentionally retires95assignment-store examples,23real-process blackbox variants,22headroom examples,17conditionalPostgreSQL examples and25isolated-cell replacement examples. Retain3assignment-store,7blackbox,1headroom,2PostgreSQL and1isolated-cell rollback/log positive-control cases. Two PostgreSQL cases remain conditional on ORCA_RELAY_TEST_POSTGRES_URL; timing-sensitive <300ms threshold remains. These gates already have no active selectors/evidence and protection none; historical receipts remain historical. With 32 capped cells, an existing active host stays on its pinned cell and reads one headroom row; new placement reads all 32. Missing, expired or prior-incarnation snapshots, capacity exhaustion and outstanding debt still refuse the active pinned host; an uncapped cell remains admissible.", "commands": [], "testFiles": [], "assertionRefs": [], @@ -14359,7 +14333,8 @@ "Real PostgreSQL query plan and concurrent admission not rerun for the scoped variant.", "Windows/Linux execution, live remote host/mobile flows and CI soak are not recorded.", "Historical receipt before Audit1279 selector removal; original command, currentCommand, counts and result are preserved as data and do not validate the shortened selector: {\"date\":\"2026-09-25\",\"runner\":\"local\",\"platform\":\"macos\",\"command\":\"ORCA_BACKGROUND_LAUNCH=1 pnpm --dir cloud/apps/relay exec vitest run ../../../cloud/apps/relay/src/assignment/assignment-headroom-scope.test.ts ../../../cloud/apps/relay/src/assignment/assignment-connection-headroom.test.ts ../../../cloud/apps/relay/src/assignment-store.test.ts ../../../cloud/apps/relay/src/assignment/assignment-store-lock-order.test.ts ../../../cloud/apps/relay/src/cell-inventory-lock-contention.test.ts ../../../cloud/apps/relay/src/assignment-isolated-cell-replacement.test.ts ../../../cloud/apps/relay/src/regional-rehome-target-selection.test.ts --silent=false\",\"currentCommand\":\"ORCA_BACKGROUND_LAUNCH=1 pnpm --dir cloud/apps/relay exec vitest run ../../../cloud/apps/relay/src/assignment/assignment-headroom-scope.test.ts ../../../cloud/apps/relay/src/assignment/assignment-connection-headroom.test.ts ../../../cloud/apps/relay/src/assignment/assignment-store.test.ts ../../../cloud/apps/relay/src/assignment/assignment-store-lock-order.test.ts ../../../cloud/apps/relay/src/cell-inventory-lock-contention.test.ts ../../../cloud/apps/relay/src/assignment/assignment-isolated-cell-replacement.test.ts ../../../cloud/apps/relay/src/regional-rehome-target-selection.test.ts --silent=false\",\"result\":\"passed\",\"durationSeconds\":0.513,\"summary\":\"189 tests across seven files passed; independent root rerun also passed189 tests. Relay typecheck passed separately.\"}", - "Historical receipt before Audit1507 selector removal; preserved as data, not proof of the current selector: {\"date\":\"2026-11-04\",\"runner\":\"local\",\"platform\":\"linux\",\"command\":\"ORCA_BACKGROUND_LAUNCH=1 pnpm --dir cloud/apps/relay test src/assignment/assignment-headroom-scope.test.ts src/assignment/assignment-connection-headroom.test.ts src/assignment/assignment-store.test.ts src/cell-inventory-lock-contention.test.ts src/assignment/assignment-isolated-cell-replacement.test.ts src/regional-rehome-target-selection.test.ts --silent=false --maxWorkers=2\",\"currentCommand\":\"ORCA_BACKGROUND_LAUNCH=1 pnpm --dir cloud/apps/relay exec vitest run ../../../cloud/apps/relay/src/assignment/assignment-headroom-scope.test.ts ../../../cloud/apps/relay/src/assignment/assignment-connection-headroom.test.ts ../../../cloud/apps/relay/src/assignment/assignment-store.test.ts ../../../cloud/apps/relay/src/cell/admission/cell-inventory-lock-contention.test.ts ../../../cloud/apps/relay/src/assignment/assignment-isolated-cell-replacement.test.ts ../../../cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-target-selection.test.ts --silent=false\",\"result\":\"passed\",\"durationSeconds\":2.22,\"summary\":\"164 tests passed across the six remaining headroom fixture suites on Linux through the relay package runner, including its schema/contract build hooks. This executes the current selector with two workers. It does not establish native PostgreSQL contention or transaction recovery coverage.\"}" + "Historical receipt before Audit1507 selector removal; preserved as data, not proof of the current selector: {\"date\":\"2026-11-04\",\"runner\":\"local\",\"platform\":\"linux\",\"command\":\"ORCA_BACKGROUND_LAUNCH=1 pnpm --dir cloud/apps/relay test src/assignment/assignment-headroom-scope.test.ts src/assignment/assignment-connection-headroom.test.ts src/assignment/assignment-store.test.ts src/cell-inventory-lock-contention.test.ts src/assignment/assignment-isolated-cell-replacement.test.ts src/regional-rehome-target-selection.test.ts --silent=false --maxWorkers=2\",\"currentCommand\":\"ORCA_BACKGROUND_LAUNCH=1 pnpm --dir cloud/apps/relay exec vitest run ../../../cloud/apps/relay/src/assignment/assignment-headroom-scope.test.ts ../../../cloud/apps/relay/src/assignment/assignment-connection-headroom.test.ts ../../../cloud/apps/relay/src/assignment/assignment-store.test.ts ../../../cloud/apps/relay/src/cell/admission/cell-inventory-lock-contention.test.ts ../../../cloud/apps/relay/src/assignment/assignment-isolated-cell-replacement.test.ts ../../../cloud/apps/relay/src/assignment/regional-rehome/regional-rehome-target-selection.test.ts --silent=false\",\"result\":\"passed\",\"durationSeconds\":2.22,\"summary\":\"164 tests passed across the six remaining headroom fixture suites on Linux through the relay package runner, including its schema/contract build hooks. This executes the current selector with two workers. It does not establish native PostgreSQL contention or transaction recovery coverage.\"}", + "Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Cloud relay source review intentionally retires95assignment-store examples,23real-process blackbox variants,22headroom examples,17conditionalPostgreSQL examples and25isolated-cell replacement examples. Retain3assignment-store,7blackbox,1headroom,2PostgreSQL and1isolated-cell rollback/log positive-control cases. Two PostgreSQL cases remain conditional on ORCA_RELAY_TEST_POSTGRES_URL; timing-sensitive <300ms threshold remains. These gates already have no active selectors/evidence and protection none; historical receipts remain historical. All previous note strings, dated receipts, archived raw receipts and prior gap entries retain their original scopes." ], "promotionCriteria": [ "Retain red/green row budget and semantic admission cases; collect PostgreSQL, cross-platform and CI soak evidence." diff --git a/config/repo-host-read-baseline.txt b/config/repo-host-read-baseline.txt index 4cb8d19327d..19d04c4aa1c 100644 --- a/config/repo-host-read-baseline.txt +++ b/config/repo-host-read-baseline.txt @@ -23,8 +23,8 @@ 1 src/main/ipc/worktrees/removal/register-worktree-removal-handlers.ts 1 src/main/ipc/worktrees/removal/registered-worktree-root-owner.ts 1 src/main/ipc/worktrees/repo-host-ownership.ts -2 src/main/orca-profiles/profile-project-transfer-payload.ts -1 src/main/orca-profiles/profile-project-worktree-identity.ts +2 src/main/orca-profiles/project-transfer/profile-project-transfer-payload.ts +1 src/main/orca-profiles/project-transfer/profile-project-worktree-identity.ts 1 src/main/persistence/leasing-ssh-ptys/ssh-target-reassignment.ts 1 src/main/persistence/migrating-orcad-catalog/orcad-source-ownership.ts 2 src/main/persistence/restoring-sessions/folder-scope-migration.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 2f905884e9a..55d1f7f5891 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -617,50 +617,42 @@ "src/main/agent-launch/trust/agent-trust-presets.test.ts": 377, "src/main/agent-launch/trust/agent-workspace-trust.test.ts": 177, "src/main/ai-vault-search/session-search-agent-compatibility.test.ts": 192, - "src/main/ai-vault-search/session-search-anonymous-write-memory.test.ts": 1570, - "src/main/ai-vault-search/session-search-content-hash.test.ts": 61, - "src/main/ai-vault-search/session-search-deleted-sources.test.ts": 675, - "src/main/ai-vault-search/session-search-dependent-transcripts.test.ts": 489, - "src/main/ai-vault-search/session-search-directory-listings.test.ts": 50, - "src/main/ai-vault-search/session-search-engine.test.ts": 2083, - "src/main/ai-vault-search/session-search-file-id.test.ts": 277, - "src/main/ai-vault-search/session-search-file-write.test.ts": 696, - "src/main/ai-vault-search/session-search-fts5-contract.test.ts": 183, - "src/main/ai-vault-search/session-search-hit-ranking.test.ts": 58, + "src/main/ai-vault-search/discovery/session-search-deleted-sources.test.ts": 675, + "src/main/ai-vault-search/indexing/session-search-dependent-transcripts.test.ts": 489, + "src/main/ai-vault-search/discovery/session-search-directory-listings.test.ts": 50, + "src/main/ai-vault-search/query/session-search-engine.test.ts": 2083, + "src/main/ai-vault-search/storage/session-search-file-write.test.ts": 696, + "src/main/ai-vault-search/query/session-search-hit-ranking.test.ts": 58, "src/main/ai-vault-search/session-search-host-registration.test.ts": 1140, - "src/main/ai-vault-search/session-search-index-consumer.test.ts": 316, - "src/main/ai-vault-search/session-search-index-generation.test.ts": 471, - "src/main/ai-vault-search/session-search-index-writer.test.ts": 473, - "src/main/ai-vault-search/session-search-indexer.test.ts": 3307, + "src/main/ai-vault-search/storage/session-search-index-generation.test.ts": 471, + "src/main/ai-vault-search/storage/session-search-index-writer.test.ts": 473, + "src/main/ai-vault-search/indexing/session-search-indexer.test.ts": 3307, "src/main/ai-vault-search/session-search-instance.test.ts": 1045, "src/main/ai-vault-search/session-search-lifecycle-matrix.test.ts": 4969, - "src/main/ai-vault-search/session-search-list-reparse.test.ts": 330, - "src/main/ai-vault-search/session-search-live-transcript.test.ts": 434, - "src/main/ai-vault-search/session-search-merged-roots.test.ts": 529, - "src/main/ai-vault-search/session-search-message-rows.test.ts": 218, + "src/main/ai-vault-search/indexing/session-search-list-reparse.test.ts": 330, + "src/main/ai-vault-search/indexing/session-search-live-transcript.test.ts": 434, + "src/main/ai-vault-search/indexing/session-search-merged-roots.test.ts": 529, + "src/main/ai-vault-search/storage/session-search-message-rows.test.ts": 218, "src/main/ai-vault-search/session-search-native-chat-indexing.test.ts": 540, - "src/main/ai-vault-search/session-search-opencode-index.test.ts": 1158, - "src/main/ai-vault-search/session-search-orphan-rows.test.ts": 324, - "src/main/ai-vault-search/session-search-paging.test.ts": 863, - "src/main/ai-vault-search/session-search-query-planner.test.ts": 65, - "src/main/ai-vault-search/session-search-read-decision.test.ts": 46, - "src/main/ai-vault-search/session-search-restart-reindex.test.ts": 915, - "src/main/ai-vault-search/session-search-retention-delete.test.ts": 224, - "src/main/ai-vault-search/session-search-root-refresh.test.ts": 573, - "src/main/ai-vault-search/session-search-row-filter.test.ts": 274, - "src/main/ai-vault-search/session-search-row-identity.test.ts": 134, - "src/main/ai-vault-search/session-search-scan-roots.test.ts": 235, - "src/main/ai-vault-search/session-search-schema.test.ts": 876, - "src/main/ai-vault-search/session-search-scope-resolution.test.ts": 117, + "src/main/ai-vault-search/indexing/session-search-opencode-index.test.ts": 1158, + "src/main/ai-vault-search/query/session-search-paging.test.ts": 863, + "src/main/ai-vault-search/query/session-search-query-planner.test.ts": 65, + "src/main/ai-vault-search/indexing/session-search-read-decision.test.ts": 46, + "src/main/ai-vault-search/storage/session-search-retention-delete.test.ts": 224, + "src/main/ai-vault-search/indexing/session-search-root-refresh.test.ts": 573, + "src/main/ai-vault-search/query/session-search-row-filter.test.ts": 274, + "src/main/ai-vault-search/storage/session-search-row-identity.test.ts": 134, + "src/main/ai-vault-search/discovery/session-search-scan-roots.test.ts": 235, + "src/main/ai-vault-search/storage/session-search-schema.test.ts": 876, + "src/main/ai-vault-search/scope/session-search-scope-resolution.test.ts": 117, "src/main/ai-vault-search/session-search-service-registry.test.ts": 193, - "src/main/ai-vault-search/session-search-service.test.ts": 379, - "src/main/ai-vault-search/session-search-snippet-marks.test.ts": 230, - "src/main/ai-vault-search/session-search-store-scope-catalog.test.ts": 268, + "src/main/ai-vault-search/query/session-search-snippet-marks.test.ts": 230, + "src/main/ai-vault-search/scope/session-search-store-scope-catalog.test.ts": 268, "src/main/ai-vault-search/session-search-synthetic-corpus.test.ts": 372, - "src/main/ai-vault-search/session-search-typo-policy.test.ts": 158, - "src/main/ai-vault-search/session-search-typo-scope.test.ts": 195, - "src/main/ai-vault-search/session-search-write-buffer.test.ts": 197, - "src/main/ai-vault-search/session-search-write-lifetime.test.ts": 318, + "src/main/ai-vault-search/query/session-search-typo-policy.test.ts": 158, + "src/main/ai-vault-search/query/session-search-typo-scope.test.ts": 195, + "src/main/ai-vault-search/storage/session-search-write-buffer.test.ts": 197, + "src/main/ai-vault-search/storage/session-search-write-lifetime.test.ts": 318, "src/main/ai-vault/ai-vault-scan-cancellation.test.ts": 45, "src/main/ai-vault/ai-vault-scan-coordinator.test.ts": 55, "src/main/ai-vault/ai-vault-scan-progress-flow.test.ts": 835, @@ -708,7 +700,6 @@ "src/main/ai-vault/scanners/codex/session-scanner-codex-tool-records.test.ts": 177, "src/main/ai-vault/scanners/codex/session-scanner-codex-workers.test.ts": 543, "src/main/ai-vault/session-scanner-conversation-name-requests.test.ts": 443, - "src/main/ai-vault/scanners/copilot/session-scanner-copilot-cache-upgrade.test.ts": 391, "src/main/ai-vault/scanners/copilot/session-scanner-copilot-parser.test.ts": 173, "src/main/ai-vault/session-scanner-core-parser-wsl-stall.test.ts": 344, "src/main/ai-vault/scanners/cursor/session-scanner-cursor-chat-meta.test.ts": 745, @@ -769,7 +760,6 @@ "src/main/ai-vault/scan-service/session-scanner-service-restart-policy.test.ts": 44, "src/main/ai-vault/scan-service/session-scanner-service-root-request.test.ts": 44, "src/main/ai-vault/scan-service/session-scanner-service-root-response.test.ts": 251, - "src/main/ai-vault/scan-service/session-scanner-service-search-roots.test.ts": 825, "src/main/ai-vault/scan-service/session-scanner-service-search.test.ts": 1741, "src/main/ai-vault/scan-service/session-scanner-service-spawn.test.ts": 312, "src/main/ai-vault/session-scanner-timeline.test.ts": 160, @@ -831,10 +821,8 @@ "src/main/automations/automation-zero-grace-tick-latency.test.ts": 2108, "src/main/automations/dispatch-refusal-wsl-move.test.ts": 577, "src/main/automations/external-automation-manager-cache.test.ts": 70, - "src/main/automations/external-automation-owner-guard.test.ts": 332, "src/main/automations/external-automation-probe-scheduler.test.ts": 97, "src/main/automations/external-manager-scoped.test.ts": 391, - "src/main/automations/external-manager.test.ts": 388, "src/main/automations/run-terminal-retention.test.ts": 112, "src/main/automations/automation-workspace-create.test.ts": 50, "src/main/automations/hook-review-blocked-run-terminals.test.ts": 4564, @@ -844,7 +832,6 @@ "src/main/automations/run-target-resolution.test.ts": 367, "src/main/automations/runtime-chat-run-observer.test.ts": 6812, "src/main/automations/runtime-terminal-run-observer-evidence.test.ts": 230, - "src/main/automations/runtime-terminal-run-observer.test.ts": 4026, "src/main/automations/service-precheck.test.ts": 2057, "src/main/automations/service.test.ts": 2970, "src/main/bitbucket/credential-connection.test.ts": 156, @@ -982,7 +969,6 @@ "src/main/browser/cookies/browser-cookie-import-partition.electron.test.ts": 2260, "src/main/browser/cookies/browser-cookie-import-snapshot-ownership.test.ts": 1178, "src/main/browser/cookies/browser-cookie-import-validated-partition.electron.test.ts": 2445, - "src/main/browser/cookies/browser-cookie-import-write.test.ts": 68, "src/main/browser/cookies/browser-cookie-import.comet.test.ts": 1501, "src/main/browser/cookies/browser-cookie-import.test.ts": 1304, "src/main/browser/cookies/browser-cookie-samesite.electron.test.ts": 1882, @@ -1063,7 +1049,6 @@ "src/main/browser/cdp/input/guest-focused-frame-route.test.ts": 78, "src/main/browser/routing/local-host-partitions/local-ssh-browser-partition-identity.test.ts": 479, "src/main/browser/routing/local-host-partitions/local-ssh-browser-profile-retirement.test.ts": 287, - "src/main/browser/routing/local-host-partitions/local-ssh-browser-route-target.test.ts": 65, "src/main/browser/routing/local-host-partitions/local-ssh-browser-route.test.ts": 92, "src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts": 341, "src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts": 165, @@ -1107,7 +1092,6 @@ "src/main/claude-usage/claude-model-pricing.test.ts": 74, "src/main/claude-usage/claude-usage-report-aggregation.test.ts": 57, "src/main/claude-usage/persisted-source-authority.test.ts": 491, - "src/main/claude-usage/persisted-token-columns-store.test.ts": 376, "src/main/claude-usage/scanner-incremental-append.test.ts": 235, "src/main/claude-usage/scanner-incremental-ownership.test.ts": 545, "src/main/claude-usage/scanner-incremental-reader.test.ts": 819, @@ -1115,9 +1099,6 @@ "src/main/claude-usage/scanner-scan.test.ts": 295, "src/main/claude-usage/scanner.test.ts": 80, "src/main/claude-usage/source-cache-compression.test.ts": 74, - "src/main/claude-usage/store-checkpoint-persistence.test.ts": 545, - "src/main/claude-usage/store-source-authority.test.ts": 530, - "src/main/claude-usage/store.test.ts": 377, "src/main/claude-usage/transcript-file-discovery-errors.test.ts": 62, "src/main/claude-usage/transcript-reader-lifetime.test.ts": 100, "src/main/claude-usage/transcript-tuple-append.test.ts": 435, @@ -1172,7 +1153,6 @@ "src/main/claude/claude-stop-ack-race.test.ts": 1301, "src/main/claude/claude-stream-json-connection-close.test.ts": 621, "src/main/claude/claude-stream-json-connection.test.ts": 8687, - "src/main/claude/claude-stream-json-exit-error.test.ts": 170, "src/main/claude/claude-streamed-text-checkpoints.test.ts": 59, "src/main/claude/claude-structured-launch-home-perf.test.ts": 401, "src/main/claude/claude-structured-result-control-overlap.test.ts": 1136, @@ -1329,8 +1309,6 @@ "src/main/codex-usage/scanner-paths.test.ts": 493, "src/main/codex-usage/scanner.test.ts": 247, "src/main/codex-usage/session-file-discovery-errors.test.ts": 70, - "src/main/codex-usage/store-automation-usage.test.ts": 305, - "src/main/codex-usage/store-persistence.test.ts": 364, "src/main/codex/app-server/codex-app-server-client.test.ts": 13839, "src/main/codex/app-server/codex-app-server-connection-exit-order.test.ts": 264, "src/main/codex/app-server/codex-app-server-connection-tree-unproven.test.ts": 634, @@ -1916,7 +1894,6 @@ "src/main/git/source-control/status-read-failure-real-git.test.ts": 307, "src/main/git/source-control/status-shared-symlinks.test.ts": 746, "src/main/git/source-control/status-submodule.test.ts": 306, - "src/main/git/source-control/status-symlink-probe-budget.test.ts": 238, "src/main/git/source-control/status-upstream-ref.test.ts": 52, "src/main/git/source-control/upstream-deferred-fork-remote-real.test.ts": 319, "src/main/git/source-control/upstream.test.ts": 406, @@ -2014,7 +1991,6 @@ "src/main/github/pr-refresh-coordinator-active-visible-priority.test.ts": 643, "src/main/github/pr-refresh-coordinator-alias-coalescing.test.ts": 1020, "src/main/github/pr-refresh-coordinator-completion-order.test.ts": 914, - "src/main/github/pr-refresh-coordinator-error-cadence.test.ts": 951, "src/main/github/pr-refresh-coordinator-foreground-pacing.test.ts": 650, "src/main/github/pr-refresh-coordinator-refresh-events.test.ts": 617, "src/main/github/pr-refresh-coordinator-visibility-policy.test.ts": 1371, @@ -2157,7 +2133,6 @@ "src/main/ipc/filesystem/filesystem-search-file-paths.test.ts": 443, "src/main/ipc/filesystem/filesystem-symlink-directory-entries.test.ts": 56, "src/main/ipc/filesystem/filesystem-write-bytes.test.ts": 147, - "src/main/ipc/filesystem/filesystem-write-identical.test.ts": 138, "src/main/ipc/filesystem/filesystem-wsl-stopped-distro-git.test.ts": 1163, "src/main/ipc/filesystem/filesystem-wsl-stopped-distro-reads.test.ts": 1284, "src/main/ipc/filesystem/filesystem.test.ts": 2043, @@ -2238,7 +2213,6 @@ "src/main/ipc/pty/ipc/spawn-push-target-materialization-real-git.test.ts": 1316, "src/main/ipc/pty/ipc/write-input-user-input.test.ts": 84, "src/main/ipc/pty/managed-data-account-spawn-environment.test.ts": 1150, - "src/main/ipc/pty/pane/join-pane-spawn.test.ts": 1438, "src/main/ipc/pty/pane/pane-owner-replacement.test.ts": 1960, "src/main/ipc/pty/pane/serializer-document-lifetime.test.ts": 77, "src/main/ipc/pty/pane/spawn-registration.test.ts": 935, @@ -2257,7 +2231,6 @@ "src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts": 4680, "src/main/ipc/pty/pty-ssh-stop-verdict.test.ts": 3615, "src/main/ipc/pty/pty-write-ipc-validation.test.ts": 5157, - "src/main/ipc/pty/runtime/kill-legacy-relay-bridged.test.ts": 3679, "src/main/ipc/pty/runtime/kill-same-id-respawn.test.ts": 3784, "src/main/ipc/pty/runtime/spawn-preflight-wsl-background-hold.test.ts": 1568, "src/main/ipc/filesystem/watcher-process/rebinding-file-watch-noise.test.ts": 317, @@ -2267,7 +2240,6 @@ "src/main/ipc/worktrees/removal/registered-worktree-root-stopped-distro.test.ts": 168, "src/main/ipc/worktrees/removal/registered-worktree-root-wsl-runtime.test.ts": 261, "src/main/ipc/worktrees/removal/registered-worktree-roots-scoped-invalidation.test.ts": 141, - "src/main/ipc/renderer-lifetime-abort.test.ts": 65, "src/main/ipc/renderer-shutdown-checkpoint-sleep-records.test.ts": 1914, "src/main/ipc/renderer-shutdown-checkpoint.test.ts": 496, "src/main/ipc/renderer-terminal-serializer-readiness.test.ts": 45, @@ -2308,14 +2280,12 @@ "src/main/ipc/ssh/ssh-app-shutdown.test.ts": 4455, "src/main/ipc/ssh/ssh-connect-decision-cancellation.test.ts": 6414, "src/main/ipc/ssh/ssh-credential-cancel.test.ts": 4604, - "src/main/ipc/ssh/ssh-disconnect-cancellation.test.ts": 6851, "src/main/ipc/ssh/ssh-host-user-disconnect.test.ts": 4734, "src/main/ipc/ssh/ssh-passphrase.test.ts": 135, "src/main/ipc/ssh/ssh.test.ts": 6905, "src/main/ipc/terminal-preview-output-stream.test.ts": 53, "src/main/ipc/terminal-render-desync-evidence.test.ts": 78, "src/main/ipc/terminal-startup-color-query-replies.test.ts": 265, - "src/main/ipc/usage-provider-handlers-readiness.test.ts": 506, "src/main/ipc/filesystem/watcher-process/watcher-event-root-path-rewrite.test.ts": 48, "src/main/workspaces/removal/watcher-removal-gate.test.ts": 384, "src/main/ipc/workspace-cleanup/workspace-cleanup-activity.test.ts": 76, @@ -2438,7 +2408,6 @@ "src/main/managed-server/install/orcad-remote-launch-setsid.test.ts": 342, "src/main/managed-server/install/orcad-remote-launch.test.ts": 319, "src/main/managed-server/install/orcad-remote-node-runtime.test.ts": 248, - "src/main/managed-server/install/orcad-remote-primitives.test.ts": 337, "src/main/managed-server/install/orcad-remote-readiness-wait.test.ts": 9063, "src/main/managed-server/install/orcad-remote-runtime.test.ts": 488, "src/main/managed-server/install/orcad-remote-shell-commands.integration.test.ts": 9000, @@ -2474,7 +2443,6 @@ "src/main/muse/hook-service.test.ts": 145, "src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery-freshness.test.ts": 390, "src/main/native-chat/agent-model-catalog/agent-model-catalog-entry.test.ts": 75, - "src/main/native-chat/agent-model-catalog/agent-model-catalog-persistence.test.ts": 115, "src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.test.ts": 4786, "src/main/native-chat/agent-model-catalog/agent-model-catalog-store.test.ts": 611, "src/main/native-chat/agent-model-catalog/agent-model-catalog-unavailable.test.ts": 465, @@ -2658,20 +2626,17 @@ "src/main/opencode/overlay-dir-gc.test.ts": 141, "src/main/opencode/overlay-source-ownership.test.ts": 60, "src/main/opencode2/status-plugin-setup-lifetime.test.ts": 108, - "src/main/orca-profiles/other-profile-workspace-catalog.test.ts": 462, - "src/main/orca-profiles/profile-active-transfer-worker.test.ts": 2841, - "src/main/orca-profiles/profile-active-transfer.test.ts": 2243, - "src/main/orca-profiles/profile-artifact-cloud-cleanup.test.ts": 553, - "src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts": 683, - "src/main/orca-profiles/profile-cloud-service-sign-out-connect-race.test.ts": 541, - "src/main/orca-profiles/profile-cloud-session-refresh-rotation.test.ts": 523, - "src/main/orca-profiles/profile-cloud-session-store.test.ts": 133, + "src/main/orca-profiles/catalog/other-profile-workspace-catalog.test.ts": 462, + "src/main/orca-profiles/project-transfer/profile-active-transfer-worker.test.ts": 2841, + "src/main/orca-profiles/cloud-auth/profile-artifact-cloud-cleanup.test.ts": 553, + "src/main/orca-profiles/cloud-auth/profile-cloud-service-connect-overlap.test.ts": 683, + "src/main/orca-profiles/cloud-auth/profile-cloud-service-sign-out-connect-race.test.ts": 541, + "src/main/orca-profiles/cloud-session/profile-cloud-session-refresh-rotation.test.ts": 523, "src/main/orca-profiles/profile-index-store.test.ts": 1265, - "src/main/orca-profiles/profile-project-domain-transfer.test.ts": 5088, - "src/main/orca-profiles/profile-project-session-field-disposition.test.ts": 334, - "src/main/orca-profiles/profile-project-session-state.test.ts": 300, - "src/main/orca-profiles/profile-project-transfer-migration.test.ts": 1642, - "src/main/orca-profiles/profile-project-transfer.test.ts": 1456, + "src/main/orca-profiles/project-transfer/profile-project-session-field-disposition.test.ts": 334, + "src/main/orca-profiles/project-transfer/profile-project-session-state.test.ts": 300, + "src/main/orca-profiles/project-transfer/profile-project-transfer-migration.test.ts": 1642, + "src/main/orca-profiles/project-transfer/profile-project-transfer.test.ts": 1456, "src/main/orca-profiles/profile-telemetry-consent-seed.test.ts": 536, "src/main/persistence/migrating-orcad-catalog/orcad-migration-export-holds.test.ts": 231, "src/main/orcad/electron-serve-provider-selection.test.ts": 554, @@ -2693,7 +2658,6 @@ "src/main/orcad/orcad-cli-orchestration.integration.test.ts": 214, "src/main/orcad/orcad-forked-child-paths.test.ts": 337, "src/main/orcad/orcad-help.integration.test.ts": 5016, - "src/main/orcad/orcad-host-account-launch-env-store.test.ts": 299, "src/main/orcad/orcad-idle-exit-monitor.test.ts": 106, "src/main/orcad/orcad-instance-lock.test.ts": 315, "src/main/orcad/orcad-launcher-isolation.integration.test.ts": 617, @@ -2740,7 +2704,6 @@ "src/main/persistence/loading-store/profile-state-maintenance-contracts.test.ts": 8856, "src/main/persistence/loading-store/profile-state-settings-writes.test.ts": 2311, "src/main/persistence/loading-store/profile-state-sqlite-authority.test.ts": 2840, - "src/main/persistence/loading-store/profile-state-store-backups.test.ts": 2270, "src/main/persistence/loading-store/profile-state-temp-cleanup-lifetime.test.ts": 2582, "src/main/persistence/loading-store/profile-state-update-quit.test.ts": 2094, "src/main/persistence/loading-store/pty-incarnation-renderer-save.test.ts": 2182, @@ -2791,7 +2754,6 @@ "src/main/persistence/moving-wsl-projects/wsl-move-quiesce.test.ts": 413, "src/main/persistence/moving-wsl-projects/wsl-move-real-pause.test.ts": 1939, "src/main/persistence/moving-wsl-projects/wsl-move-reset.test.ts": 891, - "src/main/persistence/moving-wsl-projects/wsl-move-restore-hints.test.ts": 65, "src/main/persistence/moving-wsl-projects/wsl-move-retention.test.ts": 2285, "src/main/persistence/moving-wsl-projects/wsl-move-rewrite-ledger.test.ts": 641, "src/main/persistence/moving-wsl-projects/wsl-move-scope-guard.test.ts": 639, @@ -2917,7 +2879,6 @@ "src/main/persistence/tracking-repos/persistence-folder-scan-project-groups.test.ts": 1944, "src/main/persistence/tracking-repos/persistence-folder-workspace-notes.test.ts": 2124, "src/main/persistence/tracking-repos/persistence-invalid-workspace-layout-purge.test.ts": 2151, - "src/main/persistence/tracking-repos/persistence-repo-lifecycle.test.ts": 3528, "src/main/persistence/tracking-repos/persistence-update-repo.test.ts": 2213, "src/main/persistence/tracking-repos/persistence-workspace-attachments.test.ts": 2030, "src/main/persistence/tracking-repos/persistence-workspace-pinned-automation-fence.test.ts": 2412, @@ -3161,7 +3122,6 @@ "src/main/ripgrep/bundled-ripgrep-real.test.ts": 242, "src/main/ripgrep/bundled-ripgrep-text-search.test.ts": 707, "src/main/ripgrep/ripgrep-filename-identity-real.test.ts": 274, - "src/main/ripgrep/synchronous-spawn-failure.test.ts": 54, "src/main/ripgrep/text-search-unicode-real.test.ts": 332, "src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement-main-close.test.ts": 6833, "src/main/runtime/session-tabs/acknowledged-terminal-tab-retirement.test.ts": 6423, @@ -3177,7 +3137,6 @@ "src/main/runtime/agent-session/records/agent-session-store-load-scale.test.ts": 732, "src/main/runtime/agent-session/agent-session-tab-layout-queue.test.ts": 4061, "src/main/runtime/agent-session/agent-session-conversation-clear-commit.test.ts": 957, - "src/main/runtime/agent-session/agent-session-death-evidence-persistence.test.ts": 1113, "src/main/runtime/agent-session/agent-session-launch-directory.test.ts": 926, "src/main/runtime/agent-session/agent-session-tab-layout.test.ts": 275, "src/main/runtime/agent-session/agent-session-unsaved-creation-supersession.test.ts": 726, @@ -3393,7 +3352,6 @@ "src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-delivery.test.ts": 7599, "src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-notification-consistency.test.ts": 24765, "src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-routing.test.ts": 14953, - "src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-titles.test.ts": 11638, "src/main/runtime/orchestration/mailbox/notifications/orchestration-message-delivery-identity.test.ts": 25822, "src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-messages-fake-parity.test.ts": 510, "src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-open-dialog-delivery-hold.test.ts": 5567, @@ -3442,7 +3400,6 @@ "src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.test.ts": 662, "src/main/runtime/orchestration/db/schema/dispatch-consumer-generation-migration.test.ts": 640, "src/main/runtime/orchestration/db/dispatch-context/dispatch-failure-idempotency.test.ts": 544, - "src/main/runtime/orchestration/federation/synchronization/federation-ack-checkpoints.test.ts": 38, "src/main/runtime/orchestration/federation/synchronization/federation-acknowledgment-integrity.test.ts": 557, "src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts": 566, "src/main/runtime/orchestration/federation/synchronization/federation-sync.test.ts": 5264, @@ -3571,13 +3528,11 @@ "src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts": 1096, "src/main/runtime/rpc/methods/client-state/client-ui-set-collapsed.test.ts": 1091, "src/main/runtime/rpc/methods/clipboard/clipboard.test.ts": 848, - "src/main/runtime/rpc/methods/files/file-watch-event-batcher.test.ts": 69, "src/main/runtime/rpc/methods/files/files-path-search.test.ts": 884, "src/main/runtime/rpc/methods/files/files-read-dir-page.test.ts": 1213, "src/main/runtime/rpc/methods/files/files-read-dir-remote-budget.test.ts": 860, "src/main/runtime/rpc/methods/files/files-watch-cancellation.test.ts": 886, "src/main/runtime/rpc/methods/files/files.test.ts": 1018, - "src/main/runtime/rpc/methods/source-control/gitlab/gitlab.test.ts": 4209, "src/main/runtime/rpc/methods/integrations/jira/jira-saved-filter-state.test.ts": 937, "src/main/runtime/rpc/methods/integrations/jira/jira.test.ts": 732, "src/main/runtime/rpc/methods/integrations/linear/linear-agent-access.test.ts": 4648, @@ -3623,7 +3578,6 @@ "src/main/runtime/rpc/methods/orchestration/messaging/check-worker-consumer-fencing.test.ts": 5876, "src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts": 4547, "src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts": 4373, - "src/main/runtime/rpc/methods/orchestration/messaging/implicit-task-run-routing.test.ts": 4876, "src/main/runtime/rpc/methods/orchestration/messaging/recipient-routing.test.ts": 4675, "src/main/runtime/rpc/methods/orchestration/messaging/run-bound-mailbox-history.test.ts": 4288, "src/main/runtime/rpc/methods/orchestration/messaging/run-bound-mailbox-interleavings.test.ts": 5049, @@ -3662,12 +3616,10 @@ "src/main/runtime/rpc/methods/orchestration/worker/worker-terminal-custody-at-creation.test.ts": 5687, "src/main/runtime/rpc/methods/orchestration/worker/workers-new-worktree.test.ts": 6117, "src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts": 5182, - "src/main/runtime/rpc/methods/pairing/pairing.test.ts": 776, "src/main/runtime/rpc/methods/plugins/plugin-dev-emit.test.ts": 3118, "src/main/runtime/rpc/methods/plugins/plugin-dev-request.test.ts": 3725, "src/main/runtime/rpc/methods/plugins/plugins.test.ts": 274, "src/main/runtime/rpc/methods/preflight/preflight-selected-target.test.ts": 5043, - "src/main/runtime/rpc/methods/projects/repo.test.ts": 896, "src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts": 4349, "src/main/runtime/rpc/methods/session-tabs/session-tabs-move-validation.test.ts": 4261, "src/main/runtime/rpc/methods/session-tabs/session-tabs-retirement-proof-delta.test.ts": 1726, @@ -3714,7 +3666,6 @@ "src/main/runtime/rpc/mobile-socket-wiring.test.ts": 312, "src/main/runtime/rpc/orcad-feature-readiness.test.ts": 40, "src/main/runtime/rpc/orchestration-11745-regression-verification.test.ts": 22874, - "src/main/runtime/rpc/orchestration-caller-show.test.ts": 4209, "src/main/runtime/rpc/orchestration-check-wait-session.test.ts": 5096, "src/main/runtime/rpc/orchestration-commit-notify-characterization.test.ts": 5702, "src/main/runtime/rpc/orchestration-contract-fence.test.ts": 6113, @@ -3735,7 +3686,6 @@ "src/main/runtime/rpc/orchestration-party-agreement.test.ts": 4581, "src/main/runtime/rpc/orchestration-run-use-invalid-takeover.test.ts": 4575, "src/main/runtime/rpc/orchestration-runtime-update-settlement.test.ts": 5105, - "src/main/runtime/rpc/orchestration-session-caller.test.ts": 5717, "src/main/runtime/rpc/orchestration-session-coordinator.test.ts": 4655, "src/main/runtime/rpc/orchestration-session-recipient.test.ts": 5100, "src/main/runtime/rpc/orchestration-session-run-binding.test.ts": 4448, @@ -3744,7 +3694,6 @@ "src/main/runtime/rpc/remote-runtime-server-heartbeat-missed-probe-tolerance.test.ts": 59, "src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts": 60, "src/main/runtime/rpc/repo-add-cli.integration.test.ts": 1603, - "src/main/runtime/rpc/rpc-caller-scope.test.ts": 5071, "src/main/runtime/rpc/runtime-client-capabilities.test.ts": 43, "src/main/runtime/rpc/runtime-source-admission.test.ts": 909, "src/main/runtime/rpc/shadowed-port-probe.test.ts": 99, @@ -3758,7 +3707,6 @@ "src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery-history.test.ts": 1892, "src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery.test.ts": 2369, "src/main/runtime/rpc/terminal-multiplex-desktop-resize-routing.test.ts": 2160, - "src/main/runtime/rpc/terminal-multiplex-endpoint-loss-notice.test.ts": 1852, "src/main/runtime/rpc/terminal-multiplex-initial-snapshot-buffering.test.ts": 2118, "src/main/runtime/rpc/terminal-multiplex-input-sequence-replay.test.ts": 5709, "src/main/runtime/rpc/terminal-multiplex-input-write-rejection.test.ts": 2423, @@ -3771,7 +3719,6 @@ "src/main/runtime/rpc/terminal-multiplex-snapshot-query-replay.test.ts": 2715, "src/main/runtime/rpc/terminal-multiplex-snapshot-serialization.test.ts": 2224, "src/main/runtime/rpc/terminal-multiplex-subscribe-slot-recovery.test.ts": 1792, - "src/main/runtime/rpc/terminal-opencode-send-guard.integration.test.ts": 4512, "src/main/runtime/rpc/terminal-output-batching.test.ts": 2087, "src/main/runtime/rpc/terminal-output-frame-chunks.test.ts": 70, "src/main/runtime/rpc/terminal-passive-resize-input.test.ts": 2656, @@ -3793,7 +3740,6 @@ "src/main/runtime/rpc/unpaired-device-auth-throttle.test.ts": 42, "src/main/runtime/rpc/web-session-pairing.test.ts": 402, "src/main/runtime/rpc/workspace-creator-context.test.ts": 40, - "src/main/runtime/rpc/worktree-catalog-snapshot.test.ts": 46, "src/main/runtime/rpc/worktree-removal-marker-projection.test.ts": 497, "src/main/runtime/rpc/worktree-rm-cli.integration.test.ts": 6876, "src/main/runtime/rpc/ws-empty-payload-frame-write.test.ts": 117, @@ -3864,7 +3810,6 @@ "src/main/runtime/rpc/server/runtime-rpc-websocket-reply-size-limit.test.ts": 4410, "src/main/runtime/files/search/runtime-search-line-fragments.test.ts": 624, "src/main/runtime/files/server-browse/runtime-server-environment-commands.test.ts": 262, - "src/main/runtime/rpc/server/runtime-socket-sweep.test.ts": 47, "src/main/runtime/client/runtime-subscription-registry.test.ts": 142, "src/main/runtime/terminal/records/runtime-terminal-exit-contracts.test.ts": 5325, "src/main/runtime/terminal/identity/runtime-terminal-handle-contracts.test.ts": 3983, @@ -3872,7 +3817,6 @@ "src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts": 4427, "src/main/runtime/terminal/adoption/runtime-terminal-orphan-adoption-rollback.test.ts": 1832, "src/main/runtime/terminal/surface/runtime-terminal-retirement-contracts.test.ts": 4505, - "src/main/runtime/terminal/title/runtime-terminal-set-pane-title.test.ts": 5216, "src/main/runtime/terminal/input/runtime-terminal-writer.test.ts": 150, "src/main/runtime/construction/runtime-workspace-launch-contracts.test.ts": 4059, "src/main/runtime/workspaces/session-hosts/runtime-workspace-session-controller-twin-repo.test.ts": 298, @@ -3891,11 +3835,9 @@ "src/main/runtime/session-tabs/session-tab-close-force.test.ts": 7089, "src/main/runtime/session-tabs/runtime-inventory-publication-authority.test.ts": 5775, "src/main/runtime/session-tabs/headless-mobile-session-absorbed-rows.test.ts": 4223, - "src/main/runtime/session-tabs/main-layout-agent-launch-tabs.test.ts": 4233, "src/main/runtime/session-tabs/main-layout-session-tab-move.test.ts": 4233, "src/main/runtime/session-tabs/session-tab-prototype-dispatch.test.ts": 4888, "src/main/runtime/session-tabs/session-tabs-headless-main-change.test.ts": 4320, - "src/main/runtime/session-tabs/session-tabs-held-rows-commit.test.ts": 5046, "src/main/runtime/session-tabs/session-tabs-inventory-publication.test.ts": 4166, "src/main/runtime/session-tabs/session-tabs-main-rows-parity.test.ts": 4606, "src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts": 4153, @@ -3931,13 +3873,11 @@ "src/main/runtime/agent-session/lifecycle/structured-agent-cli-writers.test.ts": 140, "src/main/runtime/agent-session/lifecycle/structured-agent-session-history-close-race.test.ts": 5020, "src/main/runtime/agent-session/naming/structured-agent-session-provider-naming-shutdown.test.ts": 1987, - "src/main/runtime/agent-session/lifecycle/structured-agent-session-tab-authority.test.ts": 11047, "src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts": 720, "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts": 38220, "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-lifecycle.test.ts": 9312, "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker-mail.test.ts": 6125, "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-dispatch-worker.test.ts": 6981, - "src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts": 1605, "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-helpers.test.ts": 8057, "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-reuse.test.ts": 6372, "src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-worker-start-unknown.test.ts": 7813, @@ -4089,7 +4029,6 @@ "src/main/ssh/host-keys/ssh-known-hosts.test.ts": 105, "src/main/ssh/external-editors/zed-ssh-url.test.ts": 55, "src/main/ssh/connection/ssh-connect-config.test.ts": 182, - "src/main/ssh/connection/ssh-connection-attribution.test.ts": 44, "src/main/ssh/connection/ssh-connection-auth-fallback.test.ts": 512, "src/main/ssh/connection/ssh-connection-channel-error.test.ts": 461, "src/main/ssh/connection/ssh-connection-channel-open.test.ts": 1230, @@ -4262,10 +4201,8 @@ "src/main/startup/main-process-quit-pending-writer.test.ts": 328, "src/main/startup/main-process-quit-update-veto.test.ts": 1714, "src/main/startup/main-process-ready-activation-failure.test.ts": 313, - "src/main/startup/main-process-ready-identity-write.test.ts": 3997, "src/main/startup/main-process-ready-persistence-cleanup.test.ts": 164, "src/main/startup/main-process-ready-phase-ordering.test.ts": 242, - "src/main/startup/main-process-runtime-launch-activation.test.ts": 1369, "src/main/startup/main-window-actions-quit-and-stop-all-sessions.test.ts": 488, "src/main/startup/os-opened-document-resolution.test.ts": 74, "src/main/startup/os-opened-documents.test.ts": 67, @@ -4313,7 +4250,6 @@ "src/main/telemetry/validator-warn-cache.test.ts": 187, "src/main/telemetry/validator.test.ts": 170, "src/main/telemetry/wsl-usage-reporter.test.ts": 407, - "src/main/pty/history/terminal-history-async-delete.test.ts": 374, "src/main/pty/history/terminal-history-gc-fs-call-count.test.ts": 157, "src/main/pty/history/terminal-history-gc.test.ts": 824, "src/main/pty/history/terminal-history-tombstone-retry.test.ts": 715, @@ -4367,22 +4303,15 @@ "src/main/updater/lifecycle/serve-supervisor-install-park.test.ts": 173, "src/main/updater/mac-install/shipit-leftover-recovery.test.ts": 136, "src/main/updater/lifecycle/updater-wsl-move-install-hold.test.ts": 287, - "src/main/usage/usage-cache-snapshot-writer.test.ts": 55, - "src/main/usage/usage-worktree-canonicalizer.test.ts": 43, - "src/main/usage/usage-worktree-metadata.test.ts": 61, - "src/main/usage/agent-token-usage-reporter.test.ts": 343, - "src/main/usage/analytics-session-id-store.test.ts": 195, - "src/main/usage/highest-usage-key.test.ts": 45, - "src/main/usage/jsonl-file-reader.test.ts": 112, - "src/main/usage/jsonl-file-snapshot.test.ts": 54, - "src/main/usage/jsonl-line-offsets.test.ts": 66, - "src/main/usage/usage-breakdown-scaling.test.ts": 84, - "src/main/usage/usage-calendar-range.test.ts": 53, - "src/main/usage/usage-provider-store-initialization.test.ts": 586, - "src/main/usage/usage-provider-store-lifecycle.test.ts": 769, - "src/main/usage/usage-scan-worker-cache-cleanup.test.ts": 153, - "src/main/usage/usage-source-cache-file.test.ts": 94, - "src/main/usage/usage-worktree-resolver.test.ts": 269, + "src/main/usage/cache/usage-cache-snapshot-writer.test.ts": 55, + "src/main/usage/reporting/token-usage/analytics-session-id-store.test.ts": 195, + "src/main/usage/source-input/jsonl/jsonl-file-reader.test.ts": 112, + "src/main/usage/source-input/jsonl/jsonl-line-offsets.test.ts": 66, + "src/main/usage/rollups/usage-breakdown-scaling.test.ts": 84, + "src/main/usage/reporting/range-query/usage-calendar-range.test.ts": 53, + "src/main/usage/provider-lifecycle/usage-provider-store-lifecycle.test.ts": 769, + "src/main/usage/cache/usage-source-cache-file.test.ts": 94, + "src/main/usage/worktree-attribution/usage-worktree-resolver.test.ts": 269, "src/main/warp-themes/discovery.test.ts": 58, "src/main/warp-themes/index.test.ts": 678, "src/main/warp-themes/manual-warp-theme-files.test.ts": 104, @@ -4390,11 +4319,9 @@ "src/main/warp-themes/parser.test.ts": 85, "src/main/warp-themes/theme-file-scanner.test.ts": 56, "src/main/windows/windows-command-paths.test.ts": 77, - "src/main/window/attach-main-window-services.test.ts": 964, "src/main/window/clipboard-agent-session-attachment-paste.test.ts": 585, "src/main/window/clipboard-copied-file-paths.test.ts": 58, "src/main/window/clipboard-dashboard-popout-access.test.ts": 1361, - "src/main/window/clipboard-ipc-handlers.test.ts": 496, "src/main/window/clipboard-macos-image-paste.test.ts": 1087, "src/main/window/clipboard-publisher-executable.test.ts": 62, "src/main/window/clipboard-remote-file-staging-fs.test.ts": 66, @@ -4406,7 +4333,6 @@ "src/main/window/createMainWindow-markdown-editor-focus.test.ts": 1084, "src/main/window/createMainWindow-recovery-reload-watchdog.test.ts": 1251, "src/main/window/createMainWindow-renderer-crash-recovery.test.ts": 1613, - "src/main/window/createMainWindow-terminal-focus-shortcuts.test.ts": 2628, "src/main/window/createMainWindow-user-quit-close.test.ts": 1592, "src/main/window/createMainWindow.test.ts": 1603, "src/main/window/darwin-user-temp-dir.test.ts": 51, @@ -4521,7 +4447,6 @@ "src/main/wsl/execution/wsl-guest-pane-process-script-cost.test.ts": 213, "src/main/wsl/execution/wsl-guest-pane-processes.test.ts": 48, "src/main/wsl/execution/wsl-guest-process-identity.test.ts": 54, - "src/main/wsl/host-lifecycle/wsl-host-automation-wake.test.ts": 288, "src/main/wsl/host-lifecycle/wsl-host-kept-for-peers.test.ts": 159, "src/main/wsl/host-lifecycle/wsl-host-pending-removal.test.ts": 955, "src/main/wsl/host-lifecycle/wsl-host-server-stop.test.ts": 407, @@ -4730,12 +4655,10 @@ "src/renderer/src/components/browser-pane/host-guest/browser-page-guest-recovery.test.ts": 515, "src/renderer/src/components/browser-pane/host-guest/browser-page-registration-ownership.test.ts": 2197, "src/renderer/src/components/browser-pane/host-guest/browser-page-viewport.test.ts": 242, - "src/renderer/src/components/browser-pane/host-guest/browser-page-window-close.test.ts": 54, "src/renderer/src/components/browser-pane/host-guest/browser-system-resume.test.ts": 187, "src/renderer/src/components/browser-pane/host-guest/use-browser-page-keyboard-shortcuts.split.test.tsx": 2098, "src/renderer/src/components/browser-pane/host-guest/use-browser-page-webview-partition.test.ts": 1985, "src/renderer/src/components/browser-pane/host-guest/webview-registry.test.ts": 103, - "src/renderer/src/components/browser-pane/navigate/browser-file-editor-open.test.ts": 1853, "src/renderer/src/components/browser-pane/navigate/browser-load-failure-overlay.test.tsx": 831, "src/renderer/src/components/browser-pane/navigate/browser-page-download-activity.test.ts": 44, "src/renderer/src/components/browser-pane/navigate/browser-webview-load-failure.test.ts": 243, @@ -4810,19 +4733,16 @@ "src/renderer/src/components/editor/diff/monaco-view/DiffViewer.word-wrap-lifecycle.test.tsx": 2499, "src/renderer/src/components/editor/EditorConflictReviewSurface.live-record.test.tsx": 1193, "src/renderer/src/components/editor/EditorEditFileSurface.monaco-containment.test.tsx": 2666, - "src/renderer/src/components/editor/EditorFileLoadErrorView.test.tsx": 660, "src/renderer/src/components/editor/EditorFileLocationMenuItems.test.tsx": 846, "src/renderer/src/components/editor/EditorPanel.custom-editor-flush.test.tsx": 2478, "src/renderer/src/components/editor/EditorPanel.diff-rich-owner.test.tsx": 2823, "src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.external-sync.test.tsx": 1660, "src/renderer/src/components/editor/notebook/kernel/IpynbKernelToolbar.test.tsx": 736, - "src/renderer/src/components/editor/notebook/document/IpynbRendering.test.tsx": 2143, "src/renderer/src/components/editor/markdown-preview/surface/MarkdownPreview.link-routing.interaction.test.tsx": 1127, "src/renderer/src/components/editor/MediaViewer.test.tsx": 308, "src/renderer/src/components/editor/PdfFind.test.tsx": 581, "src/renderer/src/components/editor/PluginBytesCustomEditorSurface.test.tsx": 641, "src/renderer/src/components/editor/PluginEditorNeedsDesktopNotice.test.tsx": 2107, - "src/renderer/src/components/editor/PluginFileTypeSuggestion.test.tsx": 2062, "src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownEditor.focus-leave.test.tsx": 4927, "src/renderer/src/components/editor/ai-vault-session-log-content.test.tsx": 1899, "src/renderer/src/components/editor/check-details/actions/check-annotation-path.test.ts": 53, @@ -4842,21 +4762,19 @@ "src/renderer/src/components/editor/combined-diff/resolve-changes/combined-diff-entries.test.ts": 54, "src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-actions.disk-precondition.test.tsx": 2383, "src/renderer/src/components/editor/conflict-review-file-tree-windowing.test.tsx": 1487, - "src/renderer/src/components/editor/csv/CsvGrid.test.tsx": 994, "src/renderer/src/components/editor/csv/CsvViewer.delimiter.test.tsx": 2923, "src/renderer/src/components/editor/csv/CsvViewer.editing.test.tsx": 3583, - "src/renderer/src/components/editor/csv/csv-byte-index.test.ts": 1645, - "src/renderer/src/components/editor/csv/csv-cell-links.test.tsx": 302, - "src/renderer/src/components/editor/csv/csv-column-width-preferences.test.ts": 208, - "src/renderer/src/components/editor/csv/csv-paged-preview.test.ts": 143, - "src/renderer/src/components/editor/csv/csv-parse-budget.test.ts": 102, - "src/renderer/src/components/editor/csv/csv-parse.test.ts": 148, - "src/renderer/src/components/editor/csv/csv-pending-save.test.ts": 1926, - "src/renderer/src/components/editor/csv/csv-preview-save-safety.test.ts": 1973, - "src/renderer/src/components/editor/csv/csv-table-interactions.test.ts": 310, - "src/renderer/src/components/editor/csv/csv-text-document.test.ts": 153, - "src/renderer/src/components/editor/csv/useCsvPagedPreview.test.tsx": 429, - "src/renderer/src/components/editor/csv/useCsvPendingCell.test.tsx": 714, + "src/renderer/src/components/editor/csv/document/csv-byte-index.test.ts": 1645, + "src/renderer/src/components/editor/csv/grid/csv-cell-links.test.tsx": 302, + "src/renderer/src/components/editor/csv/grid/columns/csv-column-width-preferences.test.ts": 208, + "src/renderer/src/components/editor/csv/preview/csv-paged-preview.test.ts": 143, + "src/renderer/src/components/editor/csv/document/csv-parse-budget.test.ts": 102, + "src/renderer/src/components/editor/csv/document/csv-parse.test.ts": 148, + "src/renderer/src/components/editor/save/queue/csv-pending-save.test.ts": 1926, + "src/renderer/src/components/editor/save/queue/csv-preview-save-safety.test.ts": 1973, + "src/renderer/src/components/editor/csv/editing/csv-table-interactions.test.ts": 310, + "src/renderer/src/components/editor/csv/document/csv-text-document.test.ts": 153, + "src/renderer/src/components/editor/csv/editing/useCsvPendingCell.test.tsx": 714, "src/renderer/src/components/editor/view-mode/custom-editor-routing.test.ts": 2715, "src/renderer/src/components/editor/rich-markdown/details/details-markdown-html.test.ts": 93, "src/renderer/src/components/editor/save/flush/discard-editor-file-changes.save-race.test.ts": 1150, @@ -4867,7 +4785,6 @@ "src/renderer/src/components/editor/save/bytes/editor-bytes-documents.test.ts": 690, "src/renderer/src/components/editor/save/commands/editor-child-owner-save.test.tsx": 2480, "src/renderer/src/components/editor/external-changes/editor-clean-tab-draft-invariant.test.ts": 1274, - "src/renderer/src/components/editor/editor-dropped-file-open.test.ts": 595, "src/renderer/src/components/editor/external-changes/editor-external-watch-path-index.test.ts": 1754, "src/renderer/src/components/editor/save/commands/editor-file-save-utf8-conversion.test.ts": 1915, "src/renderer/src/components/editor/editor-git-discard-other-workspace.test.ts": 1967, @@ -4875,7 +4792,6 @@ "src/renderer/src/components/editor/model-lifetime/identity/editor-model-host-isolation.test.ts": 5906, "src/renderer/src/components/editor/model-lifetime/identity/editor-model-uri-labels.test.ts": 1223, "src/renderer/src/components/editor/editor-path-move-inflight.test.ts": 50, - "src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.recheck.test.ts": 1796, "src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.test.ts": 1809, "src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.races.test.ts": 1290, "src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.test.ts": 1431, @@ -5104,7 +5020,6 @@ "src/renderer/src/components/native-chat/viewport/rail/NativeChatMessageRail.test.tsx": 1134, "src/renderer/src/components/native-chat/NativeChatNewRowsMarker.test.tsx": 3019, "src/renderer/src/components/native-chat/usage/NativeChatNoticeRow.test.tsx": 3399, - "src/renderer/src/components/native-chat/pane/actions/NativeChatPaneHeader.test.tsx": 2736, "src/renderer/src/components/native-chat/composer/editor/NativeChatPromptEditor.paragraph-selection.test.tsx": 652, "src/renderer/src/components/native-chat/composer/editor/NativeChatPromptEditor.test.tsx": 1110, "src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.test.tsx": 762, @@ -5259,7 +5174,6 @@ "src/renderer/src/components/new-workspace/SmartWorkspaceNameField-repo-slug-routing.test.ts": 342, "src/renderer/src/components/new-workspace/smart-workspace-github-direct-link.test.ts": 347, "src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts": 136, - "src/renderer/src/components/new-workspace/use-jira-composer-project.test.tsx": 279, "src/renderer/src/components/new-workspace/use-jira-source-connection.test.tsx": 278, "src/renderer/src/components/new-workspace/use-jira-url-source.test.tsx": 419, "src/renderer/src/components/new-workspace/use-linear-source-connection.test.tsx": 1335, @@ -5286,7 +5200,6 @@ "src/renderer/src/components/plugins/view/plugin-view-data-acts.test.tsx": 3002, "src/renderer/src/components/plugins/view/plugin-view-editor-capture.test.tsx": 1934, "src/renderer/src/components/plugins/view/plugin-view-editor-shot-cleanup.test.ts": 59, - "src/renderer/src/components/plugins/view/plugin-view-editor-workspace.test.ts": 99, "src/renderer/src/components/plugins/view/plugin-view-panel-settle.test.ts": 206, "src/renderer/src/components/plugins/view/plugin-view-request-handler-workspace.test.ts": 2307, "src/renderer/src/components/plugins/view/plugin-view-request-handler.test.ts": 2849, @@ -5366,7 +5279,6 @@ "src/renderer/src/components/right-sidebar/source-control/review/source-control-create-pr-intent-flow.test.ts": 71, "src/renderer/src/components/right-sidebar/source-control/review/source-control-manual-review-url.test.ts": 77, "src/renderer/src/components/right-sidebar/source-control/listing/source-control-submodule-expansion.test.ts": 80, - "src/renderer/src/components/right-sidebar/source-control/ai/use-ai.operation-recovery.test.tsx": 13031, "src/renderer/src/components/right-sidebar/source-control/commit/rename-mutation-paths.test.ts": 49, "src/renderer/src/components/right-sidebar/source-control/commit/source-control-entry-failure-toast.test.ts": 486, "src/renderer/src/components/right-sidebar/source-control/commit/use-commit-message-generation.cancel.test.ts": 1992, @@ -5375,7 +5287,6 @@ "src/renderer/src/components/right-sidebar/source-control/review/create-pr-intent-operation-target.test.ts": 1735, "src/renderer/src/components/right-sidebar/source-control/review/use-create-pr-intent-jira-title.test.tsx": 1956, "src/renderer/src/components/right-sidebar/source-control/review/use-pull-request-generation.test.tsx": 2720, - "src/renderer/src/components/right-sidebar/ssh-port-forward-dialog.ime-enter.test.tsx": 585, "src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.test.tsx": 688, "src/renderer/src/components/right-sidebar/checks-panel/refresh/use-checks-panel-terminal-worktree.test.ts": 2116, "src/renderer/src/components/right-sidebar/hosted-review/creation/use-create-jira-review-title.test.tsx": 1979, @@ -5519,7 +5430,6 @@ "src/renderer/src/components/sidebar/host-path-browser/remote-file-browser-entry-actions.test.ts": 289, "src/renderer/src/components/sidebar/worktree-list/listing/rendered-sidebar-worktree-order.test.ts": 1873, "src/renderer/src/components/sidebar/project-admission/drop/sidebar-project-drop.test.ts": 227, - "src/renderer/src/components/sidebar/project-admission/host-selection/use-add-repo-windows-drive-refusal.test.tsx": 470, "src/renderer/src/components/sidebar/project-admission/host-selection/use-add-repo-wsl-host-paths.test.tsx": 660, "src/renderer/src/components/sidebar/sidebar-feedback/use-feedback-image-drop.test.tsx": 511, "src/renderer/src/components/sidebar/workspace-board/projection/use-workspace-board-task-status-sync.queued.test.ts": 1022, @@ -5594,7 +5504,6 @@ "src/renderer/src/components/status-bar/resource-session-kill-confirmation.test.ts": 53, "src/renderer/src/components/status-bar/resource-session-removal-render-budget.test.tsx": 290, "src/renderer/src/components/status-bar/resource-usage-folder-merge.test.ts": 251, - "src/renderer/src/components/status-bar/status-bar-pool-countdown.test.tsx": 654, "src/renderer/src/components/status-bar/usage-pool-label.test.ts": 170, "src/renderer/src/components/status-bar/use-owner-usage-rate-limits.test.tsx": 462, "src/renderer/src/components/status-bar/use-resource-memory-snapshot.test.tsx": 321, @@ -5609,10 +5518,8 @@ "src/renderer/src/components/tab-bar/cli-chat-resume-run-close.test.ts": 3079, "src/renderer/src/components/tab-bar/group-tab-order.test.ts": 2091, "src/renderer/src/components/tab-bar/host-agent-launch-preferences-source.test.tsx": 3154, - "src/renderer/src/components/tab-bar/recent-tab-switching.test.ts": 1795, "src/renderer/src/components/tab-bar/tab-agent-launch-options.test.ts": 438, "src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.test.ts": 206, - "src/renderer/src/components/tab-bar/tab-bar-layout-owner-props.test.ts": 174, "src/renderer/src/components/tab-bar/tab-context-menu.test.tsx": 5620, "src/renderer/src/components/tab-bar/tab-create-entry-classifier.test.ts": 510, "src/renderer/src/components/tab-bar/tab-create-entry-local-path.test.ts": 2614, @@ -5645,7 +5552,6 @@ "src/renderer/src/components/task-page/jira/task-page-jira-board-detail-integration.test.tsx": 2192, "src/renderer/src/components/task-page/jira/task-page-jira-board-transitions.test.ts": 69, "src/renderer/src/components/task-page/jira/task-page-jira-board-view.test.tsx": 2287, - "src/renderer/src/components/task-page/jira/task-page-jira-cache-selectors.test.ts": 54, "src/renderer/src/components/task-page/jira/task-page-jira-favourite-selection.test.tsx": 3326, "src/renderer/src/components/task-page/jira/task-page-jira-grouping.test.ts": 2324, "src/renderer/src/components/task-page/jira/task-page-jira-linked-issues.test.ts": 204, @@ -5719,14 +5625,11 @@ "src/renderer/src/components/terminal-pane/pty-connection/agent-identity/pty-connection-command-finished-late-done.test.ts": 10940, "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts": 18380, "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-foreground-agent.test.ts": 20118, - "src/renderer/src/components/terminal-pane/pty-connection/lifecycle/pty-connection-git-bash-console-capacity.test.ts": 5784, "src/renderer/src/components/terminal-pane/pty-connection/lifecycle/pty-connection-hibernation-kill-shell-foreground.test.ts": 2205, - "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts": 21687, "src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-restore-marker-handoff.test.ts": 2170, "src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-restore-unhide-coverage.test.ts": 4612, "src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-restore-unhide-retired-task.test.ts": 1947, "src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-hook-idle-arbitration.test.ts": 2228, - "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts": 21974, "src/renderer/src/components/terminal-pane/pty-connection/spawn/pty-connection-main-pane-restore-start.test.ts": 2430, "src/renderer/src/components/terminal-pane/pty-connection/spawn/pty-connection-main-pane-start.test.ts": 2611, "src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-post-dispose-restore-termination.test.ts": 1215, @@ -5736,9 +5639,7 @@ "src/renderer/src/components/terminal-pane/pty-connection/reattach/pty-connection-remote-snapshot-image-title.test.ts": 1754, "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-restore-and-resume.test.ts": 19401, "src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-restored-baseline-shortfall.test.ts": 1902, - "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts": 19652, "src/renderer/src/components/terminal-pane/pty-connection/spawn/pty-connection-spawn-deferred-sleep.test.ts": 6918, - "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts": 18950, "src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-visible-pane-output-pause-latch.test.ts": 1639, "src/renderer/src/components/terminal-pane/pty-connection/reattach/deferred-session-reattach-newer-daemon-hold.test.ts": 2570, "src/renderer/src/components/terminal-pane/pty-connection/reattach/deferred-session-reattach-startup-snapshot.test.ts": 1830, @@ -5848,7 +5749,6 @@ "src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts": 99, "src/renderer/src/components/terminal-pane/links/terminal-link-click-fallback.test.ts": 985, "src/renderer/src/components/terminal-pane/links/terminal-link-open-beside-source.test.ts": 947, - "src/renderer/src/components/terminal-pane/links/http/terminal-link-osc-url-routing.test.ts": 986, "src/renderer/src/components/terminal-pane/links/terminal-link-paired-click-fallback.test.ts": 989, "src/renderer/src/components/terminal-pane/links/gestures/terminal-link-pointer-gesture.test.ts": 550, "src/renderer/src/components/terminal-pane/links/files/terminal-link-provider-batching.test.ts": 1051, @@ -5867,7 +5767,6 @@ "src/renderer/src/components/terminal-pane/layout/split/terminal-pane-split-request-routing.test.ts": 2015, "src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-commit.test.ts": 2090, "src/renderer/src/components/terminal-pane/layout/detach/terminal-pane-tab-detach-main-move.test.ts": 2147, - "src/renderer/src/components/terminal-pane/parking/verdict/terminal-park-verdict-flip-telemetry.test.ts": 123, "src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts": 473, "src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-registry.test.ts": 245, "src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-sleep-preserved-exit.test.ts": 399, @@ -5909,7 +5808,6 @@ "src/renderer/src/components/terminal/terminal-tab-actions-unrouted-close.test.ts": 589, "src/renderer/src/components/terminal/terminal-tab-actions.test.ts": 626, "src/renderer/src/components/terminal/terminal-tab-close-running-confirm.test.ts": 499, - "src/renderer/src/components/terminal/terminal-tab-create.test.ts": 367, "src/renderer/src/components/terminal/unsaved-close-queue.test.ts": 42, "src/renderer/src/components/terminal/use-terminal-provider-snapshot-capability.test.tsx": 573, "src/renderer/src/components/terminal/window-close-running-work.test.ts": 97, @@ -5949,7 +5847,6 @@ "src/renderer/src/components/worktree-jump/use-worktree-jump-palette-browser-ownership.test.ts": 2096, "src/renderer/src/components/worktree-jump/use-worktree-jump-palette-task-search.test.tsx": 2140, "src/renderer/src/components/worktree-jump/worktree-jump-palette-browser-navigation.test.tsx": 4470, - "src/renderer/src/components/wsl-host-stopped/WslHostStoppedNotice.test.tsx": 491, "src/renderer/src/components/wsl-move/WslMoveDialog.test.tsx": 524, "src/renderer/src/components/wsl-move/wsl-move-dialog-store.test.ts": 2011, "src/renderer/src/components/wsl-move/wsl-move-scope-rows.test.ts": 156, @@ -5984,7 +5881,6 @@ "src/renderer/src/hooks/ipc-events/direct-ssh-unrestored-forward-sync.test.ts": 95, "src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge-reveal.test.ts": 1764, "src/renderer/src/hooks/ipc-events/mobile-terminal-close-ipc-bridge.test.ts": 2200, - "src/renderer/src/hooks/ipc-events/orca-profile-auth-ipc-bridge.test.ts": 1908, "src/renderer/src/hooks/ipc-events/os-markdown-file-open-bridge.test.ts": 280, "src/renderer/src/hooks/ipc-events/quit-and-stop-all-sessions-ipc-bridge.test.ts": 398, "src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge-ownership.test.ts": 2068, @@ -6007,7 +5903,6 @@ "src/renderer/src/hooks/runtime-client-events-sync-ownership.test.ts": 59, "src/renderer/src/hooks/runtime-client-events-sync.test.ts": 118, "src/renderer/src/hooks/runtime-project-refresh-scheduler.test.ts": 65, - "src/renderer/src/hooks/shortcut-label-cache.test.tsx": 2021, "src/renderer/src/hooks/unpaired-device-auth-notification.test.ts": 41, "src/renderer/src/hooks/use-document-dark-theme.test.tsx": 350, "src/renderer/src/hooks/use-list-multi-selection.test.tsx": 545, @@ -6040,7 +5935,6 @@ "src/renderer/src/hooks/useIpcEvents-agent-status-queue-ordering.test.ts": 3680, "src/renderer/src/hooks/useIpcEvents-agent-status-snapshot-replay.test.ts": 4119, "src/renderer/src/hooks/useIpcEvents-agent-status-ssh-authority.test.ts": 3310, - "src/renderer/src/hooks/useIpcEvents-browser-navigation.test.ts": 1511, "src/renderer/src/hooks/useIpcEvents-close-routing-session-tabs.test.ts": 5812, "src/renderer/src/hooks/useIpcEvents-new-workspace-shortcut.test.ts": 72, "src/renderer/src/hooks/useIpcEvents-runtime-environment-selectors.test.ts": 530, @@ -6085,12 +5979,10 @@ "src/renderer/src/lib/agent-session/resume/agent-resume-launch-target.test.ts": 3911, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-after-failure.test.ts": 870, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-exited-owner.test.ts": 1289, - "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-join-delivery.test.ts": 862, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-options.test.ts": 991, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-persistence.test.ts": 386, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-probe-outage.test.ts": 1891, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-record.test.ts": 151, - "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-resume-identity.test.ts": 828, "src/renderer/src/lib/agent-session/launch/startup/agent-startup-delayed-delivery-perf.test.ts": 1708, "src/shared/agent-status/contracts/agent-status-evidence-clock.test.ts": 88, "src/shared/agent-status/title/agent-title-tracker.test.ts": 172, @@ -6102,7 +5994,6 @@ "src/renderer/src/lib/agent-session/resume/history/ai-vault-session-drag.test.ts": 68, "src/renderer/src/lib/agent-session/resume/history/ai-vault-session-resume-preparation.test.ts": 408, "src/renderer/src/lib/agent-session/history/title-sync/ai-vault-tab-title-sync-inputs.test.ts": 476, - "src/renderer/src/lib/agent-session/history/title-sync/ai-vault-tab-title-sync.test.ts": 925, "src/renderer/src/lib/keyboard/app-keyboard-router.test.ts": 187, "src/renderer/src/lib/clipboard/menu/app-menu-paste.test.ts": 229, "src/renderer/src/lib/automation-session-reuse.test.ts": 70, @@ -6135,12 +6026,8 @@ "src/renderer/src/lib/browser/navigation/http-link-routing-store.test.ts": 2211, "src/renderer/src/lib/text-input/ime/ime-composition-keyboard-event.test.ts": 274, "src/renderer/src/lib/text-input/ime/ime-text-field.test.tsx": 739, - "src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts": 48, "src/renderer/src/lib/agent-session/launch/background/launch-agent-background-session-launch-parity.test.ts": 2792, "src/renderer/src/lib/agent-session/launch/background/launch-agent-background-session.test.ts": 1040, - "src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts": 1821, - "src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-windows-quoting.test.ts": 1196, - "src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab.test.ts": 1417, "src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-new-tab-host-route-readiness.test.ts": 489, "src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-picker-contract.test.ts": 3592, "src/renderer/src/lib/agent-session/launch/continuation/launch-agent-session-continuation-toast.test.tsx": 2347, @@ -6162,7 +6049,6 @@ "src/renderer/src/lib/monaco-languages/register-vue.test.ts": 303, "src/renderer/src/lib/monaco-languages/register-zig.test.ts": 4750, "src/renderer/src/lib/monaco-languages/textmate-token-provider.test.ts": 245, - "src/renderer/src/lib/monaco-languages/zig-highlighting.test.ts": 7984, "src/renderer/src/lib/agent-session/resume/cli-fork/native-chat-cli-fork-preparation.test.ts": 2773, "src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts": 545, "src/renderer/src/lib/pane-manager/pane-close-focus-successor.test.ts": 1123, @@ -6347,10 +6233,8 @@ "src/renderer/src/store/plugins/catalog/plugin-panel-retry-timer-cleanup.test.ts": 5216, "src/renderer/src/store/plugins/catalog/plugin-panels.test.ts": 2142, "src/renderer/src/store/projects/project-catalog-null-field-ingest.test.ts": 309, - "src/renderer/src/store/diagnostics/react-commit-cascade-write-probe.test.ts": 602, "src/renderer/src/store/repos/dropped-repo-worktree-rows.test.ts": 1738, "src/renderer/src/store/repos/repo-removal.test.ts": 799, - "src/renderer/src/store/repos/safe-auto-fork-sync.test.ts": 446, "src/renderer/src/store/repos/wsl-moved-local-session-rows.test.ts": 319, "src/renderer/src/store/repos/wsl-moved-repo-ui-retention.test.ts": 2920, "src/renderer/src/store/slices/runtime-status/views/runtime-status-subscriptions.test.ts": 182, @@ -6414,7 +6298,6 @@ "src/renderer/src/store/slices/editor/buffers/editor-buffer-reconcile-identity.test.ts": 1775, "src/renderer/src/store/slices/editor/buffers/editor-buffer-reconcile-joins.test.ts": 1766, "src/renderer/src/store/slices/editor/buffers/editor-buffer-rejoin.test.ts": 1843, - "src/renderer/src/store/slices/editor/buffers/editor-buffer-views.test.ts": 2004, "src/renderer/src/store/slices/editor/file-ids/floating-editor-file-id-layout-owner.test.ts": 933, "src/renderer/src/store/slices/worktrees/session/folder-workspace-activation-and-activity.test.ts": 2358, "src/renderer/src/store/slices/diff-comments/folder-workspace-diff-comments.test.ts": 1042, @@ -6497,7 +6380,6 @@ "src/renderer/src/store/slices/tabs/tabs-hydration-group-validation.test.ts": 249, "src/renderer/src/store/slices/tabs/tabs-hydration.test.ts": 273, "src/renderer/src/store/slices/tabs/tabs-label-and-pin-state.test.ts": 1921, - "src/renderer/src/store/slices/tabs/tabs-model-reconciliation.test.ts": 1800, "src/renderer/src/store/slices/tabs/tabs-open-close-lifecycle.test.ts": 2140, "src/renderer/src/store/slices/tabs/tabs-pane-layout-operations.test.ts": 1652, "src/renderer/src/store/slices/tabs/tabs-unread-and-focus.test.ts": 1801, @@ -6517,7 +6399,6 @@ "src/renderer/src/store/slices/ui/ui-modal-slot-dismissal.test.ts": 662, "src/renderer/src/store/slices/ui/ui-slice-surface-actions.test.ts": 1760, "src/renderer/src/store/slices/worktrees/session/workspace-activation-preparation.test.ts": 1932, - "src/renderer/src/store/slices/workspace-attention/workspace-unread-characterization.test.ts": 1974, "src/renderer/src/store/slices/workspace-attention/workspace-unread-flag-host-raises.test.ts": 1914, "src/renderer/src/store/slices/workspace-attention/workspace-unread-on-screen-characterization.test.ts": 1780, "src/renderer/src/store/slices/workspace-attention/workspace-unread-screen-moves-characterization.test.ts": 1884, @@ -6575,7 +6456,6 @@ "src/renderer/src/store/terminals/terminal-no-op-subscriber.test.ts": 1763, "src/renderer/src/store/terminals/terminal-startup-queue-restart.test.ts": 1895, "src/renderer/src/store/terminals/terminal-tab-close-intent.test.ts": 1945, - "src/renderer/src/store/terminals/workspace-terminal-placeholders.test.ts": 302, "src/renderer/src/store/slices/runtime-status/views/use-runtime-status-view.test.tsx": 1979, "src/renderer/src/store/workspace-layout/workspace-layout-cache.test.ts": 63, "src/renderer/src/store/slices/worktrees/listing/worktree-host-collision-index.test.ts": 1875, @@ -7066,7 +6946,6 @@ "src/shared/orca-session-address.test.ts": 154, "src/shared/orca-yaml-alias-bounds.test.ts": 425, "src/shared/orca-yaml-bounds.test.ts": 192, - "src/shared/orcad-artifacts.test.ts": 45, "src/shared/orcad-build-identity.test.ts": 48, "src/shared/orcad-migration-manifest-contract.test.ts": 323, "src/shared/orcad-migration/orcad-migration-blob-transfer.test.ts": 348, @@ -7576,7 +7455,6 @@ "tests/e2e/host-agent-launch-settings-hook-bookkeeping.unit.test.ts": 21972, "tests/e2e/host-cold-park-remote-subscriber.unit.test.ts": 5314, "tests/e2e/launch-agent-background-session-remote.unit.test.ts": 1016, - "tests/e2e/launch-agent-in-new-tab-web-runtime.unit.test.ts": 14288, "tests/e2e/linear-cli-recovery.unit.test.ts": 7592, "tests/e2e/linear-store.unit.test.ts": 519, "tests/e2e/linear-write-lifetime.unit.test.ts": 5214, @@ -7699,10 +7577,6 @@ "src/main/skills/install/skill-wsl-install-transaction.integration.test.ts": 250, "src/main/skills/filesystem/skill-wsl-posix-semantics.integration.test.ts": 254, "src/renderer/src/lib/pane-manager/terminal-scroll/pane-scroll.test.ts": 153, - "src/renderer/src/lib/pane-manager/terminal-input/pane-terminal-mouse-wheel.test.ts": 88, - "src/renderer/src/lib/pane-manager/pane-layout/pane-tree-equalization-parity.test.ts": 182, - "src/renderer/src/lib/pane-manager/terminal-input/terminal-ime-anchor.test.ts": 51, - "src/renderer/src/lib/pane-manager/terminal-scroll/terminal-scroll-intent.test.ts": 118, "src/renderer/src/lib/pane-manager/terminal-replay/terminal-structural-replay-coordinator.test.ts": 68, "src/renderer/src/lib/pane-manager/terminal-protocol/windows-pty-compatibility.test.ts": 68 } diff --git a/config/scripts/mobile-web/check-entry/mobile-test-change-scope.mjs b/config/scripts/mobile-web/check-entry/mobile-test-change-scope.mjs index 76328d54edb..1c2c90ff286 100644 --- a/config/scripts/mobile-web/check-entry/mobile-test-change-scope.mjs +++ b/config/scripts/mobile-web/check-entry/mobile-test-change-scope.mjs @@ -27,7 +27,6 @@ const DESKTOP_SUITE_PREFIXES = [ 'src/main/runtime/agent-session/agent-session-account-', 'src/main/runtime/agent-session/agent-session-acquisition-', 'src/main/runtime/agent-session/agent-session-conversation-', - 'src/main/runtime/agent-session/agent-session-death-', 'src/main/runtime/agent-session/agent-session-launch-', 'src/main/runtime/agent-session/agent-session-operation-', 'src/main/runtime/agent-session/agent-session-rewind-', diff --git a/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs b/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs index cc412c5eb09..a9fa7066888 100644 --- a/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs +++ b/config/scripts/orcad-distribution/server-bundle/orcad-entry-build.mjs @@ -20,7 +20,7 @@ export const ORCAD_CHILD_ENTRY_POINTS = { daemon: 'src/main/daemon/daemon-entry.ts', writer: 'src/main/persistence/profile-state/profile-state-writer-worker-entry.ts', backup: 'src/main/persistence/profile-state/profile-state-backup-worker-entry.ts', - sessionSearch: 'src/main/ai-vault-search/session-search-worker-entry.ts', + sessionSearch: 'src/main/ai-vault-search/worker/session-search-worker-entry.ts', foreignSqliteReader: 'src/main/foreign-sqlite-readers/foreign-sqlite-reader-entry.ts', portScanCommandWorker: 'src/main/ports/port-scan-command-worker-entry.ts', commandPathDirectoryWorker: 'src/main/ipc/command-path/command-path-directory-worker-entry.ts', diff --git a/config/scripts/performance/claude-usage/claude-usage-benchmark-persistence.mjs b/config/scripts/performance/claude-usage/claude-usage-benchmark-persistence.mjs index 7e52c72b0e7..6235bdbe039 100644 --- a/config/scripts/performance/claude-usage/claude-usage-benchmark-persistence.mjs +++ b/config/scripts/performance/claude-usage/claude-usage-benchmark-persistence.mjs @@ -27,14 +27,40 @@ export function resolveClaudeBenchmarkCommit(ref) { } const SNAPSHOT_MODULE_PATHS = [ + 'src/main/usage/cache/usage-cache-snapshot-writer.ts', 'src/main/usage/usage-cache-snapshot-writer.ts', 'src/main/usage-cache-snapshot-writer.ts' ] +const PERSISTENCE_MODULE_PATHS = { + snapshot: SNAPSHOT_MODULE_PATHS, + lifecycle: [ + 'src/main/usage/provider-lifecycle/usage-provider-store-lifecycle.ts', + 'src/main/usage/usage-provider-store-lifecycle.ts' + ], + sourceCache: [ + 'src/main/usage/cache/usage-source-cache-file.ts', + 'src/main/usage/usage-source-cache-file.ts' + ] +} -function persistenceEntry(mode) { +function listClaudeBenchmarkModulePaths(commit, modulePaths) { + const listed = runProcessSync({ + program: 'git', + args: ['ls-tree', '--name-only', commit, '--', ...modulePaths], + cwd: ROOT, + timeoutMs: 10_000, + maxOutputBytes: MIB, + env: { ...process.env, ORCA_BACKGROUND_LAUNCH: '1' } + }) + assert.equal(listed.code, 0, listed.stderr) + assert.equal(listed.outputTruncated, false) + return new Set(listed.stdout.trim().split('\n')) +} + +function persistenceEntry(mode, modulePaths) { const exports = [ - `export { UsageCacheSnapshotWriter } from './src/main/usage/usage-cache-snapshot-writer';`, - `export { UsageProviderStoreLifecycle } from './src/main/usage/usage-provider-store-lifecycle';` + `export { UsageCacheSnapshotWriter } from './${modulePaths.snapshot.slice(0, -3)}';`, + `export { UsageProviderStoreLifecycle } from './${modulePaths.lifecycle.slice(0, -3)}';` ] if (mode === 'published') { exports.push(`export { validatePersistedClaudeUsageProjections } @@ -42,7 +68,7 @@ function persistenceEntry(mode) { } else if (mode === 'main') { exports.push(`export { readUsageSourceCache as readSourceCache, writeUsageSourceCache as writeSourceCache, splitUsageCacheFile as splitCacheFile } - from './src/main/usage/usage-source-cache-file';`) + from './${modulePaths.sourceCache.slice(0, -3)}';`) } else { exports.push(`export { readClaudeUsageSourceCache as readSourceCache, writeClaudeUsageSourceCache as writeSourceCache, persistClaudeUsageSourceCache as persistSourceCache, @@ -75,24 +101,25 @@ const INACTIVE_LIFECYCLE_IMPORTS = new Map([ export async function loadClaudeUsageBenchmarkPersistence(mode, commit = null, frozen = new Map()) { const sourceFingerprints = {} const stubFingerprints = {} - let snapshotModulePath = SNAPSHOT_MODULE_PATHS[0] + const modulePaths = Object.fromEntries( + Object.entries(PERSISTENCE_MODULE_PATHS).map(([name, paths]) => [name, paths[0]]) + ) + const nativeModulePaths = new Map() if (typeof commit === 'string') { - const listed = runProcessSync({ - program: 'git', - args: ['ls-tree', '--name-only', commit, '--', ...SNAPSHOT_MODULE_PATHS], - cwd: ROOT, - timeoutMs: 10_000, - maxOutputBytes: MIB, - env: { ...process.env, ORCA_BACKGROUND_LAUNCH: '1' } - }) - assert.equal(listed.code, 0, listed.stderr) - assert.equal(listed.outputTruncated, false) - const paths = new Set(listed.stdout.trim().split('\n')) - snapshotModulePath = SNAPSHOT_MODULE_PATHS.find((path) => paths.has(path)) - assert(snapshotModulePath, 'Pinned usage snapshot writer is absent') + const paths = listClaudeBenchmarkModulePaths( + commit, + Object.values(PERSISTENCE_MODULE_PATHS).flat() + ) + for (const [name, candidates] of Object.entries(PERSISTENCE_MODULE_PATHS)) { + if (name === 'sourceCache' && mode !== 'main') { + continue + } + modulePaths[name] = candidates.find((path) => paths.has(path)) + assert(modulePaths[name], `Pinned usage ${name} is absent`) + } } const result = await build({ - stdin: { contents: persistenceEntry(mode), loader: 'ts', resolveDir: ROOT }, + stdin: { contents: persistenceEntry(mode, modulePaths), loader: 'ts', resolveDir: ROOT }, platform: 'node', format: 'esm', bundle: true, @@ -107,7 +134,7 @@ export async function loadClaudeUsageBenchmarkPersistence(mode, commit = null, f .join('/') const modulePath = resolved.endsWith('.ts') ? resolved : `${resolved}.ts` return SNAPSHOT_MODULE_PATHS.includes(modulePath) - ? { path: resolve(ROOT, snapshotModulePath) } + ? { path: resolve(ROOT, modulePaths.snapshot) } : undefined }) bundler.onResolve( @@ -122,6 +149,29 @@ export async function loadClaudeUsageBenchmarkPersistence(mode, commit = null, f return match ? { path: match, namespace: 'inactive-lifecycle' } : undefined } ) + bundler.onResolve({ filter: /^\./ }, (args) => { + if (typeof commit !== 'string') { + return undefined + } + const target = relative(ROOT, resolve(args.resolveDir, args.path)).split(sep).join('/') + if (!target.startsWith('src/')) { + return undefined + } + if (!nativeModulePaths.has(target)) { + const extensions = ['.tsx', '.ts', '.jsx', '.js', '.css', '.json'] + const candidates = extname(target) + ? [target] + : [ + ...extensions.map((extension) => target + extension), + ...extensions.map((extension) => `${target}/index${extension}`) + ] + const paths = listClaudeBenchmarkModulePaths(commit, candidates) + const modulePath = candidates.find((path) => paths.has(path)) + assert(modulePath, `Pinned usage source is absent: ${String(commit)}:${target}`) + nativeModulePaths.set(target, modulePath) + } + return { path: resolve(ROOT, nativeModulePaths.get(target)) } + }) bundler.onLoad({ filter: /.*/, namespace: 'inactive-lifecycle' }, (args) => { const contents = INACTIVE_LIFECYCLE_IMPORTS.get(args.path) stubFingerprints[args.path] = claudeBenchmarkSha256(contents) diff --git a/config/scripts/performance/session-search/session-search-query-benchmark.ts b/config/scripts/performance/session-search/session-search-query-benchmark.ts index 48121c37ac7..3221aa5d151 100644 --- a/config/scripts/performance/session-search/session-search-query-benchmark.ts +++ b/config/scripts/performance/session-search/session-search-query-benchmark.ts @@ -6,20 +6,20 @@ import { } from '../../../../src/main/ai-vault/parse-cache/session-scanner-parse-cache' import { resetSessionParseCacheForTests } from '../../../../src/main/ai-vault/parse-cache/session-parse-cache-store' import { resetTranscriptConsumersForTests } from '../../../../src/main/ai-vault/transcripts/session-transcript-consumers' -import { SessionSearchEngine } from '../../../../src/main/ai-vault-search/session-search-engine' +import { SessionSearchEngine } from '../../../../src/main/ai-vault-search/query/session-search-engine' import type { SessionSearchRequest, SessionSearchScope -} from '../../../../src/main/ai-vault-search/session-search-engine-types' -import { registerSessionSearchIndexConsumer } from '../../../../src/main/ai-vault-search/session-search-index-consumer' -import { SessionSearchStore } from '../../../../src/main/ai-vault-search/session-search-store' +} from '../../../../src/main/ai-vault-search/query/session-search-engine-types' +import { registerSessionSearchIndexConsumer } from '../../../../src/main/ai-vault-search/indexing/session-search-index-consumer' +import { SessionSearchStore } from '../../../../src/main/ai-vault-search/storage/session-search-store' import type SyncDatabase from '../../../../src/main/sqlite/sync-database' import { writeSyntheticTranscriptCorpus, type SyntheticCorpus, type SyntheticCorpusOptions -} from '../../../../src/main/ai-vault-search/session-search-synthetic-corpus' -import { sessionCandidate } from '../../../../src/main/ai-vault-search/session-search-transcript-fixtures' +} from '../../../../src/main/ai-vault-search/indexing/session-search-synthetic-corpus' +import { sessionCandidate } from '../../../../src/main/ai-vault-search/indexing/session-search-transcript-fixtures' // Measure real engine/store on synthetic corpus only; never use real transcripts. diff --git a/config/scripts/performance/session-search/session-search-scope-benchmark.ts b/config/scripts/performance/session-search/session-search-scope-benchmark.ts index c1c6fdb979a..c644806d915 100644 --- a/config/scripts/performance/session-search/session-search-scope-benchmark.ts +++ b/config/scripts/performance/session-search/session-search-scope-benchmark.ts @@ -6,14 +6,14 @@ import { } from '../../../../src/main/ai-vault/parse-cache/session-scanner-parse-cache' import { resetSessionParseCacheForTests } from '../../../../src/main/ai-vault/parse-cache/session-parse-cache-store' import { resetTranscriptConsumersForTests } from '../../../../src/main/ai-vault/transcripts/session-transcript-consumers' -import { SessionSearchEngine } from '../../../../src/main/ai-vault-search/session-search-engine' +import { SessionSearchEngine } from '../../../../src/main/ai-vault-search/query/session-search-engine' import type { SessionSearchRequest, SessionSearchScope -} from '../../../../src/main/ai-vault-search/session-search-engine-types' -import { registerSessionSearchIndexConsumer } from '../../../../src/main/ai-vault-search/session-search-index-consumer' -import { SessionSearchStore } from '../../../../src/main/ai-vault-search/session-search-store' -import { sessionCandidate } from '../../../../src/main/ai-vault-search/session-search-transcript-fixtures' +} from '../../../../src/main/ai-vault-search/query/session-search-engine-types' +import { registerSessionSearchIndexConsumer } from '../../../../src/main/ai-vault-search/indexing/session-search-index-consumer' +import { SessionSearchStore } from '../../../../src/main/ai-vault-search/storage/session-search-store' +import { sessionCandidate } from '../../../../src/main/ai-vault-search/indexing/session-search-transcript-fixtures' import type SyncDatabase from '../../../../src/main/sqlite/sync-database' import { writeToolHeavyCorpus, type ToolHeavyCorpus } from './session-search-tool-heavy-corpus' diff --git a/config/scripts/performance/session-search/session-search-write-benchmark.ts b/config/scripts/performance/session-search/session-search-write-benchmark.ts index c2c07e1249a..285c3be68de 100644 --- a/config/scripts/performance/session-search/session-search-write-benchmark.ts +++ b/config/scripts/performance/session-search/session-search-write-benchmark.ts @@ -9,10 +9,10 @@ import { import { resetSessionParseCacheForTests } from '../../../../src/main/ai-vault/parse-cache/session-parse-cache-store' import { resetTranscriptConsumersForTests } from '../../../../src/main/ai-vault/transcripts/session-transcript-consumers' import { requestWholeTranscriptRead } from '../../../../src/main/ai-vault/transcripts/session-transcript-reader' -import { registerSessionSearchIndexConsumer } from '../../../../src/main/ai-vault-search/session-search-index-consumer' -import { SessionSearchStore } from '../../../../src/main/ai-vault-search/session-search-store' -import { writeSyntheticTranscriptCorpus } from '../../../../src/main/ai-vault-search/session-search-synthetic-corpus' -import { sessionCandidate } from '../../../../src/main/ai-vault-search/session-search-transcript-fixtures' +import { registerSessionSearchIndexConsumer } from '../../../../src/main/ai-vault-search/indexing/session-search-index-consumer' +import { SessionSearchStore } from '../../../../src/main/ai-vault-search/storage/session-search-store' +import { writeSyntheticTranscriptCorpus } from '../../../../src/main/ai-vault-search/indexing/session-search-synthetic-corpus' +import { sessionCandidate } from '../../../../src/main/ai-vault-search/indexing/session-search-transcript-fixtures' import SyncDatabase from '../../../../src/main/sqlite/sync-database' // Measures the real transcript reader and search store over a synthetic corpus. diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs index d7542ed8616..c02d22120c4 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs @@ -12,7 +12,7 @@ const NODE_RUNTIME_INCLUDE = [ 'src/packages/process-host/src/run-process.test.ts', 'tests/e2e/cursor-quota-transport.unit.test.ts', 'tests/e2e/helpers/electron-process-shutdown.unit.test.ts', - 'src/main/ai-vault-search/session-search-index-writer.test.ts', + 'src/main/ai-vault-search/storage/session-search-index-writer.test.ts', 'src/main/ai-vault/session-scanner-unlimited-dedup.test.ts', // The parse cache persists through node:sqlite. 'src/main/ai-vault/parse-cache/session-parse-cache-antigravity-upgrade.test.ts', @@ -39,8 +39,8 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/claude/claude-transcript-duration.test.ts', 'tests/e2e/native-chat-startup-option-pickers.unit.test.ts', 'src/main/ai-vault/transcripts/session-document-consumer-replacement.test.ts', - 'src/main/ai-vault-search/session-search-dependent-transcripts.test.ts', - 'src/main/ai-vault-search/session-search-list-reparse.test.ts', + 'src/main/ai-vault-search/indexing/session-search-dependent-transcripts.test.ts', + 'src/main/ai-vault-search/indexing/session-search-list-reparse.test.ts', 'src/main/runtime/rpc/server/orchestration-cli-subprocess.test.ts', 'src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-delivery.test.ts', 'src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-routing.test.ts', @@ -104,8 +104,7 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/workspaces/removal/local-worktree-removal-recovery-live.test.ts', 'src/main/rate-limits/providers/codex/codex-rpc-worker-backpressure.test.ts', 'src/main/computer/macos-native-provider-client.test.ts', - 'src/main/ai-vault-search/session-search-schema.test.ts', - 'src/main/ai-vault-search/session-search-fts5-contract.test.ts', + 'src/main/ai-vault-search/storage/session-search-schema.test.ts', 'src/main/foreign-sqlite-readers/**/*.test.ts', 'src/main/browser/*cookie*.test.ts', 'src/main/browser/cookies/*cookie*.test.ts', diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs index 2259db54cb3..b52d995ed1c 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-sqlite-runtime-scan.mjs @@ -28,8 +28,8 @@ const SQLITE_HARNESSES = new Set([ ]) export const SQLITE_MODULES = [ 'src/main/sqlite/sync-database', - 'src/main/ai-vault-search/session-search-schema', - 'src/main/ai-vault-search/session-search-store', + 'src/main/ai-vault-search/storage/session-search-schema', + 'src/main/ai-vault-search/storage/session-search-store', 'src/main/persistence/profile-state/profile-state-sqlite-authority', 'src/main/native-chat/agent-session-journal/database/journal-host-database', 'src/main/runtime/orchestration/db', diff --git a/config/tsconfig.tc.web.json b/config/tsconfig.tc.web.json index a8d6f7c30cb..a8bf2c20c70 100644 --- a/config/tsconfig.tc.web.json +++ b/config/tsconfig.tc.web.json @@ -1,7 +1,6 @@ { "extends": "./tsconfig.web.json", "exclude": [ - "../src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts", "../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx", "../src/renderer/src/runtime/provider-accounts/observations/provider-account-observation.test-fixture.ts", "../src/shared/**/*.test.ts", diff --git a/config/tsconfig.test.pane-launch.json b/config/tsconfig.test.pane-launch.json index 0885af36f1d..ef0039b3bd9 100644 --- a/config/tsconfig.test.pane-launch.json +++ b/config/tsconfig.test.pane-launch.json @@ -1,7 +1,6 @@ { "extends": "./tsconfig.web.json", "include": [ - "../src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts", "../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts", "../src/main/runtime/rpc/methods/orchestration/orchestration-check-ambiguous-caller.test.ts", "../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx", diff --git a/config/tsconfig.web.json b/config/tsconfig.web.json index 8b5c4e283c7..97a75ba3e28 100644 --- a/config/tsconfig.web.json +++ b/config/tsconfig.web.json @@ -11,7 +11,6 @@ "../src/shared/**/*" ], "exclude": [ - "../src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts", "../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx", "../src/renderer/src/runtime/provider-accounts/observations/provider-account-observation.test-fixture.ts" ], diff --git a/config/vitest.performance.config.ts b/config/vitest.performance.config.ts index a068105564d..09f2b1bc311 100644 --- a/config/vitest.performance.config.ts +++ b/config/vitest.performance.config.ts @@ -8,19 +8,16 @@ const contracts = [ 'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts', 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts', 'src/shared/agent-launch/permissions/tui-agent-permission-choice.test.ts', - 'src/main/runtime/rpc/methods/projects/repo.test.ts', 'src/renderer/src/components/tab-bar/use-new-tab-agent-menu-host-preferences.test.tsx', 'src/main/sqlite/sync-database.test.ts', 'src/main/runtime/orchestration/db/row-column-lists.test.ts', 'src/shared/native-chat/tools/native-chat-tool-pairing.performance.test.ts', 'src/main/codex-usage/codex-rollout-file-lifetime.test.ts', 'src/main/codex-usage/scanner-incremental-append.test.ts', - 'src/main/usage/jsonl-file-reader.test.ts', - 'src/main/usage/jsonl-file-snapshot.test.ts', + 'src/main/usage/source-input/jsonl/jsonl-file-reader.test.ts', 'config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs', 'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs', - 'src/main/claude-usage/scanner-incremental-append.test.ts', - 'src/main/claude-usage/store-checkpoint-persistence.test.ts' + 'src/main/claude-usage/scanner-incremental-append.test.ts' ] for (const contract of contracts) { if (!existsSync(resolve(contract))) { diff --git a/docs/assets/readme-downloads.svg b/docs/assets/readme-downloads.svg index 2892989fee1..e2861c64f52 100644 --- a/docs/assets/readme-downloads.svg +++ b/docs/assets/readme-downloads.svg @@ -1,5 +1,5 @@ - - downloads: 169m + + downloads: 170m @@ -15,7 +15,7 @@ downloads downloads - 169m - 169m + 170m + 170m diff --git a/docs/site/content/docs/agents/supported.mdx b/docs/site/content/docs/agents/supported.mdx index 98313aa6d1a..2e68990f84e 100644 --- a/docs/site/content/docs/agents/supported.mdx +++ b/docs/site/content/docs/agents/supported.mdx @@ -52,7 +52,7 @@ If an agent's CLI is installed outside `PATH`, expand its row in **Settings → | Freebuff | Auto-setup | [Freebuff](https://freebuff.com/cli) | | Command Code | Auto-setup, status | [Command Code](https://commandcode.ai/docs/quickstart) | | Muse | macOS/Linux; trusts the workspace at launch | [Meta](https://dev.meta.ai/docs/muse-code) | -| DeepSeek Harness | Launched through its `dsh-tui` profile; hooks, status, questions, resume | [DeepSeek](https://deepseek-harness.github.io/deepseek-harness/) | +| DeepSeek Harness | Needs `@deepseek-ai/dsh` plus the community `@deepseek-harness-tui/dsh-tui`; hooks, status, questions, resume | [dsh-TUI](https://github.com/ccch1mneyyy/dsh-TUI#quick-start) | | ZCode | Deep integration; needs a `zcode` CLI that ships the TUI (see note below) | [Z.ai](https://zcode.z.ai/en/docs) | | Continue | Auto-setup | [Continue](https://docs.continue.dev/cli/quickstart) | | Cursor CLI | Deep integration | [Cursor](https://cursor.com/cli) | diff --git a/docs/site/content/docs/mobile.mdx b/docs/site/content/docs/mobile.mdx index e8fed6790d1..7e2b5050bd6 100644 --- a/docs/site/content/docs/mobile.mdx +++ b/docs/site/content/docs/mobile.mdx @@ -125,6 +125,7 @@ For a direct LAN or Tailscale connection, allow the paired desktop's listening p - **Pairing fails** — make sure your desktop and phone are signed into the same Orca account. Pairing codes expire after a few minutes; generate a fresh one if it's been sitting on the screen. - **Authentication failed / pairing invalid** — the desktop no longer accepts this device token (for example after desktop cleared paired devices). Try **Retry** on the banner first (transient rejections can recover without re-pairing). If it keeps failing, use **Re-pair** from desktop, or **Remove** the host and pair again. - **Update Orca Mobile / Update Orca on your computer** — the phone and desktop speak a versioned mobile protocol. If either side is too old, mobile blocks that host and points you at the App Store (iOS), [GitHub Releases](https://github.com/stablyai/orca/releases) (Android APK or desktop), then back to hosts. After updating, refresh the connection; if the message stays, remove the host and pair again. +- **A chat tab says Update mobile** — the session was started in desktop Chat UI, and this phone's app is too old to show it (the tab opens to an empty pane). Update the mobile app, then reconnect to the host so it sees the new app. If the app is already up to date and the tab still says Update mobile after reconnecting, report it with your mobile app version and desktop Orca version. - **Quick Commands unavailable** — update the paired desktop so it advertises the quick-commands capability. - **Can't reach desktop** — phone and desktop must share a network path (LAN, Tailscale, or the pairing path you used). Closing the desktop app drops the connection; reopen desktop and the phone reconnects automatically. diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.task-list-linear-linear.listissues-1.json b/mobile/rpc-foundation/goldens/matrix-tasks.task-list-linear-linear.listissues-1.json index de6b3862827..4e6a101e19e 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.task-list-linear-linear.listissues-1.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.task-list-linear-linear.listissues-1.json @@ -158,11 +158,6 @@ "ordinal": 13, "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"linear.searchIssues\",\"params\":{\"query\":\"bug\",\"limit\":50,\"workspaceId\":\"linear-workspace\"}}" }, - "1a5f65e0078d": { - "name": "loading", - "ordinal": 15, - "value": false - }, "1f4eeb3dcff1": { "name": "items", "ordinal": 5, @@ -452,46 +447,6 @@ "loading": false, "refreshing": false }, - "a27078adc061": { - "name": "items", - "ordinal": 13, - "value": [ - { - "key": "linear:linear-workspace:issue-2", - "provider": "linear", - "source": { - "description": "", - "id": "issue-2", - "identifier": "ENG-2", - "labels": [], - "priority": 0, - "state": { - "color": "#000", - "name": "Todo", - "type": "unstarted" - }, - "team": { - "id": "team-1", - "key": "ENG", - "name": "Engineering" - }, - "title": "A found issue", - "updatedAt": "2020-01-01T00:00:00.000Z", - "url": "", - "workspaceId": "linear-workspace" - }, - "status": "Todo", - "subtitle": "ENG-2 · Engineering", - "title": "A found issue", - "updatedAt": "2020-01-01T00:00:00.000Z" - } - ] - }, - "ab9026005b36": { - "name": "refreshing", - "ordinal": 16, - "value": false - }, "b25e7c116f7e": { "name": "items", "ordinal": 5, @@ -532,11 +487,6 @@ "ordinal": 9, "value": true }, - "bf0de0571310": { - "name": "taskListSettled", - "ordinal": 17, - "value": true - }, "c6d55e6b8844": { "name": "linear.listIssues#1", "ordinal": 3, @@ -634,62 +584,6 @@ "ordinal": 18, "value": true }, - "dd5be60ee9f9": { - "name": "linear.searchIssues#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "linear.searchIssues" - }, - { - "name": "params", - "value": { - "limit": 50, - "query": "bug", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": [ - { - "description": "", - "id": "issue-2", - "identifier": "ENG-2", - "labels": [], - "priority": 0, - "state": { - "color": "#000", - "name": "Todo", - "type": "unstarted" - }, - "team": { - "id": "team-1", - "key": "ENG", - "name": "Engineering" - }, - "title": "A found issue", - "updatedAt": "2020-01-01T00:00:00.000Z", - "url": "", - "workspaceId": "linear-workspace" - } - ] - } - } - }, "dff6398be355": { "name": "linear.listIssues#1", "ordinal": 3, @@ -729,11 +623,6 @@ } } }, - "e3642939f5f6": { - "name": "linear.searchIssues#1", - "ordinal": 12, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"linear.searchIssues\",\"params\":{\"query\":\"bug\",\"limit\":50,\"workspaceId\":\"linear-workspace\"}}" - }, "e6b86743ee36": { "name": "linear.listIssues#1", "ordinal": 3, @@ -783,11 +672,6 @@ "$rpc": "undefined" } }, - "ef8932b03a8c": { - "name": "error", - "ordinal": 14, - "value": "" - }, "f1dcb0c02c92": { "name": "error", "ordinal": 6, @@ -880,8 +764,8 @@ { "id": "tk-list-linear.normal:load-settled", "observation": { - "sender": ["c6d55e6b8844", "dd5be60ee9f9"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "837199f7c720"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -898,11 +782,12 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "a27078adc061", - "ef8932b03a8c", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310" + "52e364aee6ba", + "3e58b6085f7d", + "29cadc65bcbb", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf" ] } }, diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.task-list-linear-linear.searchissues-1.json b/mobile/rpc-foundation/goldens/matrix-tasks.task-list-linear-linear.searchissues-1.json index 4fd93457341..2de13df6257 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.task-list-linear-linear.searchissues-1.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.task-list-linear-linear.searchissues-1.json @@ -4,9 +4,9 @@ "family": "tasks.task-list-linear", "namedDeltas": [], "values": { - "0091f1ca9ca4": { + "0920d57a5690": { "name": "linear.searchIssues#1", - "ordinal": 11, + "ordinal": 12, "args": [ { "name": "method", @@ -38,14 +38,56 @@ } } }, - "1a5f65e0078d": { + "0a23a5e47479": { "name": "loading", - "ordinal": 15, + "ordinal": 16, "value": false }, - "1b36d3ce7e9d": { + "19d7ea49485f": { "name": "linear.searchIssues#1", - "ordinal": 11, + "ordinal": 13, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"linear.searchIssues\",\"params\":{\"query\":\"bug\",\"limit\":50,\"workspaceId\":\"linear-workspace\"}}" + }, + "1fbeb5648bad": { + "name": "linear.searchIssues#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "linear.searchIssues" + }, + { + "name": "params", + "value": { + "limit": 50, + "query": "bug", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true, + "result": { + "error": "inner refused", + "ok": false + } + } + } + }, + "231f0bf4ccdb": { + "name": "linear.searchIssues#1", + "ordinal": 12, "args": [ { "name": "method", @@ -80,10 +122,46 @@ } } }, - "34d17f188229": { - "name": "refreshing", - "ordinal": 14, - "value": false + "29cadc65bcbb": { + "name": "error", + "ordinal": 15, + "value": "" + }, + "2d7c2f1c74fd": { + "name": "linear.searchIssues#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "linear.searchIssues" + }, + { + "name": "params", + "value": { + "limit": 50, + "query": "bug", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true, + "result": { + "$rpc": "null" + } + } + } }, "39f99cf479f0": { "name": "error", @@ -95,6 +173,77 @@ "ordinal": 10, "value": "" }, + "3b96c8ef95d8": { + "name": "linear.searchIssues#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "linear.searchIssues" + }, + { + "name": "params", + "value": { + "limit": 50, + "query": "bug", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true, + "result": { + "error": "refused" + } + } + } + }, + "3e58b6085f7d": { + "name": "items", + "ordinal": 14, + "value": [ + { + "key": "linear:linear-workspace:issue-2", + "provider": "linear", + "source": { + "description": "", + "id": "issue-2", + "identifier": "ENG-2", + "labels": [], + "priority": 0, + "state": { + "color": "#000", + "name": "Todo", + "type": "unstarted" + }, + "team": { + "id": "team-1", + "key": "ENG", + "name": "Engineering" + }, + "title": "A found issue", + "updatedAt": "2020-01-01T00:00:00.000Z", + "url": "", + "workspaceId": "linear-workspace" + }, + "status": "Todo", + "subtitle": "ENG-2 · Engineering", + "title": "A found issue", + "updatedAt": "2020-01-01T00:00:00.000Z" + } + ] + }, "3edde845aed1": { "error": "", "items": [ @@ -136,9 +285,14 @@ "ordinal": 8, "value": false }, - "57c41659e935": { - "name": "linear.searchIssues#1", + "52e364aee6ba": { + "name": "loading", "ordinal": 11, + "value": true + }, + "55596faa3307": { + "name": "linear.searchIssues#1", + "ordinal": 12, "args": [ { "name": "method", @@ -160,13 +314,16 @@ } ], "settlement": { - "status": "rejected", + "status": "fulfilled", "startedAt": 0, "settledAt": 0, - "error": { - "category": "Error", - "message": "", - "isRpcDeliveryUnknown": true + "value": { + "error": { + "code": "method_not_found", + "message": "Unknown method" + }, + "id": "frame-2", + "ok": false } } }, @@ -175,9 +332,113 @@ "ordinal": 7, "value": false }, - "5c90b1e0c7b8": { + "609f32a21704": { + "name": "loading", + "ordinal": 2, + "value": true + }, + "7b6df16c2cf0": { + "name": "linear.listIssues#1", + "ordinal": 4, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"linear.listIssues\",\"params\":{\"filter\":\"all\",\"limit\":50,\"workspaceId\":\"linear-workspace\"}}" + }, + "837199f7c720": { "name": "linear.searchIssues#1", - "ordinal": 11, + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "linear.searchIssues" + }, + { + "name": "params", + "value": { + "limit": 50, + "query": "bug", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true, + "result": [ + { + "description": "", + "id": "issue-2", + "identifier": "ENG-2", + "labels": [], + "priority": 0, + "state": { + "color": "#000", + "name": "Todo", + "type": "unstarted" + }, + "team": { + "id": "team-1", + "key": "ENG", + "name": "Engineering" + }, + "title": "A found issue", + "updatedAt": "2020-01-01T00:00:00.000Z", + "url": "", + "workspaceId": "linear-workspace" + } + ] + } + } + }, + "83e72fb8e8cd": { + "name": "loading", + "ordinal": 14, + "value": false + }, + "8a7f1ca9ee43": { + "name": "linear.searchIssues#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "linear.searchIssues" + }, + { + "name": "params", + "value": { + "limit": 50, + "query": "bug", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true + } + } + }, + "8ceaa7a69564": { + "name": "linear.searchIssues#1", + "ordinal": 12, "args": [ { "name": "method", @@ -214,57 +475,6 @@ } } }, - "609f32a21704": { - "name": "loading", - "ordinal": 2, - "value": true - }, - "7b6df16c2cf0": { - "name": "linear.listIssues#1", - "ordinal": 4, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"linear.listIssues\",\"params\":{\"filter\":\"all\",\"limit\":50,\"workspaceId\":\"linear-workspace\"}}" - }, - "898b9173828f": { - "name": "linear.searchIssues#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "linear.searchIssues" - }, - { - "name": "params", - "value": { - "limit": 50, - "query": "bug", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "$rpc": "null" - } - } - } - }, - "8a38ef76313b": { - "name": "loading", - "ordinal": 13, - "value": false - }, "94f44b229d7d": { "error": "", "items": [ @@ -301,97 +511,16 @@ "loading": false, "refreshing": false }, - "9c9ce3233b41": { - "name": "linear.searchIssues#1", - "ordinal": 11, - "args": [ + "99f1aeb70deb": { + "error": "", + "items": [ { - "name": "method", - "value": "linear.searchIssues" - }, - { - "name": "params", - "value": { - "limit": 50, - "query": "bug", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "method_not_found", - "message": "Unknown method" - }, - "id": "frame-2", - "ok": false - } - } - }, - "9d1b472cf8a3": { - "error": "Unable to load Linear issues. Try again.", - "items": [], - "loading": false, - "refreshing": false - }, - "9dc0b0cb9c84": { - "name": "linear.searchIssues#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "linear.searchIssues" - }, - { - "name": "params", - "value": { - "limit": 50, - "query": "bug", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "error": "inner refused", - "ok": false - } - } - } - }, - "a27078adc061": { - "name": "items", - "ordinal": 13, - "value": [ - { - "key": "linear:linear-workspace:issue-2", + "key": "linear:linear-workspace:issue-1", "provider": "linear", "source": { "description": "", - "id": "issue-2", - "identifier": "ENG-2", + "id": "issue-1", + "identifier": "ENG-1", "labels": [], "priority": 0, "state": { @@ -404,22 +533,30 @@ "key": "ENG", "name": "Engineering" }, - "title": "A found issue", + "title": "A Linear issue", "updatedAt": "2020-01-01T00:00:00.000Z", "url": "", "workspaceId": "linear-workspace" }, "status": "Todo", - "subtitle": "ENG-2 · Engineering", - "title": "A found issue", + "subtitle": "ENG-1 · Engineering", + "title": "A Linear issue", "updatedAt": "2020-01-01T00:00:00.000Z" } - ] + ], + "loading": true, + "refreshing": false }, - "ab9026005b36": { - "name": "refreshing", - "ordinal": 16, - "value": false + "9cbc524246ed": { + "name": "items", + "ordinal": 14, + "value": [] + }, + "9d1b472cf8a3": { + "error": "Unable to load Linear issues. Try again.", + "items": [], + "loading": false, + "refreshing": false }, "b25e7c116f7e": { "name": "items", @@ -456,15 +593,86 @@ } ] }, + "b8b1a5203f20": { + "name": "error", + "ordinal": 15, + "value": "Unable to load Linear issues. Try again." + }, "ba411b67de4b": { "name": "taskListSettled", "ordinal": 9, "value": true }, - "bf0de0571310": { - "name": "taskListSettled", - "ordinal": 17, - "value": true + "bbbf0dc6de33": { + "name": "linear.searchIssues#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "linear.searchIssues" + }, + { + "name": "params", + "value": { + "limit": 50, + "query": "bug", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "refused", + "message": "" + }, + "id": "frame-2", + "ok": false + } + } + }, + "bbeb1f8c8fbb": { + "name": "linear.searchIssues#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "linear.searchIssues" + }, + { + "name": "params", + "value": { + "limit": 50, + "query": "bug", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "", + "isRpcDeliveryUnknown": true + } + } }, "c6d55e6b8844": { "name": "linear.listIssues#1", @@ -524,204 +732,19 @@ } } }, - "c73faccc085d": { - "name": "items", - "ordinal": 13, - "value": [] + "cbe48ad190bf": { + "name": "taskListSettled", + "ordinal": 18, + "value": true }, - "c829775e62c9": { - "name": "linear.searchIssues#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "linear.searchIssues" - }, - { - "name": "params", - "value": { - "limit": 50, - "query": "bug", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true - } - } + "d0a895d46972": { + "name": "refreshing", + "ordinal": 15, + "value": false }, - "d7a404a3f73e": { - "name": "linear.searchIssues#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "linear.searchIssues" - }, - { - "name": "params", - "value": { - "limit": 50, - "query": "bug", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "refused", - "message": "" - }, - "id": "frame-2", - "ok": false - } - } - }, - "dd5be60ee9f9": { - "name": "linear.searchIssues#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "linear.searchIssues" - }, - { - "name": "params", - "value": { - "limit": 50, - "query": "bug", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": [ - { - "description": "", - "id": "issue-2", - "identifier": "ENG-2", - "labels": [], - "priority": 0, - "state": { - "color": "#000", - "name": "Todo", - "type": "unstarted" - }, - "team": { - "id": "team-1", - "key": "ENG", - "name": "Engineering" - }, - "title": "A found issue", - "updatedAt": "2020-01-01T00:00:00.000Z", - "url": "", - "workspaceId": "linear-workspace" - } - ] - } - } - }, - "e3642939f5f6": { + "d3467ad3533d": { "name": "linear.searchIssues#1", "ordinal": 12, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"linear.searchIssues\",\"params\":{\"query\":\"bug\",\"limit\":50,\"workspaceId\":\"linear-workspace\"}}" - }, - "e9a14a2190c0": { - "name": "error", - "ordinal": 14, - "value": "Unable to load Linear issues. Try again." - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - }, - "ef8932b03a8c": { - "name": "error", - "ordinal": 14, - "value": "" - }, - "efa96bafb315": { - "name": "linear.searchIssues#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "linear.searchIssues" - }, - { - "name": "params", - "value": { - "limit": 50, - "query": "bug", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "error": "refused" - } - } - } - }, - "f1dcb0c02c92": { - "name": "error", - "ordinal": 6, - "value": "" - }, - "f55e7fb7039e": { - "name": "linear.searchIssues#1", - "ordinal": 11, "args": [ { "name": "method", @@ -752,6 +775,24 @@ "isRpcDeliveryUnknown": true } } + }, + "e8ba61988aec": { + "name": "refreshing", + "ordinal": 17, + "value": false + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } + }, + "f1dcb0c02c92": { + "name": "error", + "ordinal": 6, + "value": "" } }, "recording": { @@ -803,15 +844,15 @@ { "id": "tk-list-linear.prelude:cleanup", "observation": { - "sender": ["c6d55e6b8844", "0091f1ca9ca4"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "0920d57a5690"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", "set-query-1": "eb79a9b3682a", "load-2": "eb79a9b3682a" }, - "state": "94f44b229d7d", + "state": "99f1aeb70deb", "effects": [ "39f99cf479f0", "609f32a21704", @@ -821,16 +862,17 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "8a38ef76313b", - "34d17f188229" + "52e364aee6ba", + "83e72fb8e8cd", + "d0a895d46972" ] } }, { "id": "tk-list-linear.normal:load-settled", "observation": { - "sender": ["c6d55e6b8844", "dd5be60ee9f9"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "837199f7c720"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -847,19 +889,20 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "a27078adc061", - "ef8932b03a8c", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310" + "52e364aee6ba", + "3e58b6085f7d", + "29cadc65bcbb", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf" ] } }, { "id": "tk-list-linear.result-absent:load-settled", "observation": { - "sender": ["c6d55e6b8844", "c829775e62c9"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "8a7f1ca9ee43"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -876,19 +919,20 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "c73faccc085d", - "e9a14a2190c0", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310" + "52e364aee6ba", + "9cbc524246ed", + "b8b1a5203f20", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf" ] } }, { "id": "tk-list-linear.result-null:load-settled", "observation": { - "sender": ["c6d55e6b8844", "898b9173828f"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "2d7c2f1c74fd"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -905,19 +949,20 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "c73faccc085d", - "e9a14a2190c0", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310" + "52e364aee6ba", + "9cbc524246ed", + "b8b1a5203f20", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf" ] } }, { "id": "tk-list-linear.inner-ok-missing:load-settled", "observation": { - "sender": ["c6d55e6b8844", "efa96bafb315"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "3b96c8ef95d8"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -934,19 +979,20 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "c73faccc085d", - "e9a14a2190c0", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310" + "52e364aee6ba", + "9cbc524246ed", + "b8b1a5203f20", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf" ] } }, { "id": "tk-list-linear.inner-false-string-error:load-settled", "observation": { - "sender": ["c6d55e6b8844", "9dc0b0cb9c84"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "1fbeb5648bad"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -963,19 +1009,20 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "c73faccc085d", - "e9a14a2190c0", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310" + "52e364aee6ba", + "9cbc524246ed", + "b8b1a5203f20", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf" ] } }, { "id": "tk-list-linear.inner-false-object-error:load-settled", "observation": { - "sender": ["c6d55e6b8844", "5c90b1e0c7b8"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "8ceaa7a69564"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -992,19 +1039,20 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "c73faccc085d", - "e9a14a2190c0", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310" + "52e364aee6ba", + "9cbc524246ed", + "b8b1a5203f20", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf" ] } }, { "id": "tk-list-linear.outer-refused:load-settled", "observation": { - "sender": ["c6d55e6b8844", "1b36d3ce7e9d"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "231f0bf4ccdb"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -1021,19 +1069,20 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "c73faccc085d", - "e9a14a2190c0", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310" + "52e364aee6ba", + "9cbc524246ed", + "b8b1a5203f20", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf" ] } }, { "id": "tk-list-linear.outer-refused-no-message:load-settled", "observation": { - "sender": ["c6d55e6b8844", "d7a404a3f73e"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "bbbf0dc6de33"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -1050,19 +1099,20 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "c73faccc085d", - "e9a14a2190c0", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310" + "52e364aee6ba", + "9cbc524246ed", + "b8b1a5203f20", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf" ] } }, { "id": "tk-list-linear.method-not-found:load-settled", "observation": { - "sender": ["c6d55e6b8844", "9c9ce3233b41"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "55596faa3307"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -1079,19 +1129,20 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "c73faccc085d", - "e9a14a2190c0", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310" + "52e364aee6ba", + "9cbc524246ed", + "b8b1a5203f20", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf" ] } }, { "id": "tk-list-linear.transport-rejection:load-settled", "observation": { - "sender": ["c6d55e6b8844", "f55e7fb7039e"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "d3467ad3533d"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -1108,19 +1159,20 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "c73faccc085d", - "e9a14a2190c0", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310" + "52e364aee6ba", + "9cbc524246ed", + "b8b1a5203f20", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf" ] } }, { "id": "tk-list-linear.transport-rejection-no-message:load-settled", "observation": { - "sender": ["c6d55e6b8844", "57c41659e935"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "bbeb1f8c8fbb"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -1137,11 +1189,12 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "c73faccc085d", - "e9a14a2190c0", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310" + "52e364aee6ba", + "9cbc524246ed", + "b8b1a5203f20", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf" ] } } diff --git a/mobile/rpc-foundation/goldens/tk-list-linear-switch-back.json b/mobile/rpc-foundation/goldens/tk-list-linear-switch-back.json index 1b71a998aaa..2355189cabe 100644 --- a/mobile/rpc-foundation/goldens/tk-list-linear-switch-back.json +++ b/mobile/rpc-foundation/goldens/tk-list-linear-switch-back.json @@ -4,11 +4,92 @@ "family": "tasks.task-list-linear", "namedDeltas": [], "values": { - "1a5f65e0078d": { + "029bb83f402f": { + "name": "error", + "ordinal": 21, + "value": "" + }, + "0a23a5e47479": { "name": "loading", - "ordinal": 15, + "ordinal": 16, "value": false }, + "0bb204f7f9f1": { + "name": "refreshing", + "ordinal": 28, + "value": false + }, + "0e04c147819c": { + "name": "linear.listIssues#2", + "ordinal": 23, + "args": [ + { + "name": "method", + "value": "linear.listIssues" + }, + { + "name": "params", + "value": { + "filter": "all", + "limit": 50, + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "19d7ea49485f": { + "name": "linear.searchIssues#1", + "ordinal": 13, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"linear.searchIssues\",\"params\":{\"query\":\"bug\",\"limit\":50,\"workspaceId\":\"linear-workspace\"}}" + }, + "1d85d05c4c17": { + "name": "linear.searchIssues#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "linear.searchIssues" + }, + { + "name": "params", + "value": { + "limit": 50, + "query": "bug", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "29cadc65bcbb": { + "name": "error", + "ordinal": 15, + "value": "" + }, + "38bcf1ed5ff9": { + "name": "taskListSettled", + "ordinal": 29, + "value": true + }, "39f99cf479f0": { "name": "error", "ordinal": 1, @@ -19,6 +100,41 @@ "ordinal": 10, "value": "" }, + "3e58b6085f7d": { + "name": "items", + "ordinal": 14, + "value": [ + { + "key": "linear:linear-workspace:issue-2", + "provider": "linear", + "source": { + "description": "", + "id": "issue-2", + "identifier": "ENG-2", + "labels": [], + "priority": 0, + "state": { + "color": "#000", + "name": "Todo", + "type": "unstarted" + }, + "team": { + "id": "team-1", + "key": "ENG", + "name": "Engineering" + }, + "title": "A found issue", + "updatedAt": "2020-01-01T00:00:00.000Z", + "url": "", + "workspaceId": "linear-workspace" + }, + "status": "Todo", + "subtitle": "ENG-2 · Engineering", + "title": "A found issue", + "updatedAt": "2020-01-01T00:00:00.000Z" + } + ] + }, "3edde845aed1": { "error": "", "items": [ @@ -60,15 +176,10 @@ "ordinal": 8, "value": false }, - "427b7993fe85": { - "name": "error", - "ordinal": 20, - "value": "" - }, - "531ad700826e": { - "name": "refreshing", - "ordinal": 27, - "value": false + "52e364aee6ba": { + "name": "loading", + "ordinal": 11, + "value": true }, "5ac1816a09df": { "name": "loading", @@ -80,19 +191,24 @@ "ordinal": 2, "value": true }, - "687501e36688": { + "657f394da6f5": { "name": "taskListSettled", - "ordinal": 28, + "ordinal": 22, "value": true }, - "7b6df16c2cf0": { - "name": "linear.listIssues#1", - "ordinal": 4, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"linear.listIssues\",\"params\":{\"filter\":\"all\",\"limit\":50,\"workspaceId\":\"linear-workspace\"}}" + "6b7ab35b43f3": { + "name": "linear.listIssues#2", + "ordinal": 24, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"linear.listIssues\",\"params\":{\"filter\":\"all\",\"limit\":50,\"workspaceId\":\"linear-workspace\"}}" }, - "8074cf69af1b": { + "6dd330aacfa2": { + "name": "error", + "ordinal": 26, + "value": "" + }, + "6ee1eb7bc043": { "name": "items", - "ordinal": 19, + "ordinal": 20, "value": [ { "key": "linear:linear-workspace:issue-1", @@ -125,9 +241,191 @@ } ] }, - "82788025d560": { + "7b6df16c2cf0": { + "name": "linear.listIssues#1", + "ordinal": 4, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"linear.listIssues\",\"params\":{\"filter\":\"all\",\"limit\":50,\"workspaceId\":\"linear-workspace\"}}" + }, + "837199f7c720": { + "name": "linear.searchIssues#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "linear.searchIssues" + }, + { + "name": "params", + "value": { + "limit": 50, + "query": "bug", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true, + "result": [ + { + "description": "", + "id": "issue-2", + "identifier": "ENG-2", + "labels": [], + "priority": 0, + "state": { + "color": "#000", + "name": "Todo", + "type": "unstarted" + }, + "team": { + "id": "team-1", + "key": "ENG", + "name": "Engineering" + }, + "title": "A found issue", + "updatedAt": "2020-01-01T00:00:00.000Z", + "url": "", + "workspaceId": "linear-workspace" + } + ] + } + } + }, + "9270aeb7d9c6": { + "status": "pending", + "startedAt": 0 + }, + "94caa29bceef": { + "name": "error", + "ordinal": 19, + "value": "" + }, + "94f44b229d7d": { + "error": "", + "items": [ + { + "key": "linear:linear-workspace:issue-1", + "provider": "linear", + "source": { + "description": "", + "id": "issue-1", + "identifier": "ENG-1", + "labels": [], + "priority": 0, + "state": { + "color": "#000", + "name": "Todo", + "type": "unstarted" + }, + "team": { + "id": "team-1", + "key": "ENG", + "name": "Engineering" + }, + "title": "A Linear issue", + "updatedAt": "2020-01-01T00:00:00.000Z", + "url": "", + "workspaceId": "linear-workspace" + }, + "status": "Todo", + "subtitle": "ENG-1 · Engineering", + "title": "A Linear issue", + "updatedAt": "2020-01-01T00:00:00.000Z" + } + ], + "loading": false, + "refreshing": false + }, + "99f1aeb70deb": { + "error": "", + "items": [ + { + "key": "linear:linear-workspace:issue-1", + "provider": "linear", + "source": { + "description": "", + "id": "issue-1", + "identifier": "ENG-1", + "labels": [], + "priority": 0, + "state": { + "color": "#000", + "name": "Todo", + "type": "unstarted" + }, + "team": { + "id": "team-1", + "key": "ENG", + "name": "Engineering" + }, + "title": "A Linear issue", + "updatedAt": "2020-01-01T00:00:00.000Z", + "url": "", + "workspaceId": "linear-workspace" + }, + "status": "Todo", + "subtitle": "ENG-1 · Engineering", + "title": "A Linear issue", + "updatedAt": "2020-01-01T00:00:00.000Z" + } + ], + "loading": true, + "refreshing": false + }, + "b25e7c116f7e": { + "name": "items", + "ordinal": 5, + "value": [ + { + "key": "linear:linear-workspace:issue-1", + "provider": "linear", + "source": { + "description": "", + "id": "issue-1", + "identifier": "ENG-1", + "labels": [], + "priority": 0, + "state": { + "color": "#000", + "name": "Todo", + "type": "unstarted" + }, + "team": { + "id": "team-1", + "key": "ENG", + "name": "Engineering" + }, + "title": "A Linear issue", + "updatedAt": "2020-01-01T00:00:00.000Z", + "url": "", + "workspaceId": "linear-workspace" + }, + "status": "Todo", + "subtitle": "ENG-1 · Engineering", + "title": "A Linear issue", + "updatedAt": "2020-01-01T00:00:00.000Z" + } + ] + }, + "ba411b67de4b": { + "name": "taskListSettled", + "ordinal": 9, + "value": true + }, + "c68fccc93876": { "name": "linear.listIssues#2", - "ordinal": 22, + "ordinal": 23, "args": [ { "name": "method", @@ -183,146 +481,6 @@ } } }, - "915569974be9": { - "name": "loading", - "ordinal": 26, - "value": false - }, - "9270aeb7d9c6": { - "status": "pending", - "startedAt": 0 - }, - "94f44b229d7d": { - "error": "", - "items": [ - { - "key": "linear:linear-workspace:issue-1", - "provider": "linear", - "source": { - "description": "", - "id": "issue-1", - "identifier": "ENG-1", - "labels": [], - "priority": 0, - "state": { - "color": "#000", - "name": "Todo", - "type": "unstarted" - }, - "team": { - "id": "team-1", - "key": "ENG", - "name": "Engineering" - }, - "title": "A Linear issue", - "updatedAt": "2020-01-01T00:00:00.000Z", - "url": "", - "workspaceId": "linear-workspace" - }, - "status": "Todo", - "subtitle": "ENG-1 · Engineering", - "title": "A Linear issue", - "updatedAt": "2020-01-01T00:00:00.000Z" - } - ], - "loading": false, - "refreshing": false - }, - "a27078adc061": { - "name": "items", - "ordinal": 13, - "value": [ - { - "key": "linear:linear-workspace:issue-2", - "provider": "linear", - "source": { - "description": "", - "id": "issue-2", - "identifier": "ENG-2", - "labels": [], - "priority": 0, - "state": { - "color": "#000", - "name": "Todo", - "type": "unstarted" - }, - "team": { - "id": "team-1", - "key": "ENG", - "name": "Engineering" - }, - "title": "A found issue", - "updatedAt": "2020-01-01T00:00:00.000Z", - "url": "", - "workspaceId": "linear-workspace" - }, - "status": "Todo", - "subtitle": "ENG-2 · Engineering", - "title": "A found issue", - "updatedAt": "2020-01-01T00:00:00.000Z" - } - ] - }, - "ab9026005b36": { - "name": "refreshing", - "ordinal": 16, - "value": false - }, - "b25e7c116f7e": { - "name": "items", - "ordinal": 5, - "value": [ - { - "key": "linear:linear-workspace:issue-1", - "provider": "linear", - "source": { - "description": "", - "id": "issue-1", - "identifier": "ENG-1", - "labels": [], - "priority": 0, - "state": { - "color": "#000", - "name": "Todo", - "type": "unstarted" - }, - "team": { - "id": "team-1", - "key": "ENG", - "name": "Engineering" - }, - "title": "A Linear issue", - "updatedAt": "2020-01-01T00:00:00.000Z", - "url": "", - "workspaceId": "linear-workspace" - }, - "status": "Todo", - "subtitle": "ENG-1 · Engineering", - "title": "A Linear issue", - "updatedAt": "2020-01-01T00:00:00.000Z" - } - ] - }, - "b84d178fd4fa": { - "name": "taskListSettled", - "ordinal": 21, - "value": true - }, - "ba411b67de4b": { - "name": "taskListSettled", - "ordinal": 9, - "value": true - }, - "bf0de0571310": { - "name": "taskListSettled", - "ordinal": 17, - "value": true - }, - "c40da88e1087": { - "name": "error", - "ordinal": 25, - "value": "" - }, "c6d55e6b8844": { "name": "linear.listIssues#1", "ordinal": 3, @@ -381,14 +539,32 @@ } } }, - "caf8f91bd626": { - "name": "error", + "cbe48ad190bf": { + "name": "taskListSettled", "ordinal": 18, + "value": true + }, + "e8ba61988aec": { + "name": "refreshing", + "ordinal": 17, + "value": false + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } + }, + "f1dcb0c02c92": { + "name": "error", + "ordinal": 6, "value": "" }, - "d2396a6354db": { + "f7948247f5de": { "name": "items", - "ordinal": 24, + "ordinal": 25, "value": [ { "key": "linear:linear-workspace:issue-1", @@ -421,145 +597,10 @@ } ] }, - "dd5be60ee9f9": { - "name": "linear.searchIssues#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "linear.searchIssues" - }, - { - "name": "params", - "value": { - "limit": 50, - "query": "bug", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": [ - { - "description": "", - "id": "issue-2", - "identifier": "ENG-2", - "labels": [], - "priority": 0, - "state": { - "color": "#000", - "name": "Todo", - "type": "unstarted" - }, - "team": { - "id": "team-1", - "key": "ENG", - "name": "Engineering" - }, - "title": "A found issue", - "updatedAt": "2020-01-01T00:00:00.000Z", - "url": "", - "workspaceId": "linear-workspace" - } - ] - } - } - }, - "e3642939f5f6": { - "name": "linear.searchIssues#1", - "ordinal": 12, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"linear.searchIssues\",\"params\":{\"query\":\"bug\",\"limit\":50,\"workspaceId\":\"linear-workspace\"}}" - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - }, - "ee67e864ea01": { - "name": "linear.listIssues#2", - "ordinal": 23, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"linear.listIssues\",\"params\":{\"filter\":\"all\",\"limit\":50,\"workspaceId\":\"linear-workspace\"}}" - }, - "ef8932b03a8c": { - "name": "error", - "ordinal": 14, - "value": "" - }, - "f1dcb0c02c92": { - "name": "error", - "ordinal": 6, - "value": "" - }, - "f310b6adb00d": { - "name": "linear.searchIssues#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "linear.searchIssues" - }, - { - "name": "params", - "value": { - "limit": 50, - "query": "bug", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "fdc3528e1a4e": { - "name": "linear.listIssues#2", - "ordinal": 22, - "args": [ - { - "name": "method", - "value": "linear.listIssues" - }, - { - "name": "params", - "value": { - "filter": "all", - "limit": 50, - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } + "fe892b7f7693": { + "name": "loading", + "ordinal": 27, + "value": false } }, "recording": { @@ -589,15 +630,15 @@ { "id": "second-filter-pending", "observation": { - "sender": ["c6d55e6b8844", "f310b6adb00d"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "1d85d05c4c17"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", "set-query-1": "eb79a9b3682a", "load-2": "9270aeb7d9c6" }, - "state": "94f44b229d7d", + "state": "99f1aeb70deb", "effects": [ "39f99cf479f0", "609f32a21704", @@ -606,15 +647,16 @@ "5ac1816a09df", "411aee2eccd9", "ba411b67de4b", - "3aefb3006914" + "3aefb3006914", + "52e364aee6ba" ] } }, { "id": "second-filter-settled", "observation": { - "sender": ["c6d55e6b8844", "dd5be60ee9f9"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "837199f7c720"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -631,19 +673,20 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "a27078adc061", - "ef8932b03a8c", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310" + "52e364aee6ba", + "3e58b6085f7d", + "29cadc65bcbb", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf" ] } }, { "id": "first-filter-back-pending", "observation": { - "sender": ["c6d55e6b8844", "dd5be60ee9f9", "fdc3528e1a4e"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6", "ee67e864ea01"], + "sender": ["c6d55e6b8844", "837199f7c720", "0e04c147819c"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f", "6b7ab35b43f3"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -662,23 +705,24 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "a27078adc061", - "ef8932b03a8c", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310", - "caf8f91bd626", - "8074cf69af1b", - "427b7993fe85", - "b84d178fd4fa" + "52e364aee6ba", + "3e58b6085f7d", + "29cadc65bcbb", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf", + "94caa29bceef", + "6ee1eb7bc043", + "029bb83f402f", + "657f394da6f5" ] } }, { "id": "first-filter-back-settled", "observation": { - "sender": ["c6d55e6b8844", "dd5be60ee9f9", "82788025d560"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6", "ee67e864ea01"], + "sender": ["c6d55e6b8844", "837199f7c720", "c68fccc93876"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f", "6b7ab35b43f3"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -697,20 +741,21 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "a27078adc061", - "ef8932b03a8c", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310", - "caf8f91bd626", - "8074cf69af1b", - "427b7993fe85", - "b84d178fd4fa", - "d2396a6354db", - "c40da88e1087", - "915569974be9", - "531ad700826e", - "687501e36688" + "52e364aee6ba", + "3e58b6085f7d", + "29cadc65bcbb", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf", + "94caa29bceef", + "6ee1eb7bc043", + "029bb83f402f", + "657f394da6f5", + "f7948247f5de", + "6dd330aacfa2", + "fe892b7f7693", + "0bb204f7f9f1", + "38bcf1ed5ff9" ] } } diff --git a/mobile/rpc-foundation/goldens/tk-list-linear.json b/mobile/rpc-foundation/goldens/tk-list-linear.json index 0cb14cb6b11..708c5585bc6 100644 --- a/mobile/rpc-foundation/goldens/tk-list-linear.json +++ b/mobile/rpc-foundation/goldens/tk-list-linear.json @@ -4,11 +4,21 @@ "family": "tasks.task-list-linear", "namedDeltas": [], "values": { - "1a5f65e0078d": { + "0a23a5e47479": { "name": "loading", - "ordinal": 15, + "ordinal": 16, "value": false }, + "19d7ea49485f": { + "name": "linear.searchIssues#1", + "ordinal": 13, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"linear.searchIssues\",\"params\":{\"query\":\"bug\",\"limit\":50,\"workspaceId\":\"linear-workspace\"}}" + }, + "29cadc65bcbb": { + "name": "error", + "ordinal": 15, + "value": "" + }, "39f99cf479f0": { "name": "error", "ordinal": 1, @@ -19,6 +29,41 @@ "ordinal": 10, "value": "" }, + "3e58b6085f7d": { + "name": "items", + "ordinal": 14, + "value": [ + { + "key": "linear:linear-workspace:issue-2", + "provider": "linear", + "source": { + "description": "", + "id": "issue-2", + "identifier": "ENG-2", + "labels": [], + "priority": 0, + "state": { + "color": "#000", + "name": "Todo", + "type": "unstarted" + }, + "team": { + "id": "team-1", + "key": "ENG", + "name": "Engineering" + }, + "title": "A found issue", + "updatedAt": "2020-01-01T00:00:00.000Z", + "url": "", + "workspaceId": "linear-workspace" + }, + "status": "Todo", + "subtitle": "ENG-2 · Engineering", + "title": "A found issue", + "updatedAt": "2020-01-01T00:00:00.000Z" + } + ] + }, "3edde845aed1": { "error": "", "items": [ @@ -60,6 +105,11 @@ "ordinal": 8, "value": false }, + "52e364aee6ba": { + "name": "loading", + "ordinal": 11, + "value": true + }, "5ac1816a09df": { "name": "loading", "ordinal": 7, @@ -75,6 +125,62 @@ "ordinal": 4, "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"linear.listIssues\",\"params\":{\"filter\":\"all\",\"limit\":50,\"workspaceId\":\"linear-workspace\"}}" }, + "837199f7c720": { + "name": "linear.searchIssues#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "linear.searchIssues" + }, + { + "name": "params", + "value": { + "limit": 50, + "query": "bug", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true, + "result": [ + { + "description": "", + "id": "issue-2", + "identifier": "ENG-2", + "labels": [], + "priority": 0, + "state": { + "color": "#000", + "name": "Todo", + "type": "unstarted" + }, + "team": { + "id": "team-1", + "key": "ENG", + "name": "Engineering" + }, + "title": "A found issue", + "updatedAt": "2020-01-01T00:00:00.000Z", + "url": "", + "workspaceId": "linear-workspace" + } + ] + } + } + }, "94f44b229d7d": { "error": "", "items": [ @@ -111,46 +217,6 @@ "loading": false, "refreshing": false }, - "a27078adc061": { - "name": "items", - "ordinal": 13, - "value": [ - { - "key": "linear:linear-workspace:issue-2", - "provider": "linear", - "source": { - "description": "", - "id": "issue-2", - "identifier": "ENG-2", - "labels": [], - "priority": 0, - "state": { - "color": "#000", - "name": "Todo", - "type": "unstarted" - }, - "team": { - "id": "team-1", - "key": "ENG", - "name": "Engineering" - }, - "title": "A found issue", - "updatedAt": "2020-01-01T00:00:00.000Z", - "url": "", - "workspaceId": "linear-workspace" - }, - "status": "Todo", - "subtitle": "ENG-2 · Engineering", - "title": "A found issue", - "updatedAt": "2020-01-01T00:00:00.000Z" - } - ] - }, - "ab9026005b36": { - "name": "refreshing", - "ordinal": 16, - "value": false - }, "b25e7c116f7e": { "name": "items", "ordinal": 5, @@ -191,11 +257,6 @@ "ordinal": 9, "value": true }, - "bf0de0571310": { - "name": "taskListSettled", - "ordinal": 17, - "value": true - }, "c6d55e6b8844": { "name": "linear.listIssues#1", "ordinal": 3, @@ -254,66 +315,15 @@ } } }, - "dd5be60ee9f9": { - "name": "linear.searchIssues#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "linear.searchIssues" - }, - { - "name": "params", - "value": { - "limit": 50, - "query": "bug", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": [ - { - "description": "", - "id": "issue-2", - "identifier": "ENG-2", - "labels": [], - "priority": 0, - "state": { - "color": "#000", - "name": "Todo", - "type": "unstarted" - }, - "team": { - "id": "team-1", - "key": "ENG", - "name": "Engineering" - }, - "title": "A found issue", - "updatedAt": "2020-01-01T00:00:00.000Z", - "url": "", - "workspaceId": "linear-workspace" - } - ] - } - } + "cbe48ad190bf": { + "name": "taskListSettled", + "ordinal": 18, + "value": true }, - "e3642939f5f6": { - "name": "linear.searchIssues#1", - "ordinal": 12, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"linear.searchIssues\",\"params\":{\"query\":\"bug\",\"limit\":50,\"workspaceId\":\"linear-workspace\"}}" + "e8ba61988aec": { + "name": "refreshing", + "ordinal": 17, + "value": false }, "eb79a9b3682a": { "status": "fulfilled", @@ -323,11 +333,6 @@ "$rpc": "undefined" } }, - "ef8932b03a8c": { - "name": "error", - "ordinal": 14, - "value": "" - }, "f1dcb0c02c92": { "name": "error", "ordinal": 6, @@ -383,8 +388,8 @@ { "id": "load-settled", "observation": { - "sender": ["c6d55e6b8844", "dd5be60ee9f9"], - "payloads": ["7b6df16c2cf0", "e3642939f5f6"], + "sender": ["c6d55e6b8844", "837199f7c720"], + "payloads": ["7b6df16c2cf0", "19d7ea49485f"], "settlements": { "mount": "eb79a9b3682a", "load-0": "eb79a9b3682a", @@ -401,11 +406,12 @@ "411aee2eccd9", "ba411b67de4b", "3aefb3006914", - "a27078adc061", - "ef8932b03a8c", - "1a5f65e0078d", - "ab9026005b36", - "bf0de0571310" + "52e364aee6ba", + "3e58b6085f7d", + "29cadc65bcbb", + "0a23a5e47479", + "e8ba61988aec", + "cbe48ad190bf" ] } } diff --git a/mobile/src/diagnostics/connection-diagnostics-screen-data.test.ts b/mobile/src/diagnostics/connection-diagnostics-screen-data.test.ts deleted file mode 100644 index fa859474b28..00000000000 --- a/mobile/src/diagnostics/connection-diagnostics-screen-data.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { resolveDiagnosticsHostId } from './connection-diagnostics-screen-data' - -import type { HostProfile } from '../host-catalog/host-profile' - -const host = (id: string): HostProfile => ({ - id, - name: id, - endpoint: 'ws://192.168.1.2:6768', - deviceToken: 'token', - publicKeyB64: 'key', - lastConnected: 0 -}) - -describe('connection diagnostics screen data', () => { - it('applies route changes synchronously without discarding a chip choice for the same route', () => { - const hosts = [host('a'), host('b')] - expect(resolveDiagnosticsHostId(hosts, undefined, null)).toBe('a') - expect(resolveDiagnosticsHostId(hosts, 'b', { hostId: 'a', requestedHostId: 'a' })).toBe('b') - expect(resolveDiagnosticsHostId(hosts, 'b', { hostId: 'a', requestedHostId: 'b' })).toBe('a') - }) - - it('does not revive a stale manual choice when routing away and back', () => { - const hosts = [host('a'), host('b'), host('c')] - const firstRouteA = {} - const routeC = {} - const secondRouteA = {} - const manualSelection = { hostId: 'b', requestedHostId: 'a', routeKey: firstRouteA } - - expect(resolveDiagnosticsHostId(hosts, 'c', manualSelection, routeC)).toBe('c') - expect(resolveDiagnosticsHostId(hosts, 'a', manualSelection, secondRouteA)).toBe('a') - }) -}) diff --git a/mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts b/mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts deleted file mode 100644 index d2438307f36..00000000000 --- a/mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - installChatViewHooks, - bannerText, - pressSend, - render, - update -} from './MobileNativeChatView.harness.test-fixture' - -vi.mock('react-native', async () => { - const { reactNativeStub } = await import('./MobileNativeChatView.render-stubs.test-fixture') - return reactNativeStub() -}) -vi.mock('react-native-safe-area-context', () => ({ - useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }) -})) -vi.mock('react-native-gesture-handler', async () => { - const { gestureHandlerStub } = await import('./MobileNativeChatView.render-stubs.test-fixture') - return gestureHandlerStub() -}) -vi.mock('lucide-react-native', () => ({ - ArrowDown: 'ArrowDown', - ChevronsDownUp: 'ChevronsDownUp', - ChevronsUpDown: 'ChevronsUpDown', - Square: 'Square' -})) -vi.mock('./transcript/MobileNativeChatMessage', () => ({ - MobileNativeChatMessage: 'ChatMessage' -})) -vi.mock('./transcript/MobileNativeChatLiveLine', () => ({ - MobileNativeChatLiveLine: 'LiveStatus' -})) -vi.mock('./input/MobileNativeChatAsk', () => ({ MobileNativeChatAsk: 'ChatAsk' })) -vi.mock('./input/MobileNativeChatPermission', () => ({ - MobileNativeChatPermission: 'ChatPermission' -})) -vi.mock('./input/MobileNativeChatQuestion', () => ({ - MobileNativeChatQuestion: 'ChatQuestion' -})) -vi.mock('../../components/ActionSheetModal', () => ({ ActionSheetModal: 'ActionSheetModal' })) -vi.mock('./composer/MobileNativeChatComposer', async () => { - const { composerStub } = await import('./MobileNativeChatView.render-stubs.test-fixture') - return composerStub() -}) - -describe('MobileNativeChatView: send and read failure banners', () => { - installChatViewHooks() - - it('retires the previous banner before sending and preserves the new delivery notice', async () => { - const onClearSendError = vi.fn() - await render({ - sendErrorMessage: 'Stop failed', - onClearSendError, - onSend: async () => { - expect(onClearSendError).toHaveBeenCalledOnce() - await update({ sendErrorMessage: 'Delivery unconfirmed' }) - return true - } - }) - - await pressSend() - - expect(onClearSendError).toHaveBeenCalledOnce() - expect(bannerText()).toBe('Delivery unconfirmed') - }) -}) - -vi.mock('./input/MobileQueuedMessageComposer', () => ({ - MobileQueuedMessageComposer: 'QueuedMessageComposer' -})) diff --git a/mobile/src/session/native-chat/MobileNativeChatView.harness.test-fixture.ts b/mobile/src/session/native-chat/MobileNativeChatView.harness.test-fixture.ts deleted file mode 100644 index bca5383d4c2..00000000000 --- a/mobile/src/session/native-chat/MobileNativeChatView.harness.test-fixture.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { resolveMobileNativeChatRowProps } from './transcript/use-mobile-native-chat-row-props' -import { createElement, type ReactElement } from 'react' -import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, beforeEach, expect, vi } from 'vitest' -import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' -import { MobileNativeChatView } from './MobileNativeChatView' -import { setMobileNativeChatDraftText } from './composer/mobile-native-chat-draft-store' -import { - scrollToEnd, - scrollToOffset, - pageScroller -} from './MobileNativeChatView.render-stubs.test-fixture' - -vi.mock('../../components/DragReorderList', () => ({ DragReorderList: 'DragReorderList' })) -vi.mock('react-native-reanimated', async () => { - const { useRef } = await import('react') - return { - default: { ScrollView: 'ScrollView' }, - useAnimatedRef: () => useRef(null), - useSharedValue: (value: unknown) => useRef({ value }).current - } -}) - -export type Overrides = { - messages?: Parameters[0]['messages'] - folded?: Parameters[0]['folded'] - streaming?: string | null - sendErrorMessage?: string | null - onClearSendError?: () => void - inputLockReason?: 'disconnected' | 'waiting' | null - composerText?: string - onSend?: (text: string) => Promise - pending?: Parameters[0]['pending'] - structuredActivityUi?: boolean - turnIndicator?: Parameters[0]['turnIndicator'] - agentWorking?: boolean - canStop?: boolean - ask?: Parameters[0]['ask'] - askRequiresTerminal?: boolean - collapsedPrompt?: Parameters[0]['collapsedPrompt'] - micActive?: boolean - micProcessing?: boolean - composerTray?: Parameters[0]['composerTray'] - question?: Parameters[0]['question'] - permission?: Parameters[0]['permission'] - sendSurfaceId?: string - keyboardInset?: number - hasMore?: boolean - olderPages?: Parameters[0]['olderPages'] - onLoadEarlier?: () => void - status?: Parameters[0]['status'] - error?: string - readFailedFinally?: boolean - actionablePromptIds?: readonly string[] -} - -export function assistantTurn(id: string, text: string): NativeChatMessage { - return { id, role: 'assistant', blocks: [{ type: 'text', text }], timestamp: 0, source: 'hook' } -} - -const DRAFT_KEY = 'draft-a' - -function chatViewElement({ - composerText = '', - ...overrides -}: Overrides): ReturnType { - setMobileNativeChatDraftText(DRAFT_KEY, composerText) - return createElement(MobileNativeChatView, { - messages: [], - folded: [], - status: 'ready', - streaming: null, - onSend: vi.fn().mockResolvedValue(true), - sendSurfaceId: 'tab-a', - getSendCompletionGeneration: () => 0, - getComposerEditGeneration: () => 0, - pending: [], - draftKey: DRAFT_KEY, - onComposerTextChange: vi.fn(), - ...overrides - }) -} - -let renderer: ReactTestRenderer | null = null - -export function installChatViewHooks(): void { - beforeEach(() => { - vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => - setTimeout(() => callback(0), 0) - ) - vi.stubGlobal('cancelAnimationFrame', (handle: ReturnType) => - clearTimeout(handle) - ) - }) - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - scrollToEnd.mockReset() - scrollToOffset.mockReset() - Object.assign(pageScroller, { scrollTop: 0, scrollHeight: 0, clientHeight: 500 }) - vi.unstubAllGlobals() - }) -} - -export function root(): ReactTestInstance { - return renderer!.root -} - -// Mocked react-native components are string tags that ReactTestInstance's ElementType omits. -export function hostType(node: ReactTestInstance): unknown { - return node.type -} - -export async function render(overrides: Overrides = {}): Promise { - await act(async () => { - renderer = create(chatViewElement(overrides)) - }) -} - -export async function update(overrides: Overrides = {}): Promise { - await act(async () => { - renderer?.update(chatViewElement(overrides)) - }) -} - -export function listIds(): string[] { - return (list().props.data as { id: string }[]).map((row) => row.id) -} - -export function list(): ReactTestInstance { - return renderer!.root.find((node) => hostType(node) === 'FlatList') -} - -export function renderedRow(id: string): ReactElement> { - const listNode = list() - const data = listNode.props.data as NativeChatMessage[] - const index = data.findIndex((row) => row.id === id) - const row = listNode.props.renderItem({ item: data[index], index }) - const resolved = resolveMobileNativeChatRowProps(index, data[index]!, row.props.lookups) - return createElement('Row', { ...row.props, ...resolved }) -} - -export function banners(): ReactTestInstance[] { - return renderer!.root.findAll((node) => node.props.accessibilityRole === 'alert') -} - -export function composer(): ReactTestInstance { - return renderer!.root.find((node) => hostType(node) === 'Composer') -} - -export function bannerText(): string { - const [alert, ...rest] = banners() - expect(rest).toHaveLength(0) - return alert - .findAll((node) => hostType(node) === 'Text') - .map((node) => node.props.children) - .join('') -} - -export async function pressSend(): Promise { - const composer = renderer!.root.find((node) => hostType(node) === 'Composer') - await act(async () => { - await composer.props.onPress() - }) -} - -export function scrollEvent(y: number, contentHeight: number) { - return { - nativeEvent: { - contentOffset: { y }, - contentSize: { height: contentHeight }, - layoutMeasurement: { height: 500 } - } - } -} - -export async function scrollAwayFromTail(): Promise { - await act(async () => { - list().props.onScrollBeginDrag?.({}) - list().props.onScroll({ - nativeEvent: { - contentOffset: { y: 200 }, - contentSize: { height: 1_200 }, - layoutMeasurement: { height: 500 } - } - }) - }) -} diff --git a/mobile/src/session/native-chat/MobileNativeChatView.render-stubs.test-fixture.ts b/mobile/src/session/native-chat/MobileNativeChatView.render-stubs.test-fixture.ts deleted file mode 100644 index dffd0c09033..00000000000 --- a/mobile/src/session/native-chat/MobileNativeChatView.render-stubs.test-fixture.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { vi } from 'vitest' - -const scrollToEnd = vi.hoisted(() => vi.fn()) -const scrollToOffset = vi.hoisted(() => vi.fn()) -const platform = vi.hoisted(() => ({ OS: 'ios' })) -const pageScroller = vi.hoisted(() => ({ - scrollTop: 0, - scrollHeight: 0, - clientHeight: 500, - getInnerViewNode: () => ({}), - getBoundingClientRect: () => ({ top: 0, bottom: 500 }), - getAttribute: () => null, - querySelectorAll: () => [], - querySelector: () => null, - addEventListener: () => {}, - removeEventListener: () => {} -})) - -export async function reactNativeStub() { - const React = await import('react') - const { reactNativeMotionStub } = await import('../../test-support/react-native-motion-stub') - return { - ...reactNativeMotionStub(), - ActivityIndicator: 'ActivityIndicator', - FlatList: React.forwardRef((props, ref) => { - const handle = { scrollToEnd, scrollToOffset, getScrollableNode: () => pageScroller } - React.useImperativeHandle(ref, () => handle, []) - return React.createElement('FlatList', props) - }), - Platform: platform, - Pressable: 'Pressable', - ScrollView: React.forwardRef((props, ref) => { - const handle = { - scrollTo: ({ y, animated }: { y: number; animated: boolean }) => - scrollToOffset({ animated, offset: y }), - scrollToEnd, - getScrollableNode: () => pageScroller, - getInnerViewNode: () => pageScroller.getInnerViewNode() - } - React.useImperativeHandle(ref, () => handle, []) - return React.createElement('ScrollView', props) - }), - StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, - Text: 'Text', - View: 'View' - } -} - -export function gestureHandlerStub() { - const chain = { - runOnJS: () => chain, - onStart: () => chain, - onUpdate: () => chain - } - return { - Gesture: { Simultaneous: () => ({}), Native: () => ({}), Pinch: () => chain }, - GestureDetector: 'GestureDetector', - GestureHandlerRootView: 'GestureHandlerRootView' - } -} - -export async function composerStub() { - const React = await import('react') - const { MobileNativeChatStopButton } = await import('./input/MobileNativeChatStopButton') - const { useMobileNativeChatDraft } = await import('./composer/mobile-native-chat-draft-store') - return { - MobileNativeChatDraftComposer: ({ - draftKey, - ...props - }: { - draftKey: string | null - onSend: (text: string) => Promise - disabled?: boolean - placeholder?: string - stop?: { onStop?: () => void; held: boolean } | null - }) => - React.createElement( - 'Composer', - { - ...props, - value: useMobileNativeChatDraft(draftKey), - accessibilityLabel: 'Send message', - onPress: () => props.onSend('hi') - }, - props.stop ? React.createElement(MobileNativeChatStopButton, props.stop) : null - ) - } -} - -export { scrollToEnd, scrollToOffset, platform, pageScroller } diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-queued-hold.test.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-queued-hold.test.ts deleted file mode 100644 index 1bea79e1632..00000000000 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-drafts-queued-hold.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { useMobileNativeChatDrafts } from './use-mobile-native-chat-drafts' -import { - closeMobileNativeChatTabDraft, - useMobileNativeChatDraft -} from './mobile-native-chat-draft-store' - -import { loadMobileNativeChatDrafts } from './mobile-native-chat-draft-persistence' - -vi.mock('@react-native-async-storage/async-storage', async () => { - const { createInMemoryAsyncStorage } = - await import('../../../test-support/in-memory-async-storage') - return { default: createInMemoryAsyncStorage() } -}) - -describe('useMobileNativeChatDrafts with queued cards', () => { - let renderer: ReactTestRenderer | null = null - let state: (ReturnType & { composerText: string }) | null = null - - afterEach(async () => { - act(() => renderer?.unmount()) - await loadMobileNativeChatDrafts('host', 'worktree') - closeMobileNativeChatTabDraft('host\0worktree\0a') - await loadMobileNativeChatDrafts('host', 'worktree') - renderer = null - state = null - }) - - function Harness(): null { - const drafts = useMobileNativeChatDrafts({ - hostId: 'host', - worktreeId: 'worktree', - tabId: 'a', - sessionId: 'session-a', - messages: [], - launchDraft: null, - transcriptLoading: false, - transcriptSettled: true - }) - state = { ...drafts, composerText: useMobileNativeChatDraft(drafts.draftKey) } - return null - } - - async function render(): Promise { - await act(async () => { - renderer = create(createElement(Harness)) - }) - } - - it("reports whether a queued card's Edit copy landed, so Edit never deletes text it did not keep", async () => { - await render() - let copied: boolean | undefined - act(() => { - copied = state?.appendComposerText('') - }) - expect(copied).toBe(false) - act(() => { - copied = state?.appendComposerText('edited text') - }) - expect(copied).toBe(true) - expect(state?.composerText).toBe('edited text') - }) -}) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatPermission.tsx b/mobile/src/session/native-chat/input/MobileNativeChatPermission.tsx index f8fffdcc0bd..148d08c1f8b 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatPermission.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatPermission.tsx @@ -19,15 +19,19 @@ function MobileNativeChatPermissionImpl({ permission, onRespond, onCancel, - onCollapse + onCollapse, + onAnswerInTerminal }: { permission: MobileChatPermission onRespond: (send: string) => Promise + /** Shown when the card has no options: only the terminal can answer it. */ + onAnswerInTerminal?: () => void onCancel?: (prompt?: NonNullable) => Promise // Collapse writes nothing to the agent. onCollapse?: () => void }): React.JSX.Element { useMobileColorScheme() + const t = useMobileTranslation() const [submitting, setSubmitting] = useState(false) const submittingRef = useRef(false) // Unknown newer-host subjects allow only cancellation; preserve their detail for the reader. @@ -66,7 +70,7 @@ function MobileNativeChatPermissionImpl({ {permission.options.map((option, index) => { - const isPrimary = index === 0 + const isPrimary = index === 0 && !permission.neutralOptions return ( ) })} + {permission.options.length === 0 && onAnswerInTerminal ? ( + [ + styles.option, + styles.optionPrimary, + pressed && styles.optionPressed + ]} + hitSlop={6} + onPress={onAnswerInTerminal} + > + + {t('chat.promptCard.answerInTerminal', 'Answer in terminal')} + + + ) : null} ) @@ -239,6 +259,8 @@ const styles = themedStyleSheet(() => ({ }, option: { minHeight: 44, + // A long menu label wraps inside its button instead of running off the card. + maxWidth: '100%', justifyContent: 'center', paddingHorizontal: spacing.md, paddingVertical: spacing.sm, diff --git a/mobile/src/session/native-chat/input/MobileNativeChatPromptCard.tsx b/mobile/src/session/native-chat/input/MobileNativeChatPromptCard.tsx index 5c1b9a47bc2..8c45ee91c9d 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatPromptCard.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatPromptCard.tsx @@ -123,11 +123,13 @@ export function MobileNativeChatPromptCard({ /> ) : permission ? ( (await onRespondPermission?.(send)) ?? false} onCancel={onCancelPrompt} onCollapse={onCollapsePrompt} + onAnswerInTerminal={onAnswerInTerminal} /> ) : question?.questions ? ( ({ + ...(holdsComposer ? { holdsComposer } : {}), + title: 'Trust this folder?', + options: [{ label: 'Trust folder', send: '\r' }] +}) + +describe('useMobileNativeChatPromptPresentation', () => { + let renderer = { unmount: () => {}, update: (_element: ReturnType) => {} } + let state: ReturnType | null = null + + beforeEach(() => mobileNativeChatPromptDismissals.clearForTests()) + afterEach(() => { + act(() => renderer.unmount()) + }) + + function Harness({ shown }: { shown: MobileChatPermission | null }): null { + state = useMobileNativeChatPromptPresentation({ + permission: shown, + waitStartedAt: 1, + scopeKey: 'tab-1', + sessionKey: 'session-1', + observing: true, + respondPermission: async () => true + }) + return null + } + + async function answer(shown: MobileChatPermission): Promise { + await act(async () => { + renderer = create(createElement(Harness, { shown })) + }) + await act(async () => { + await state?.respondPermission('\r') + }) + } + + it('hides an ordinary approval once its answer was accepted', async () => { + await answer(permission()) + expect(state?.permission).toBeNull() + }) + + // Why: the folder-trust dialog is still on screen until the host settles it. + it('keeps a composer-holding card until its host status leaves', async () => { + const shown = permission(true) + await answer(shown) + expect(state?.permission).toBe(shown) + await act(async () => renderer.update(createElement(Harness, { shown: null }))) + expect(state?.permission).toBeNull() + }) +}) diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-prompt-presentation.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-prompt-presentation.ts index 9da6c56f08b..42ba4322b44 100644 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-prompt-presentation.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-prompt-presentation.ts @@ -41,12 +41,13 @@ export function useMobileNativeChatPromptPresentation({ const respond = useCallback( async (send: string): Promise => { const accepted = await respondPermission(send) - if (accepted) { + // A folder-trust dialog stays up until the host settles it; the card keeps the composer locked meanwhile. + if (accepted && !permission?.holdsComposer) { dismissPrompt() } return accepted }, - [respondPermission, dismissPrompt] + [respondPermission, dismissPrompt, permission?.holdsComposer] ) return { occurrenceKey: promptKey === null ? null : JSON.stringify([scopeKey, sessionKey, promptKey]), diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-ownership.test.tsx b/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-ownership.test.tsx deleted file mode 100644 index f2796e90993..00000000000 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-scroll-ownership.test.tsx +++ /dev/null @@ -1,14 +0,0 @@ -// @vitest-environment happy-dom -import { expect, it } from 'vitest' -import { MobileNativeChatScrollRoots } from './mobile-native-chat-scroll-roots' - -it("forgets a closed tool line's nested command and output positions, not its neighbours'", () => { - const at = { top: 30, followsEnd: false } - const memory = new Map( - ['run:o', 'run:o/line:a:command', 'run:o/line:a:output', 'line:a:command'] - .concat(['run:o/line:ab:command', 'diff:src/line:a.ts']) - .map((address) => [address, at] as const) - ) - new MobileNativeChatScrollRoots(memory, 10).forget('line:a') - expect([...memory.keys()]).toEqual(['run:o', 'run:o/line:ab:command', 'diff:src/line:a.ts']) -}) diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-stream-frame.test.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-stream-frame.test.ts deleted file mode 100644 index 4059ee91773..00000000000 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-stream-frame.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - createNativeChatMerger, - replaceList -} from '../../../../../src/shared/native-chat/native-chat-merge' -import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' -import { applyMobileNativeChatStreamFrame } from './mobile-native-chat-stream-frame' - -function message(id: string): NativeChatMessage { - return { - id, - role: 'assistant', - blocks: [{ type: 'text', text: id }], - timestamp: 0, - source: 'transcript' - } -} - -describe('applyMobileNativeChatStreamFrame', () => { - it('replaces a partially overlapping replay that no longer extends the retained tail', () => { - const merger = createNativeChatMerger() - replaceList(merger, ['old-1', 'shared', 'old-tail'].map(message)) - - // Keep hasMore true so only the contiguity check can reject the interleaved row. - const replay = [message('shared'), message('compacted-summary'), message('old-tail')] - expect( - applyMobileNativeChatStreamFrame({ - merger, - frame: { type: 'snapshot', messages: replay, hasMore: true, beforeOffset: 9 }, - limit: 100, - replaceSnapshot: false - }) - ).toEqual({ - kind: 'messages', - messages: replay, - hasMore: true, - beforeOffset: 9, - windowReplaced: true - }) - }) -}) diff --git a/mobile/src/source-control/review/mobile-diff-review-rows.test.ts b/mobile/src/source-control/review/mobile-diff-review-rows.test.ts deleted file mode 100644 index e0acbecf7cc..00000000000 --- a/mobile/src/source-control/review/mobile-diff-review-rows.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { MobileDiffLine } from './mobile-diff-lines' -import { foldEnclosingLine } from './mobile-diff-review-rows' - -const context = (text: string): MobileDiffLine => ({ kind: 'context', text }) - -describe('foldEnclosingLine', () => { - it('names the nearest line above the fold that is indented less than the line after it', () => { - const lines: MobileDiffLine[] = [ - context("describe('queue', () => {"), - context(" it('orders files', () => {"), - context(' const queue = build()'), - context(''), - context(' expect(queue).toHaveLength(3)'), - { kind: 'delete', text: ' removed()' }, - context(' expect(queue[0].scope).toBe(1)') - ] - expect(foldEnclosingLine(lines, 6)).toBe("it('orders files', () => {") - }) - - it('skips blank lines after the fold and returns null when nothing encloses it', () => { - const lines = [ - context('const a = 1'), - context('const b = 2'), - context(''), - context('const c = 3') - ] - expect(foldEnclosingLine(lines, 2)).toBeNull() - expect(foldEnclosingLine(lines, 4)).toBeNull() - }) -}) diff --git a/mobile/src/tasks/task-query-storage.test.tsx b/mobile/src/tasks/task-query-storage.test.tsx index 38096465db4..0f31ba9f876 100644 --- a/mobile/src/tasks/task-query-storage.test.tsx +++ b/mobile/src/tasks/task-query-storage.test.tsx @@ -145,6 +145,77 @@ describe('Tasks lists kept on the phone', () => { expect(setError).not.toHaveBeenCalled() }) + it('shows the spinner for a new search instead of the previous search rows', async () => { + const issue: TaskItem = { + key: 'github:repo-1:21204', + provider: 'github', + title: '[Feature]: Expose browser tabs', + subtitle: 'orca #21204', + status: 'open', + updatedAt: '2026-11-10T06:51:00.000Z', + source: { + id: 'issue-21204', + type: 'issue', + number: 21204, + title: '[Feature]: Expose browser tabs', + state: 'open', + url: 'https://github.com/stablyai/orca/issues/21204', + labels: [], + updatedAt: '2026-11-10T06:51:00.000Z', + author: 'octocat', + repoId: 'repo-1', + repoName: 'orca' + } + } + const openIssues = { provider: 'github', kind: 'issues', query: 'is:issue is:open', repos: '' } + const bugSearch = { ...openIssues, query: 'is:issue is:open [Bug]' } + const setLoading = vi.fn() + const cache: { current?: ReturnType } = {} + function Probe() { + cache.current = useTaskListCache({ + hostId: HOST, + items: [issue], + jiraConnection: { + connected: false, + sites: [], + selection: null, + credentialError: null, + unavailableReason: null + }, + provider: 'github', + taskUiReady: true, + setItems: vi.fn(), + setError: vi.fn(), + setGithubPages: vi.fn(), + setGithubCurrentPage: vi.fn(), + setGithubRepoSources: vi.fn(), + setGithubSourceErrors: vi.fn(), + setGithubSourceFallbacks: vi.fn(), + setGithubCountedTotalPages: vi.fn(), + setLoading, + setTaskListSettled: vi.fn() + }) + return null + } + await act(async () => { + create( + createElement(QueryClientProvider, { client: new QueryClient() }, createElement(Probe)) + ) + await vi.runAllTimersAsync() + }) + act(() => cache.current!.shown('github', openIssues)) + + act(() => cache.current!.begin(bugSearch, 'github')) + expect(setLoading).toHaveBeenCalledWith(true) + expect(cache.current!.revalidating).toBe(false) + + act(() => cache.current!.shown('github', bugSearch)) + setLoading.mockClear() + act(() => cache.current!.begin(bugSearch, 'github')) + expect(setLoading).not.toHaveBeenCalled() + expect(cache.current!.revalidating).toBe(true) + }) + it('keeps agent launch commands and hook trust out of the stored hydration', async () => { const store = memoryStore(HOST) await storeFromEarlierLaunch(store, [ diff --git a/mobile/src/tasks/use-mobile-tasks-task-pagination-actions.tsx b/mobile/src/tasks/use-mobile-tasks-task-pagination-actions.tsx index 8137af41721..ddff2421e39 100644 --- a/mobile/src/tasks/use-mobile-tasks-task-pagination-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-task-pagination-actions.tsx @@ -48,6 +48,7 @@ export function useMobileTasksTaskPaginationActions(model: TaskListLoadingModel) loadGenerationRef, loadLinearContext, loadTasks, + loading, revalidating, selectedHostedRepos, setError, @@ -150,9 +151,10 @@ export function useMobileTasksTaskPaginationActions(model: TaskListLoadingModel) !githubCountedTotalPages && (provenPageLimit === null || githubPages.length < provenPageLimit) && hasRepoWithFullPage(githubPages.at(-1) ?? [], githubPerRepoLimit) - // Kept or previous-filter pages stand in while the list re-reads; paging from them would mix filters. + // Pages kept or left from another filter stand in while a list loads; paging from them would mix old and new rows. const githubCanShowPagination = !revalidating && + !loading && (githubTotalPages > 1 || (githubPages.length > 0 && githubCanLoadUncountedNextPage)) const githubPagePickerPages = useMemo(() => { const visible = new Set() @@ -181,6 +183,7 @@ export function useMobileTasksTaskPaginationActions(model: TaskListLoadingModel) targetPage < 0 || githubPaginationLoading || revalidating || + loading || selectedHostedRepos.length === 0 ) { return @@ -267,6 +270,7 @@ export function useMobileTasksTaskPaginationActions(model: TaskListLoadingModel) githubPages, githubPaginationLoading, loadGenerationRef, + loading, revalidating, selectedHostedRepos, setGithubCountedTotalPages, diff --git a/mobile/src/tasks/use-task-list-cache.ts b/mobile/src/tasks/use-task-list-cache.ts index 18a8dd3b3a9..e8dbbd65116 100644 --- a/mobile/src/tasks/use-task-list-cache.ts +++ b/mobile/src/tasks/use-task-list-cache.ts @@ -1,4 +1,4 @@ -import { skipToken, useQuery, useQueryClient } from '@tanstack/react-query' +import { hashKey, skipToken, useQuery, useQueryClient } from '@tanstack/react-query' import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' import { type HostQueryKey, type HostQueryParams, hostScopeKey } from '../query/host-query-key' import { persistedHostQueryKey, restoreStoredHostQueries } from '../query/host-query-persistence' @@ -44,6 +44,8 @@ export function useTaskListCache(view: TaskListView) { const [rowsReadAt, setRowsReadAt] = useState(null) // The provider whose rows are on screen, so a provider switch never keeps another provider's rows. const shownProviderRef = useRef(null) + // The list the rows on screen were read for; only a re-read of that same list may stand on them. + const shownListRef = useRef(null) const shownRowsRef = useRef(view.items) useLayoutEffect(() => { shownRowsRef.current = view.items @@ -60,6 +62,7 @@ export function useTaskListCache(view: TaskListView) { const paintRows = useCallback( (key: HostQueryKey, kept: TaskListSnapshot, provider: string, underRead: boolean): void => { shownProviderRef.current = provider + shownListRef.current = hashKey(key) setRowsReadAt(queryClient.getQueryState(key)?.dataUpdatedAt || null) view.setItems(kept.items) if (underRead) { @@ -132,8 +135,8 @@ export function useTaskListCache(view: TaskListView) { ) }, [hostId, queryClient]) - // A read of a list starts on that filter's kept rows, else on the same provider's rows still shown, else the - // spinner; it is also the list this provider opens on next launch. + // A read of a list starts on that filter's kept rows, else on its own rows still shown, else the spinner, so a new + // search never starts on another filter's rows; it is also the list this provider opens on next launch. const begin = useCallback( (params: HostQueryParams | null, provider: string): void => { cancelRead() @@ -147,7 +150,11 @@ export function useTaskListCache(view: TaskListView) { paintRows(key, kept, provider, true) return } - if (shownRowsRef.current.length > 0 && shownProviderRef.current === provider) { + if ( + shownRowsRef.current.length > 0 && + shownProviderRef.current === provider && + (!key || shownListRef.current === hashKey(key)) + ) { setRevalidating(true) } else { view.setLoading(true) @@ -166,7 +173,9 @@ export function useTaskListCache(view: TaskListView) { (provider: string, params: HostQueryParams): void => { awaitingStoredRef.current = null shownProviderRef.current = provider - setRowsReadAt(queryClient.getQueryState(taskListKey(hostId, params))?.dataUpdatedAt || null) + const key = taskListKey(hostId, params) + shownListRef.current = hashKey(key) + setRowsReadAt(queryClient.getQueryState(key)?.dataUpdatedAt || null) }, [hostId, queryClient] ) diff --git a/mobile/src/terminal/session/terminal-stream-layout.test.ts b/mobile/src/terminal/session/terminal-stream-layout.test.ts new file mode 100644 index 00000000000..552473c1291 --- /dev/null +++ b/mobile/src/terminal/session/terminal-stream-layout.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest' +import { acceptTerminalLayoutSeq } from './terminal-stream-layout' + +describe('acceptTerminalLayoutSeq', () => { + it('accepts a display-mode resize whose layout seq is below the scrollback output seq', () => { + const marks = new Map() + expect(acceptTerminalLayoutSeq(marks, 't', { type: 'subscribed', seq: 2 })).toBe(true) + expect(acceptTerminalLayoutSeq(marks, 't', { type: 'scrollback', seq: 14 })).toBe(true) + expect(acceptTerminalLayoutSeq(marks, 't', { type: 'resized', seq: 3 })).toBe(true) + }) + + it('drops a resize older than the layout seq the stream subscribed at', () => { + const marks = new Map() + acceptTerminalLayoutSeq(marks, 't', { type: 'subscribed', seq: 5 }) + expect(acceptTerminalLayoutSeq(marks, 't', { type: 'resized', seq: 4 })).toBe(false) + }) +}) diff --git a/mobile/src/terminal/session/terminal-stream-layout.ts b/mobile/src/terminal/session/terminal-stream-layout.ts index f808af671d9..6a8c2be4c69 100644 --- a/mobile/src/terminal/session/terminal-stream-layout.ts +++ b/mobile/src/terminal/session/terminal-stream-layout.ts @@ -1,7 +1,8 @@ import type { Dispatch, SetStateAction } from 'react' import type { MobileDisplayMode } from './mobile-terminal-model' -/** Records a stream event's layout seq; false for a superseded `resized`. Fresh scrollback resets the mark or reconnect can blank the terminal. */ +/** Records a stream event's layout seq; false for a superseded `resized`. Each `subscribed` resets the mark; + * scrollback leaves it, because binary scrollback `seq` counts output bytes, not layout changes. */ export function acceptTerminalLayoutSeq( marks: Map, handle: string, @@ -23,8 +24,10 @@ export function acceptTerminalLayoutSeq( return false } marks.set(handle, eventSeq) - } else if (eventSeq != null && data.type === 'scrollback') { + } else if (data.type === 'subscribed' && eventSeq != null) { marks.set(handle, eventSeq) + } else if (data.type === 'subscribed') { + marks.delete(handle) } return true } diff --git a/mobile/src/terminal/session/use-mobile-session-terminal-subscription.ts b/mobile/src/terminal/session/use-mobile-session-terminal-subscription.ts index 07d3b3088a4..e164f9adb0b 100644 --- a/mobile/src/terminal/session/use-mobile-session-terminal-subscription.ts +++ b/mobile/src/terminal/session/use-mobile-session-terminal-subscription.ts @@ -166,6 +166,7 @@ export function useMobileSessionTerminalSubscription( return } if (data.type === 'subscribed') { + acceptTerminalLayoutSeq(layoutSeqRef.current, handle, data) outputAck.start(data) if (resume.subscribed(data)) { initializedHandlesRef.current.add(handle) diff --git a/mobile/src/test-support/rpc-recording/adapters/task-list-mount-adapters.ts b/mobile/src/test-support/rpc-recording/adapters/task-list-mount-adapters.ts index d828e708197..ad8750958c7 100644 --- a/mobile/src/test-support/rpc-recording/adapters/task-list-mount-adapters.ts +++ b/mobile/src/test-support/rpc-recording/adapters/task-list-mount-adapters.ts @@ -191,6 +191,7 @@ export function taskListMountAdapters( loadGenerationRef: { current: 0 }, loadLinearContext: async () => {}, loadTasks: async () => {}, + loading: false, revalidating: false, selectedHostedRepos: [HOSTED_REPO], taskUiReady: true, diff --git a/mobile/src/transport/connection/host-status-gates.test.ts b/mobile/src/transport/connection/host-status-gates.test.ts deleted file mode 100644 index ca1182cafaf..00000000000 --- a/mobile/src/transport/connection/host-status-gates.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { createElement } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { RpcClient } from '../rpc/rpc-client-contract' -import { useHostStatusGates, type HostStatusGates } from './host-status-gates' - -const recordHostAppVersionMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined)) - -vi.mock('../../host-descriptors/host-app-version-store', () => ({ - recordHostAppVersion: (...args: unknown[]) => recordHostAppVersionMock(...args) -})) - -const recordDescriptorFromStatusMock = vi.hoisted(() => vi.fn()) - -vi.mock('../../host-descriptors/host-descriptor-recorder', () => ({ - recordHostDescriptorFromStatus: (...args: unknown[]) => recordDescriptorFromStatusMock(...args) -})) - -describe('useHostStatusGates', () => { - beforeEach(() => { - recordDescriptorFromStatusMock.mockClear() - }) - - it('fails closed when the same host reconnects on a replaced client', async () => { - const firstClient = { - sendRequest: vi.fn().mockResolvedValue({ - ok: true, - result: { capabilities: ['browser.screencast.v1'], floatingWorkspaceEnabled: true } - }) - } as unknown as RpcClient - const secondClient = { - sendRequest: vi.fn().mockReturnValue(new Promise(() => {})) - } as unknown as RpcClient - let gates: HostStatusGates | undefined - let renderer: ReactTestRenderer | undefined - - function Probe({ client }: { client: RpcClient }): null { - gates = useHostStatusGates({ hostId: 'host-1', client, connState: 'connected' }) - return null - } - - try { - await act(async () => { - renderer = create(createElement(Probe, { client: firstClient })) - await Promise.resolve() - }) - expect(gates?.hostCapabilities).toEqual(['browser.screencast.v1']) - - await act(async () => { - renderer?.update(createElement(Probe, { client: secondClient })) - }) - expect(gates).toMatchObject({ hostCapabilities: [], statusPending: true }) - } finally { - renderer?.unmount() - } - }) -}) diff --git a/mobile/src/transport/web-bundle/mobile-web-bundle-range-interop.test.ts b/mobile/src/transport/web-bundle/mobile-web-bundle-range-interop.test.ts deleted file mode 100644 index 618e50467fa..00000000000 --- a/mobile/src/transport/web-bundle/mobile-web-bundle-range-interop.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { createHash } from 'node:crypto' -import { gunzipSync } from 'fflate' -import { describe, expect, it } from 'vitest' -import { encodeMobileWebBundleRange } from '../../../../src/main/runtime/rpc/methods/mobile-delivery/mobile-web-bundle-range-encoding' -import { MOBILE_WEB_BUNDLE_RANGE_BYTES } from '../../../../src/shared/mobile-web-bundle/bundle-rpc-contract' - -/** Script-like and a full range long, so the host's level-6 deflate emits dynamic Huffman blocks. */ -function scriptRange(): Buffer { - const words = ['const ', 'function ', 'return ', 'export ', '=> ', '{', '}', ';\n', 'orca'] - let text = '' - for (let index = 0; text.length < MOBILE_WEB_BUNDLE_RANGE_BYTES; index += 1) { - text += words[(index * 7) % words.length] + String(index % 1000) - } - return Buffer.from(text.slice(0, MOBILE_WEB_BUNDLE_RANGE_BYTES)) -} - -describe('a host-encoded range decoded by the phone', () => { - it('inflates node gzip output with fflate to the same bytes', async () => { - const raw = scriptRange() - const encoded = await encodeMobileWebBundleRange(raw) - - expect(encoded.encoding).toBe('gzip') - const inflated = gunzipSync(new Uint8Array(encoded.bytes), { - out: new Uint8Array(raw.byteLength + 1) - }) - expect(Buffer.from(inflated).equals(raw)).toBe(true) - }) - - it('leaves incompressible bytes as identity, which needs no decoder', async () => { - const raw = Buffer.concat( - Array.from({ length: 128 }, (_, index) => - createHash('sha256').update(`range-${index}`).digest() - ) - ) - const encoded = await encodeMobileWebBundleRange(raw) - - expect(encoded.encoding).toBe('identity') - expect(encoded.bytes.equals(raw)).toBe(true) - }) -}) diff --git a/src/cli/handlers/orchestration/mutation-request-show-handler.ts b/src/cli/handlers/orchestration/mutation-request-show-handler.ts index 7418565620e..5438fc70500 100644 --- a/src/cli/handlers/orchestration/mutation-request-show-handler.ts +++ b/src/cli/handlers/orchestration/mutation-request-show-handler.ts @@ -1,14 +1,18 @@ import type { CommandHandler } from '../../dispatch' import { printOrchestrationReceipt } from './agent-view' -import { getRequiredStringFlag } from '../../flags' +import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags' import { RuntimeClientError } from '../../runtime-client' import type { OrchestrationMutationRequestShowResult } from '../../../shared/orchestration/orchestration-mutation-request' export const ORCHESTRATION_REQUEST_SHOW_HANDLER: Record = { 'orchestration request-show': async ({ flags, client, json }) => { const request = getRequiredStringFlag(flags, 'request') + const on = getOptionalStringFlag(flags, 'on') const result = await client - .call('orchestration.requestShow', { request }) + .call('orchestration.requestShow', { + request, + ...(on ? { on } : {}) + }) .catch((error: unknown) => { if (error instanceof RuntimeClientError && error.code === 'method_not_found') { throw new RuntimeClientError( diff --git a/src/cli/handlers/orchestration/worker-agent-views.test.ts b/src/cli/handlers/orchestration/worker-agent-views.test.ts new file mode 100644 index 00000000000..56ebbe06ad1 --- /dev/null +++ b/src/cli/handlers/orchestration/worker-agent-views.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from 'vitest' +import { WORKER_LIST_VIEW, WORKER_SHOW_VIEW } from './worker-agent-views' + +describe('worker views of a worker a paired server runs', () => { + it('labels a remote worker’s show with its server, record time, last report and note', () => { + expect( + WORKER_SHOW_VIEW.fields({ + dispatch: { id: 'ctx_w1', taskId: 'task_1', runId: 'run_1', status: 'dispatched' }, + worker: { + dispatchId: 'ctx_w1', + state: 'ready', + stage: 'server_record', + agentTerminalHandle: null + }, + projection: null, + observation: { reason: 'devB could not be reached, so this is this Orca’s record.' }, + server: { name: 'devB', asOf: '2026-11-09T08:30:00Z', reachable: false }, + lastReport: 'Halfway: tests written.' + }) + ).toMatchObject({ + dispatchId: 'ctx_w1', + state: 'ready', + stage: 'server_record', + server: 'devB', + asOf: '2026-11-09T08:30:00Z', + lastReport: 'Halfway: tests written.', + note: 'devB could not be reached, so this is this Orca’s record.', + waitingOnHuman: 'unknown' + }) + }) + + it('names a listed remote worker’s server, and says when its pairing was re-made', () => { + const row = { + taskId: 'task_1', + runId: 'run_1', + workerState: 'ready', + dispatchStatus: 'dispatched', + agentTerminalHandle: null, + terminalState: null + } + const fields = WORKER_LIST_VIEW.fields({ + workers: [ + { ...row, dispatchId: 'ctx_w1', server: { name: 'devB', asOf: '2026-11-09T08:30:00Z' } }, + { + ...row, + dispatchId: 'ctx_w2', + server: { name: 'devB', asOf: '2026-11-09T08:45:00Z', repaired: true } + } + ], + counts: {}, + scope: { source: 'all' } + }) + expect(fields.workers).toEqual([ + expect.objectContaining({ dispatchId: 'ctx_w1', host: 'devB', asOf: '2026-11-09T08:30:00Z' }), + expect.objectContaining({ dispatchId: 'ctx_w2', host: 'devB (pairing re-made)' }) + ]) + }) +}) diff --git a/src/cli/handlers/orchestration/worker-agent-views.ts b/src/cli/handlers/orchestration/worker-agent-views.ts index ca993bc66c1..f7a171bc131 100644 --- a/src/cli/handlers/orchestration/worker-agent-views.ts +++ b/src/cli/handlers/orchestration/worker-agent-views.ts @@ -39,10 +39,18 @@ export type WorkerShowResult = { releaseState?: string | null terminalHandle?: string | null } | null - observation?: { agentWait?: { source: string; reason?: string } | null } + observation?: { agentWait?: { source: string; reason?: string } | null; reason?: string } + /** Present only for a worker a paired server runs, which this Orca's record answers. */ + server?: RemoteWorkerServer & { reachable?: boolean } + lastReport?: string | null autoReleaseAt?: string | null + /** The paired Orca whose Run here coordinates this worker. */ + coordinatedFrom?: string | null } +/** A worker a paired server runs, as this Orca names that server and last heard from it. */ +type RemoteWorkerServer = { name: string; asOf: string; repaired?: true } + type WorkerShowFields = { dispatchId: string taskId?: string @@ -56,10 +64,15 @@ type WorkerShowFields = { terminal?: string terminalState?: string workspace?: string + server?: string + asOf?: string + lastReport?: string + note?: string attention?: string[] waitingOnHuman?: string lastError?: string autoReleaseAt?: string + coordinatedFrom?: string next?: string } @@ -84,6 +97,10 @@ export const WORKER_SHOW_VIEW: OrchestrationAgentView page?: { hasMore: boolean; nextCursor: string | null; total: number } @@ -135,6 +155,7 @@ type WorkerListRow = { workspace?: string host?: string coordinatedFrom?: string + asOf?: string attention?: string[] autoReleaseAt?: string next?: string @@ -169,8 +190,9 @@ export const WORKER_LIST_VIEW: OrchestrationAgentView { - it('sends a chat read there like a shell, with no session id', () => { - const evidence = new OrchestrationRequestEvidence(CHAT) - expect( - evidence.envelopeFor('orchestration.inbox', { - remote: true, - mutation: false, - requestId: undefined - }).orchestrationCompatibilityEvidence - ).toBeUndefined() - }) - - it('keeps the session id on writes there, so that server still refuses them', () => { - const evidence = new OrchestrationRequestEvidence(CHAT) - expect( - evidence.envelopeFor('orchestration.taskCreate', { - remote: true, - mutation: true, - requestId: 'request_1' - }).orchestrationCompatibilityEvidence - ).toEqual({ agentSessionId: '11111111-1111-4111-8111-111111111111' }) - }) -}) - -describe('caller evidence on browser commands', () => { - it('names the chat on this host, so its run can show the page it drove', () => { - const evidence = new OrchestrationRequestEvidence(CHAT) - const request = { mutation: false, requestId: undefined } - expect( - evidence.envelopeFor('browser.click', { ...request, remote: false }) - .orchestrationCompatibilityEvidence - ).toEqual({ agentSessionId: '11111111-1111-4111-8111-111111111111' }) - expect( - evidence.envelopeFor('browser.click', { ...request, remote: true }) - .orchestrationCompatibilityEvidence - ).toBeUndefined() - }) -}) diff --git a/src/cli/specs/orchestration-worker-specs.ts b/src/cli/specs/orchestration-worker-specs.ts index c6426789fd7..94b759bb37f 100644 --- a/src/cli/specs/orchestration-worker-specs.ts +++ b/src/cli/specs/orchestration-worker-specs.ts @@ -145,14 +145,23 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ path: ['orchestration', 'worker-list'], summary: 'List supervised worker terminal resource accounting', usage: - 'orca orchestration worker-list [--run ] [--terminal-state ] [--include-remote] [--cursor ] [--limit <1-100>] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'run', 'terminal-state', 'include-remote', 'cursor', 'limit'], + 'orca orchestration worker-list [--run ] [--terminal-state ] [--include-remote] [--on ] [--cursor ] [--limit <1-100>] [--json]', + allowedFlags: [ + ...GLOBAL_FLAGS, + 'run', + 'terminal-state', + 'include-remote', + 'on', + 'cursor', + 'limit' + ], notes: [ 'Terminal state is process accounting and is reported separately from Task status; a completed Task can still own a live terminal.', 'A reclaimable worker with resource.autoReleaseAt is released automatically at that time unless it is reused with worker-start --terminal or kept open (worker-keep-open, worker-start --keep-open, or the user).', 'Context-only Dispatches created by orchestration dispatch are included as unsupervised with terminal state retained.', 'Returns at most 100 local rows, newest first, by default; --include-remote adds connected-server observations when the host supports fleet listing. Continue with the opaque nextCursor value unchanged.', - 'Without --run the list is scoped to the Run bound to the calling terminal, and to every Run when there is no binding; the receipt reports which in scope.source (flag, bound, or all).' + 'Without --run the list is scoped to the Run bound to the calling terminal, and to every Run when there is no binding; the receipt reports which in scope.source (flag, bound, or all).', + "--on lists that paired server's own workers for your Run there (or all of them without a Run), paged with its own cursor." ] } ] diff --git a/src/cli/specs/orchestration.ts b/src/cli/specs/orchestration.ts index 44f8f118418..bbb9e89c261 100644 --- a/src/cli/specs/orchestration.ts +++ b/src/cli/specs/orchestration.ts @@ -209,12 +209,13 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ { path: ['orchestration', 'request-show'], summary: 'Ask whether one orchestration mutation request already took effect', - usage: 'orca orchestration request-show --request [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'request'], + usage: 'orca orchestration request-show --request [--on ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'request', 'on'], notes: [ 'Read-only: it never starts, retries, or settles anything, so it is safe to run after any lost response.', 'completed means the mutation landed and --retry-request replays the recorded outcome instead of starting a second one. pending means the original mutation is still running or Orca restarted before recording its outcome; wait for a live original command, otherwise replay with --retry-request.', - 'absent means this runtime holds no receipt for that request under your caller identity: it never arrived, it failed before recording anything, or the receipt was pruned. Absent is not proof that nothing happened.' + 'absent means this runtime holds no receipt for that request under your caller identity: it never arrived, it failed before recording anything, or the receipt was pruned. Absent is not proof that nothing happened.', + 'A command about a worker on a paired server keeps its receipt on that server; --on asks there.' ] }, { diff --git a/src/main/agent-hooks/server/testing/providers/codex/server-ingest-codex-async-question.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-ingest-codex-async-question.test.ts index fef89b48fd9..9c12c88f705 100644 --- a/src/main/agent-hooks/server/testing/providers/codex/server-ingest-codex-async-question.test.ts +++ b/src/main/agent-hooks/server/testing/providers/codex/server-ingest-codex-async-question.test.ts @@ -1,7 +1,4 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { normalizeHookPayload } from '../../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' -import { createHookListenerState } from '../../../../../../shared/agent-hook-listener/listener-state' -import { buildRelayHookEnvelope } from '../../../../../../wsl-guest/agent-hook-envelope-build' import { AgentHookServer, _internals } from '../../../agent-hook-server' import { PANE, buildBody, postHookEvent } from '../../server.test-fixtures' @@ -29,18 +26,6 @@ const ACCEPTED = { hook_event_name: 'PostToolUse', tool_response: '{"accepted":true}' } -const reply = (index: number) => ({ - hook_event_name: 'UserPromptSubmit', - turn_id: 'turn-1', - prompt: `\n${JSON.stringify([ - { - answer: 'SQLite', - question: QUESTIONS.questions[index]!.title, - questionItemId: JSON.stringify(['request_user_input_async', 'call_3_1', index]) - } - ])}\n` -}) - beforeEach(() => { _internals.resetCachesForTests() }) @@ -49,27 +34,6 @@ afterEach(() => { vi.restoreAllMocks() }) -// The execution host normalizes each hook, then main ingests the relayed row, as for SSH and WSL. -function codexPane() { - const host = createHookListenerState() - const server = new AgentHookServer() - return { - report(payload: Record) { - const event = normalizeHookPayload( - host, - 'codex', - buildBody(payload, { worktreeId: 'folder-workspace' }), - 'production' - ) - if (!event) { - throw new Error('Expected a Codex hook event') - } - server.ingestRemote(buildRelayHookEnvelope(event, 'codex'), 'wsl:Ubuntu') - return { host: event.payload, main: server.getStatusSnapshotForPane(PANE)[0] } - } - } -} - const waitingOnQuestion = { state: 'waiting', toolName: 'request_user_input_async', @@ -77,33 +41,6 @@ const waitingOnQuestion = { } describe('Codex async questions', () => { - it('waits on an open question through the turn until every question is answered', () => { - const pane = codexPane() - pane.report({ hook_event_name: 'UserPromptSubmit', turn_id: 'turn-1', prompt: 'Set up a db' }) - - expect(pane.report(ASK).main).toMatchObject(waitingOnQuestion) - // Codex accepts the call at once and keeps working; the question is still open. - const accepted = pane.report(ACCEPTED) - expect(accepted.host).toMatchObject(waitingOnQuestion) - expect(accepted.main).toMatchObject(waitingOnQuestion) - pane.report({ hook_event_name: 'PreToolUse', turn_id: 'turn-1', tool_name: 'Bash' }) - // An approval on screen wins over the open question. - const approval = pane.report({ - hook_event_name: 'PermissionRequest', - turn_id: 'turn-1', - tool_name: 'Bash', - tool_input: { command: 'pnpm tc' } - }).main - expect(approval?.state).toBe('waiting') - expect(approval?.interactivePrompt).toContain('"approval"') - pane.report({ hook_event_name: 'PostToolUse', turn_id: 'turn-1', tool_name: 'Bash' }) - expect(pane.report(reply(0)).main).toMatchObject(waitingOnQuestion) - - const answered = pane.report(reply(1)).main - expect(answered).toMatchObject({ state: 'working' }) - expect(answered?.interactivePrompt).toBeUndefined() - }) - it('drops one question per skip keystroke on a local pane, since Codex reports no skip', async () => { const server = new AgentHookServer() await server.start({ env: 'production' }) diff --git a/src/main/agent-launch/trust/agent-workspace-trust-spawn.test.ts b/src/main/agent-launch/trust/agent-workspace-trust-spawn.test.ts deleted file mode 100644 index 14cc1d4fec8..00000000000 --- a/src/main/agent-launch/trust/agent-workspace-trust-spawn.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AgentWorkspaceTrustDecision } from '../../../shared/agent-launch/permissions/agent-workspace-trust-decision' -import type { AgentTrustSpawnFields } from './agent-workspace-trust' -import { applyAgentWorkspaceTrustToSpawn } from './agent-workspace-trust-spawn' - -// An SSH launch only forwards the request to the relay, so no local config is written. -async function sshTrustRequest(input: { - worktreeId: string - globalEnabled?: boolean - repoDecision?: AgentWorkspaceTrustDecision -}): Promise { - const spawnOptions: AgentTrustSpawnFields = {} - await applyAgentWorkspaceTrustToSpawn({ - launchAgent: 'claude', - worktreeId: input.worktreeId, - cwd: '/srv/app', - store: { - getFolderWorkspace: () => ({ folderPath: '/srv/folder' }), - getRepo: (repoId) => - repoId === 'repo-1' && input.repoDecision - ? { agentWorkspaceTrust: input.repoDecision } - : undefined - }, - isFreshLaunch: true, - settings: { agentWorkspaceTrustEnabled: input.globalEnabled ?? true }, - env: {}, - claudeAuth: null, - wslDistro: null, - connectionId: 'ssh-1', - spawnOptions - }) - return spawnOptions -} - -describe('agent folder trust follows the repo decision', () => { - it('pre-trusts a repo whose decision is pre-trust', async () => { - expect( - await sshTrustRequest({ worktreeId: 'repo-1::/srv/app', repoDecision: 'pre-trust' }) - ).toEqual({ agentWorkspaceTrust: { workspacePath: '/srv/app' } }) - }) - - it('leaves the folder untrusted when the repo lets agents ask', async () => { - expect( - await sshTrustRequest({ worktreeId: 'repo-1::/srv/app', repoDecision: 'agent-asks' }) - ).toEqual({}) - }) - - it('never pre-trusts when folder trust is off globally', async () => { - expect( - await sshTrustRequest({ - worktreeId: 'repo-1::/srv/app', - globalEnabled: false, - repoDecision: 'pre-trust' - }) - ).toEqual({}) - }) -}) diff --git a/src/main/ai-vault-search/session-search-degraded-roots.ts b/src/main/ai-vault-search/discovery/session-search-degraded-roots.ts similarity index 95% rename from src/main/ai-vault-search/session-search-degraded-roots.ts rename to src/main/ai-vault-search/discovery/session-search-degraded-roots.ts index ccd690354ee..be252e3d34a 100644 --- a/src/main/ai-vault-search/session-search-degraded-roots.ts +++ b/src/main/ai-vault-search/discovery/session-search-degraded-roots.ts @@ -1,4 +1,4 @@ -import type { AiVaultScanIssue } from '../../shared/ai-vault/contracts/ai-vault-types' +import type { AiVaultScanIssue } from '../../../shared/ai-vault/contracts/ai-vault-types' import type { SessionSearchDirectoryReader } from './session-search-directory-listings' export type SessionSearchDegradedRoot = { root: string; reason: string } diff --git a/src/main/ai-vault-search/session-search-deleted-sources.test.ts b/src/main/ai-vault-search/discovery/session-search-deleted-sources.test.ts similarity index 90% rename from src/main/ai-vault-search/session-search-deleted-sources.test.ts rename to src/main/ai-vault-search/discovery/session-search-deleted-sources.test.ts index 7296d1caee2..300663c89c9 100644 --- a/src/main/ai-vault-search/session-search-deleted-sources.test.ts +++ b/src/main/ai-vault-search/discovery/session-search-deleted-sources.test.ts @@ -1,8 +1,8 @@ -import './session-search-worker.test-fixture' +import '../worker/session-search-worker.test-fixture' import { mkdir, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { afterEach, beforeEach, expect, it } from 'vitest' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' +import { resetTranscriptConsumersForTests } from '../../ai-vault/transcripts/session-transcript-consumers' import { retireDeletedSessionSearchSources } from './session-search-deleted-sources' import { SessionSearchDirectoryListings, @@ -11,8 +11,8 @@ import { import { openSessionSearchIndexerHarness, type SessionSearchIndexerHarness -} from './session-search-indexer-test-fixture' -import { SessionSearchStore } from './session-search-store' +} from '../indexing/session-search-indexer-test-fixture' +import { SessionSearchStore } from '../storage/session-search-store' let harness: SessionSearchIndexerHarness let store: SessionSearchStore diff --git a/src/main/ai-vault-search/session-search-deleted-sources.ts b/src/main/ai-vault-search/discovery/session-search-deleted-sources.ts similarity index 98% rename from src/main/ai-vault-search/session-search-deleted-sources.ts rename to src/main/ai-vault-search/discovery/session-search-deleted-sources.ts index c62916c6bf6..0aed54d2aa4 100644 --- a/src/main/ai-vault-search/session-search-deleted-sources.ts +++ b/src/main/ai-vault-search/discovery/session-search-deleted-sources.ts @@ -3,7 +3,7 @@ import type { SessionSearchDegradedRoot } from './session-search-degraded-roots' import type { SessionSearchDirectoryReader } from './session-search-directory-listings' import { isUnderScanRoot } from './session-search-scan-roots' import { splitSyntheticSessionSource } from './session-search-synthetic-sources' -import type { SessionSearchIndexStore } from './session-search-store' +import type { SessionSearchIndexStore } from '../storage/session-search-store-types' // Walk missing directories upward to seek a listing that proves which component disappeared. const MISSING_DIRECTORY = new Set(['ENOENT', 'ENOTDIR']) diff --git a/src/main/ai-vault-search/session-search-directory-listings.test.ts b/src/main/ai-vault-search/discovery/session-search-directory-listings.test.ts similarity index 91% rename from src/main/ai-vault-search/session-search-directory-listings.test.ts rename to src/main/ai-vault-search/discovery/session-search-directory-listings.test.ts index be96c8f2f1e..5125d63d2a0 100644 --- a/src/main/ai-vault-search/session-search-directory-listings.test.ts +++ b/src/main/ai-vault-search/discovery/session-search-directory-listings.test.ts @@ -3,7 +3,7 @@ import { SessionSearchDirectoryListings } from './session-search-directory-listi const { readdir } = vi.hoisted(() => ({ readdir: vi.fn() })) -vi.mock('../native-chat/wsl-transcript-fs-access', () => ({ +vi.mock('../../native-chat/wsl-transcript-fs-access', () => ({ wslGatedReaddir: readdir })) diff --git a/src/main/ai-vault-search/session-search-directory-listings.ts b/src/main/ai-vault-search/discovery/session-search-directory-listings.ts similarity index 95% rename from src/main/ai-vault-search/session-search-directory-listings.ts rename to src/main/ai-vault-search/discovery/session-search-directory-listings.ts index 13f2f68d8c2..cac48a04441 100644 --- a/src/main/ai-vault-search/session-search-directory-listings.ts +++ b/src/main/ai-vault-search/discovery/session-search-directory-listings.ts @@ -1,4 +1,4 @@ -import { wslGatedReaddir } from '../native-chat/wsl-transcript-fs-access' +import { wslGatedReaddir } from '../../native-chat/wsl-transcript-fs-access' export type SessionSearchDirectoryListing = | { listed: true; names: ReadonlySet } diff --git a/src/main/ai-vault-search/session-search-scan-roots.test.ts b/src/main/ai-vault-search/discovery/session-search-scan-roots.test.ts similarity index 95% rename from src/main/ai-vault-search/session-search-scan-roots.test.ts rename to src/main/ai-vault-search/discovery/session-search-scan-roots.test.ts index 936a0012533..488d6df1470 100644 --- a/src/main/ai-vault-search/session-search-scan-roots.test.ts +++ b/src/main/ai-vault-search/discovery/session-search-scan-roots.test.ts @@ -1,6 +1,6 @@ import { expect, it } from 'vitest' import { delimiter, join } from 'node:path' -import type { SessionFileDiscovery } from '../ai-vault/session-scanner-types' +import type { SessionFileDiscovery } from '../../ai-vault/session-scanner-types' import { sameSessionSearchRoots, sessionSearchRootListings } from './session-search-scan-roots' const STATE = '/tmp/ss-roots/openclaw-state' diff --git a/src/main/ai-vault-search/session-search-scan-roots.ts b/src/main/ai-vault-search/discovery/session-search-scan-roots.ts similarity index 90% rename from src/main/ai-vault-search/session-search-scan-roots.ts rename to src/main/ai-vault-search/discovery/session-search-scan-roots.ts index 41856865e33..77d3761ad64 100644 --- a/src/main/ai-vault-search/session-search-scan-roots.ts +++ b/src/main/ai-vault-search/discovery/session-search-scan-roots.ts @@ -1,13 +1,13 @@ -import type { AiVaultScanIssue } from '../../shared/ai-vault/contracts/ai-vault-types' -import { AI_VAULT_AGENT_SOURCES } from '../ai-vault/session-scanner-agent-sources' -import { normalizedWslHomeDirs } from '../ai-vault/session-scanner-roots' -import { sessionCandidatesFromDiscoveries } from '../ai-vault/session-scanner-candidates' -import { discoverAiVaultSessionSources } from '../ai-vault/session-scanner-source-discovery' +import type { AiVaultScanIssue } from '../../../shared/ai-vault/contracts/ai-vault-types' +import { AI_VAULT_AGENT_SOURCES } from '../../ai-vault/session-scanner-agent-sources' +import { normalizedWslHomeDirs } from '../../ai-vault/session-scanner-roots' +import { sessionCandidatesFromDiscoveries } from '../../ai-vault/session-scanner-candidates' +import { discoverAiVaultSessionSources } from '../../ai-vault/session-scanner-source-discovery' import type { AiVaultScanOptions, SessionFileCandidate, SessionFileDiscovery -} from '../ai-vault/session-scanner-types' +} from '../../ai-vault/session-scanner-types' export type SessionSearchRootListing = { root: string; files: number } diff --git a/src/main/ai-vault-search/session-search-synthetic-sources.ts b/src/main/ai-vault-search/discovery/session-search-synthetic-sources.ts similarity index 82% rename from src/main/ai-vault-search/session-search-synthetic-sources.ts rename to src/main/ai-vault-search/discovery/session-search-synthetic-sources.ts index cd3ae5b5b8e..78a39a9e505 100644 --- a/src/main/ai-vault-search/session-search-synthetic-sources.ts +++ b/src/main/ai-vault-search/discovery/session-search-synthetic-sources.ts @@ -1,6 +1,6 @@ -import type { AiVaultScanIssue } from '../../shared/ai-vault/contracts/ai-vault-types' -import { splitOpenCodeSqliteCandidate } from '../../shared/opencode-sqlite-session-path' -import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' +import type { AiVaultScanIssue } from '../../../shared/ai-vault/contracts/ai-vault-types' +import { splitOpenCodeSqliteCandidate } from '../../../shared/opencode-sqlite-session-path' +import type { SessionFileCandidate } from '../../ai-vault/session-scanner-types' /** A session inside a shared container rather than a standalone transcript file. */ export type SessionSearchSyntheticSource = { container: string; id: string } diff --git a/src/main/ai-vault-search/session-search-clock.ts b/src/main/ai-vault-search/indexing/session-search-clock.ts similarity index 100% rename from src/main/ai-vault-search/session-search-clock.ts rename to src/main/ai-vault-search/indexing/session-search-clock.ts diff --git a/src/main/ai-vault-search/indexing/session-search-dependent-transcripts.test.ts b/src/main/ai-vault-search/indexing/session-search-dependent-transcripts.test.ts new file mode 100644 index 00000000000..83015e82964 --- /dev/null +++ b/src/main/ai-vault-search/indexing/session-search-dependent-transcripts.test.ts @@ -0,0 +1,96 @@ +import { mkdir, writeFile } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { parseAgentSessionFileCached } from '../../ai-vault/parse-cache/session-scanner-parse-cache' +import { resetSessionParseCacheForTests } from '../../ai-vault/parse-cache/session-parse-cache-store' +import { resetCodexSessionIndexTitleCacheForTests } from '../../ai-vault/scanners/codex/session-scanner-codex-title-index' +import type { SessionFileCandidate } from '../../ai-vault/session-scanner-types' +import { resetTranscriptConsumersForTests } from '../../ai-vault/transcripts/session-transcript-consumers' +import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' +import { + openSessionSearchIndexFile, + type SessionSearchIndexFile +} from '../storage/session-search-index-test-fixture' +import { SessionSearchStore } from '../storage/session-search-store' +import { + CODEX_ROLLOUT_FILE, + CODEX_SESSION_ID, + codexRolloutLines, + sessionCandidate +} from './session-search-transcript-fixtures' + +let index: SessionSearchIndexFile +let store: SessionSearchStore +let root: string +let errors: unknown[] + +beforeEach(async () => { + resetTranscriptConsumersForTests() + resetCodexSessionIndexTitleCacheForTests() + index = await openSessionSearchIndexFile('ss-dependent-transcripts') + root = dirname(index.path) + errors = [] + store = new SessionSearchStore(index.path, (error) => errors.push(error)) + registerSessionSearchIndexConsumer(store) +}) + +afterEach(async () => { + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + resetCodexSessionIndexTitleCacheForTests() + store.close() + await index.close() +}) + +async function writeSource(path: string, content: string): Promise { + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, content) +} + +async function coldRead(candidate: SessionFileCandidate) { + resetSessionParseCacheForTests() + const session = await parseAgentSessionFileCached(candidate, process.platform) + expect(errors).toEqual([]) + expect(session).not.toBeNull() + return session +} + +function matches(term: string): unknown { + return index.db + .prepare( + `SELECT count(*) AS n FROM messages_fts + JOIN messages m ON m.id = messages_fts.rowid + JOIN sessions s ON s.id = m.session_row_id + WHERE messages_fts MATCH ?` + ) + .get(term) +} + +it('updates the indexed Codex title when only session_index.jsonl changes', async () => { + const home = join(root, 'codex') + const path = join(home, 'sessions', CODEX_ROLLOUT_FILE) + await writeSource(path, `${codexRolloutLines(['pwd'], '/repo/app', 'codexmessage').join('\n')}\n`) + const titleIndex = join(home, 'session_index.jsonl') + await writeSource( + titleIndex, + `${JSON.stringify({ id: CODEX_SESSION_ID, thread_name: 'Original' })}\n` + ) + const candidate = await sessionCandidate('codex', path, home) + candidate.file.sidecar = 'none' + await coldRead(candidate) + expect(index.db.prepare('SELECT title FROM sessions').get()).toEqual({ title: 'Original' }) + + await writeSource( + titleIndex, + `${JSON.stringify({ id: CODEX_SESSION_ID, thread_name: 'Renamed conversation' })}\n` + ) + expect((await sessionCandidate('codex', path, home)).file).toEqual({ + ...candidate.file, + sidecar: undefined + }) + expect(await coldRead(candidate)).toMatchObject({ title: 'Renamed conversation' }) + expect(index.db.prepare('SELECT title FROM sessions').get()).toEqual({ + title: 'Renamed conversation' + }) + expect(matches('codexmessage')).toEqual({ n: 1 }) +}) diff --git a/src/main/ai-vault-search/session-search-index-consumer.ts b/src/main/ai-vault-search/indexing/session-search-index-consumer.ts similarity index 89% rename from src/main/ai-vault-search/session-search-index-consumer.ts rename to src/main/ai-vault-search/indexing/session-search-index-consumer.ts index 7e2001fc429..827e1e7709c 100644 --- a/src/main/ai-vault-search/session-search-index-consumer.ts +++ b/src/main/ai-vault-search/indexing/session-search-index-consumer.ts @@ -1,7 +1,7 @@ -import { inSessionParseFileLane } from '../ai-vault/parse-cache/session-parse-file-lane' -import { requestWholeTranscriptRead } from '../ai-vault/transcripts/session-transcript-reader' -import { traceSessionSearch } from './session-search-trace' -import type { AiVaultAgent } from '../../shared/ai-vault/contracts/ai-vault-types' +import { inSessionParseFileLane } from '../../ai-vault/parse-cache/session-parse-file-lane' +import { requestWholeTranscriptRead } from '../../ai-vault/transcripts/session-transcript-reader' +import { traceSessionSearch } from '../session-search-trace' +import type { AiVaultAgent } from '../../../shared/ai-vault/contracts/ai-vault-types' import { registerTranscriptConsumer, type TranscriptConsumer, @@ -9,11 +9,14 @@ import { type TranscriptReadConsumer, type TranscriptReadOutcome, type TranscriptReadStart -} from '../ai-vault/transcripts/session-transcript-consumers' -import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' -import { fileIdentity } from './session-search-file-cursor' -import type { SessionSearchFileWrite } from './session-search-index-writer' -import type { SessionSearchResumableCursor, SessionSearchIndexStore } from './session-search-store' +} from '../../ai-vault/transcripts/session-transcript-consumers' +import type { SessionFileCandidate } from '../../ai-vault/session-scanner-types' +import { fileIdentity } from '../storage/session-search-file-cursor' +import type { SessionSearchFileWrite } from '../storage/session-search-index-writer' +import type { + SessionSearchResumableCursor, + SessionSearchIndexStore +} from '../storage/session-search-store-types' export const SELF_CONTAINED_TRANSCRIPT_AGENTS = { claude: true, diff --git a/src/main/ai-vault-search/session-search-index-pass.ts b/src/main/ai-vault-search/indexing/session-search-index-pass.ts similarity index 85% rename from src/main/ai-vault-search/session-search-index-pass.ts rename to src/main/ai-vault-search/indexing/session-search-index-pass.ts index ac8840cb669..5614a5511b6 100644 --- a/src/main/ai-vault-search/session-search-index-pass.ts +++ b/src/main/ai-vault-search/indexing/session-search-index-pass.ts @@ -1,13 +1,16 @@ -import { throwIfAiVaultScanCancelled } from '../ai-vault/ai-vault-scan-cancellation' +import { throwIfAiVaultScanCancelled } from '../../ai-vault/ai-vault-scan-cancellation' import { createSessionParseStats, parseAgentSessionFileCached, type SessionParseStats -} from '../ai-vault/parse-cache/session-scanner-parse-cache' -import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' -import { fileIdentity } from './session-search-file-cursor' +} from '../../ai-vault/parse-cache/session-scanner-parse-cache' +import type { SessionFileCandidate } from '../../ai-vault/session-scanner-types' +import { fileIdentity } from '../storage/session-search-file-cursor' import { sessionSearchReadDecision } from './session-search-read-decision' -import type { SessionSearchFileRow, SessionSearchIndexStore } from './session-search-store' +import type { + SessionSearchFileRow, + SessionSearchIndexStore +} from '../storage/session-search-store-types' export type SessionSearchIndexPassOptions = { signal?: AbortSignal diff --git a/src/main/ai-vault-search/session-search-indexer-options.ts b/src/main/ai-vault-search/indexing/session-search-indexer-options.ts similarity index 93% rename from src/main/ai-vault-search/session-search-indexer-options.ts rename to src/main/ai-vault-search/indexing/session-search-indexer-options.ts index 41c4d6dcd6f..c9b9987d322 100644 --- a/src/main/ai-vault-search/session-search-indexer-options.ts +++ b/src/main/ai-vault-search/indexing/session-search-indexer-options.ts @@ -1,5 +1,5 @@ import type { SessionSearchClock } from './session-search-clock' -import type { SessionSearchScanRoots } from './session-search-scan-roots' +import type { SessionSearchScanRoots } from '../discovery/session-search-scan-roots' export const DEFAULT_SESSION_SEARCH_RECONCILE_INTERVAL_MS = 20_000 export const DEFAULT_SESSION_SEARCH_RECENT_PER_AGENT = 12 diff --git a/src/main/ai-vault-search/session-search-indexer-test-fixture.ts b/src/main/ai-vault-search/indexing/session-search-indexer-test-fixture.ts similarity index 93% rename from src/main/ai-vault-search/session-search-indexer-test-fixture.ts rename to src/main/ai-vault-search/indexing/session-search-indexer-test-fixture.ts index 2753651ddb7..0b1a9c5461f 100644 --- a/src/main/ai-vault-search/session-search-indexer-test-fixture.ts +++ b/src/main/ai-vault-search/indexing/session-search-indexer-test-fixture.ts @@ -1,11 +1,11 @@ -import './session-search-worker.test-fixture' +import '../worker/session-search-worker.test-fixture' import { mkdir, mkdtemp, rename, rm, stat, utimes, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' -import SyncDatabase from '../sqlite/sync-database' -import { isolatedScanRoots } from '../ai-vault/session-scanner-test-fixtures' +import SyncDatabase from '../../sqlite/sync-database' +import { isolatedScanRoots } from '../../ai-vault/session-scanner-test-fixtures' import type { SessionSearchClock, SessionSearchTimerHandle } from './session-search-clock' -import type { SessionSearchScanRoots } from './session-search-scan-roots' +import type { SessionSearchScanRoots } from '../discovery/session-search-scan-roots' import { assistantRecord, userRecord } from './session-search-transcript-fixtures' const CLOCK_EPOCH_MS = 1_740_000_000_000 diff --git a/src/main/ai-vault-search/session-search-indexer.test.ts b/src/main/ai-vault-search/indexing/session-search-indexer.test.ts similarity index 77% rename from src/main/ai-vault-search/session-search-indexer.test.ts rename to src/main/ai-vault-search/indexing/session-search-indexer.test.ts index aacbb8a6a75..5da9142ba74 100644 --- a/src/main/ai-vault-search/session-search-indexer.test.ts +++ b/src/main/ai-vault-search/indexing/session-search-indexer.test.ts @@ -1,13 +1,14 @@ -import './session-search-worker.test-fixture' -import { mkdirSync, rmSync } from 'node:fs' +import '../worker/session-search-worker.test-fixture' +import 'node:fs' import { appendFile, chmod, mkdir, rm, stat, utimes } from 'node:fs/promises' import { join } from 'node:path' import { afterEach, beforeEach, expect, it } from 'vitest' -import { resetSessionParseCacheForTests } from '../ai-vault/parse-cache/session-parse-cache-store' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' -import type SyncDatabase from '../sqlite/sync-database' +import { resetSessionParseCacheForTests } from '../../ai-vault/parse-cache/session-parse-cache-store' +import { resetTranscriptConsumersForTests } from '../../ai-vault/transcripts/session-transcript-consumers' +import type SyncDatabase from '../../sqlite/sync-database' import { SessionSearchIndexer } from './session-search-indexer' -import { removeSessionSearchDatabase } from './session-search-schema' +import '../storage/session-search-schema' +import { removeVersionedCacheDatabase } from '../../sqlite/versioned-cache-database' import { parseTranscript } from './session-search-transcript-fixtures' import { claudeLines, @@ -263,41 +264,6 @@ it('moves the retention window with the clock instead of freezing it at construc expect(sessionsMatching('ages')).toEqual([]) }) -it.skipIf(!CAN_DENY_READ)('stops re-reading a transcript it cannot read', async () => { - const path = transcriptPath() - await writeClaudeTranscript(path, ['a session behind the wrong mode bits'], SESSION_ID) - await chmod(path, 0o000) - try { - await newIndexer().start() - for (let cycle = 0; cycle < 4; cycle++) { - await nextCycle() - } - - expect(indexer?.status()).toMatchObject({ filesDue: 0, filesFailed: 1, phase: 'degraded' }) - expect(rowFor(path)?.failCount).toBeGreaterThanOrEqual(3) - - // A changed stat releases the failed-read hold; chmod alone does not change the freshness key. - await chmod(path, 0o644) - const later = new Date(Date.now() + 60_000) - await utimes(path, later, later) - await nextCycle() - - expect(sessionsMatching('mode')).toEqual([SESSION_ID]) - expect(indexer?.status()).toMatchObject({ filesFailed: 0, phase: 'current' }) - } finally { - await chmod(path, 0o644) - } -}) - -it('releases the database path when the open itself throws', async () => { - // A directory at the database path makes opening fail without leaving an ownership claim. - mkdirSync(harness.databasePath, { recursive: true }) - await expect(newIndexer().initialize()).rejects.toThrow() - - rmSync(harness.databasePath, { recursive: true, force: true }) - await expect(newIndexer().initialize()).resolves.toBeUndefined() -}) - it('re-reads a file a chunked read left half written, and settles it in one pass', async () => { const path = transcriptPath() await writeClaudeTranscript(path, ['the committed half'], SESSION_ID) @@ -353,7 +319,7 @@ it('reads a declined file at its current stat, not the one it was recorded with' // Retain the session-list cursor while deleting the index to force an append the consumer must decline. await indexer?.close() - removeSessionSearchDatabase(harness.databasePath) + removeVersionedCacheDatabase(harness.databasePath) newIndexer() await appendFile(path, `${claudeLines(['declined turn'], SESSION_ID, 10).join('\n')}\n`) await parseTranscript(path) @@ -444,50 +410,6 @@ it('keeps rows under no configured root, and retires them only when gone', async expect(sessionsMatching('profile')).toEqual([]) }) -it('stops everything on close, including work already queued', async () => { - await writeClaudeTranscript(transcriptPath(), ['indexed before the close'], SESSION_ID) - await newIndexer().start() - - const queued = indexer?.reconcile({ full: true }) - await indexer?.close() - await queued - - expect(errors).toEqual([]) - expect(clock.pendingTimers).toBe(0) - clock.advance(5 * INTERVAL_MS) - await indexer?.settled() - expect(errors).toEqual([]) - - const after = transcriptPath(OTHER_SESSION_ID) - await writeClaudeTranscript(after, ['written after the close'], OTHER_SESSION_ID) - await parseTranscript(after) - expect(sessionsMatching('written')).toEqual([]) - expect(sessionsMatching('indexed')).toEqual([SESSION_ID]) -}) - -it('stops the opening sweep at its deadline and drains the rest over the passes that follow', async () => { - for (let index = 0; index < 5; index++) { - const session = `0000000${index}-bbbb-4ccc-8ddd-eeeeeeeeeeee` - await writeClaudeTranscript(transcriptPath(session), [`backlogged session ${index}`], session) - } - await newIndexer(readsPerPass(2)).start() - expect(indexer?.status()).toMatchObject({ - filesIndexed: 2, - filesDue: 3, - phase: 'indexing', - lastSweepCompletedAt: null - }) - - await nextCycle() - expect(indexer?.status()).toMatchObject({ filesIndexed: 4, filesDue: 1, phase: 'indexing' }) - expect(indexer?.status().lastSweepCompletedAt).toBeNull() - - await nextCycle() - expect(sessionsMatching('backlogged')).toHaveLength(5) - expect(indexer?.status()).toMatchObject({ filesIndexed: 5, filesDue: 0, phase: 'current' }) - expect(indexer?.status().lastSweepCompletedAt).not.toBeNull() -}) - it.skipIf(!CAN_DENY_READ)('retires a deleted file behind a block of unreadable rows', async () => { // Keep the root nonempty so empty-root grace cannot mask retirement behavior. await writeClaudeTranscript(transcriptPath(), ['a live conversation'], SESSION_ID) @@ -520,30 +442,3 @@ it.skipIf(!CAN_DENY_READ)('retires a deleted file behind a block of unreadable r await chmod(locked, 0o700) } }) - -it('holds out a repeatedly rejected write while other files continue indexing', async () => { - const broken = transcriptPath() - await writeClaudeTranscript(broken, ['rejectedneedle'], SESSION_ID) - await writeClaudeTranscript(transcriptPath(OTHER_SESSION_ID), ['healthyneedle'], OTHER_SESSION_ID) - const subject = newIndexer() - await subject.initialize() - harness.write((db) => - db.exec(`CREATE TRIGGER reject_one_file BEFORE INSERT ON messages - WHEN (SELECT file_path FROM sessions WHERE id=NEW.session_row_id) LIKE '%${SESSION_ID}%' - BEGIN SELECT RAISE(ABORT, 'rejected fixture write'); END`) - ) - await subject.start() - for (let pass = 0; pass < 3; pass++) { - await subject.reconcile({ full: true }) - } - expect(rowFor(broken)).toEqual({ state: 'failed', failCount: 3 }) - expect(sessionsMatching('healthyneedle')).toEqual([OTHER_SESSION_ID]) - expect(sessionsMatching('rejectedneedle')).toEqual([]) - await appendFile( - transcriptPath(OTHER_SESSION_ID), - `${claudeLines(['continuedneedle'], OTHER_SESSION_ID, 10).join('\n')}\n` - ) - await subject.reconcile({ full: true }) - expect(sessionsMatching('continuedneedle')).toEqual([OTHER_SESSION_ID]) - expect(rowFor(broken)).toEqual({ state: 'failed', failCount: 3 }) -}) diff --git a/src/main/ai-vault-search/session-search-indexer.ts b/src/main/ai-vault-search/indexing/session-search-indexer.ts similarity index 95% rename from src/main/ai-vault-search/session-search-indexer.ts rename to src/main/ai-vault-search/indexing/session-search-indexer.ts index 7cef202dd5e..2f2b99d1390 100644 --- a/src/main/ai-vault-search/session-search-indexer.ts +++ b/src/main/ai-vault-search/indexing/session-search-indexer.ts @@ -6,13 +6,13 @@ import { DEFAULT_SESSION_SEARCH_RECONCILE_INTERVAL_MS, type SessionSearchIndexerOptions } from './session-search-indexer-options' -import { SessionSearchDirectoryListings } from './session-search-directory-listings' +import { SessionSearchDirectoryListings } from '../discovery/session-search-directory-listings' import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' import { runSessionSearchPass } from './session-search-pass' -import { sessionSearchHistoryCutoffMs } from './session-search-retention-policy' -import type { SessionSearchStateCounts } from './session-search-store' -import { SessionSearchWorkerStore } from './session-search-worker-store' -import type { SessionSearchDegradedRoot } from './session-search-degraded-roots' +import { sessionSearchHistoryCutoffMs } from '../session-search-retention-policy' +import type { SessionSearchStateCounts } from '../storage/session-search-store-types' +import { SessionSearchWorkerStore } from '../worker/session-search-worker-store' +import type { SessionSearchDegradedRoot } from '../discovery/session-search-degraded-roots' import { SessionSearchWorkLoop } from './session-search-work-loop' // Duplicate indexers would register competing consumers and fence each other’s writes. diff --git a/src/main/ai-vault-search/session-search-lag-recovery.test.ts b/src/main/ai-vault-search/indexing/session-search-lag-recovery.test.ts similarity index 85% rename from src/main/ai-vault-search/session-search-lag-recovery.test.ts rename to src/main/ai-vault-search/indexing/session-search-lag-recovery.test.ts index 55559668c49..c57e091bc95 100644 --- a/src/main/ai-vault-search/session-search-lag-recovery.test.ts +++ b/src/main/ai-vault-search/indexing/session-search-lag-recovery.test.ts @@ -1,12 +1,12 @@ import { appendFile, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import { expect, it } from 'vitest' -import { resetSessionParseCacheForTests } from '../ai-vault/parse-cache/session-parse-cache-store' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' +import { resetSessionParseCacheForTests } from '../../ai-vault/parse-cache/session-parse-cache-store' +import { resetTranscriptConsumersForTests } from '../../ai-vault/transcripts/session-transcript-consumers' import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' import { runSessionSearchIndexPass } from './session-search-index-pass' -import { openSessionSearchIndexFile } from './session-search-index-test-fixture' -import { SessionSearchStore } from './session-search-store' +import { openSessionSearchIndexFile } from '../storage/session-search-index-test-fixture' +import { SessionSearchStore } from '../storage/session-search-store' import { parseTranscript, sessionCandidate, userRecord } from './session-search-transcript-fixtures' it('recovers a declined append through its proven prefix while the transcript keeps growing', async () => { diff --git a/src/main/ai-vault-search/indexing/session-search-list-reparse.test.ts b/src/main/ai-vault-search/indexing/session-search-list-reparse.test.ts new file mode 100644 index 00000000000..c07f7bf4f9e --- /dev/null +++ b/src/main/ai-vault-search/indexing/session-search-list-reparse.test.ts @@ -0,0 +1,55 @@ +import { afterEach, beforeEach, expect, it } from 'vitest' +import { resetTranscriptConsumersForTests } from '../../ai-vault/transcripts/session-transcript-consumers' +import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' +import { + openSessionSearchIndexFile, + replayTranscriptRead, + syntheticCandidate, + userMessages, + type SessionSearchIndexFile +} from '../storage/session-search-index-test-fixture' +import { SessionSearchStore } from '../storage/session-search-store' + +let index: SessionSearchIndexFile +let store: SessionSearchStore +const messages = userMessages('Searchable conversation', 2) + +beforeEach(async () => { + index = await openSessionSearchIndexFile('ss-list-reparse') + store = new SessionSearchStore(index.path) + registerSessionSearchIndexConsumer(store) +}) + +afterEach(async () => { + resetTranscriptConsumersForTests() + store.close() + await index.close() +}) + +it('still indexes new appended messages', () => { + replayTranscriptRead({ messages }) + replayTranscriptRead({ + candidate: syntheticCandidate({ sizeBytes: 5000 }), + mode: 'append', + previousByteOffset: 4096, + messages, + outcome: { byteOffset: 5000 } + }) + expect(index.db.prepare('SELECT count(*) AS n FROM messages').get()).toEqual({ n: 4 }) +}) + +it('keeps the index current when a second fold appends a span it already holds', () => { + // Pi and OMP can publish the same append when folding one shared transcript. + replayTranscriptRead({ messages }) + const append = { + candidate: syntheticCandidate({ sizeBytes: 5000 }), + mode: 'append' as const, + previousByteOffset: 4096, + messages, + outcome: { byteOffset: 5000 } + } + replayTranscriptRead(append) + replayTranscriptRead(append) + expect(index.db.prepare('SELECT count(*) AS n FROM messages').get()).toEqual({ n: 4 }) + expect(index.db.prepare('SELECT state FROM files').get()).toEqual({ state: 'current' }) +}) diff --git a/src/main/ai-vault-search/session-search-live-transcript.test.ts b/src/main/ai-vault-search/indexing/session-search-live-transcript.test.ts similarity index 62% rename from src/main/ai-vault-search/session-search-live-transcript.test.ts rename to src/main/ai-vault-search/indexing/session-search-live-transcript.test.ts index 832af6e6e5f..fbc27f70b4b 100644 --- a/src/main/ai-vault-search/session-search-live-transcript.test.ts +++ b/src/main/ai-vault-search/indexing/session-search-live-transcript.test.ts @@ -1,17 +1,17 @@ -import { mkdtemp, rm, writeFile, appendFile } from 'node:fs/promises' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it } from 'vitest' -import { resetSessionParseCacheForTests } from '../ai-vault/parse-cache/session-parse-cache-store' +import { resetSessionParseCacheForTests } from '../../ai-vault/parse-cache/session-parse-cache-store' import { registerTranscriptConsumer, resetTranscriptConsumersForTests, type TranscriptSessionIdentity -} from '../ai-vault/transcripts/session-transcript-consumers' -import { requestWholeTranscriptRead } from '../ai-vault/transcripts/session-transcript-reader' -import SyncDatabase from '../sqlite/sync-database' +} from '../../ai-vault/transcripts/session-transcript-consumers' +import '../../ai-vault/transcripts/session-transcript-reader' +import SyncDatabase from '../../sqlite/sync-database' import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' -import { SessionSearchStore } from './session-search-store' +import { SessionSearchStore } from '../storage/session-search-store' import { assistantRecord, CLAUDE_SESSION_ID as SESSION_ID, @@ -64,31 +64,6 @@ function sessionsMatching(term: string): string[] { ).map((row) => row.id) } -it('indexes a Claude transcript through the reader and resumes on append', async () => { - const root = await makeTempDir() - const path = join(root, `${SESSION_ID}.jsonl`) - await writeFile( - path, - `${[ - userRecord(0, 'find the flaky terminal reattach'), - assistantRecord(1, 'look at resolveTerminalPath first') - ].join('\n')}\n` - ) - await parseTranscript(path) - expect(errors).toEqual([]) - expect(sessionsMatching('reattach')).toEqual([SESSION_ID]) - expect(sessionsMatching('terminal')).toEqual([SESSION_ID]) - - await appendFile(path, `${assistantRecord(2, 'the zygomorphic follow-up landed')}\n`) - const resumed = await parseTranscript(path) - expect(resumed.stats).toMatchObject({ incremental: 1, fullParses: 0 }) - expect(errors).toEqual([]) - expect(sessionsMatching('zygomorphic')).toEqual([SESSION_ID]) - expect(reader.prepare('SELECT count(*) AS n FROM sessions').get()).toEqual({ - n: 1 - }) -}) - it('keeps the prompt searchable while excluding tool results', async () => { const root = await makeTempDir() const codexHome = await makeTempDir() @@ -164,30 +139,3 @@ it('names a Codex session mid-read from its own opening record', async () => { cwd: '/repo/app' }) }) - -it('indexes a file the session list already read past, once a whole read is asked for', async () => { - const root = await makeTempDir() - const path = join(root, `${SESSION_ID}.jsonl`) - await writeFile(path, `${userRecord(0, 'the opening prompt')}\n`) - - // Simulate first enablement with a warm session-list cache and an empty index. - resetTranscriptConsumersForTests() - await parseTranscript(path) - registerSessionSearchIndexConsumer(store) - - await appendFile(path, `${assistantRecord(1, 'a zygomorphic reply')}\n`) - const appended = await parseTranscript(path) - expect(appended.stats).toMatchObject({ incremental: 1, fullParses: 0 }) - // The index never saw the preceding bytes, so it must decline this append. - expect(sessionsMatching('zygomorphic')).toEqual([]) - - expect(store.files()).toEqual([]) - requestWholeTranscriptRead(path) - - const reread = await parseTranscript(path) - expect(reread.stats).toMatchObject({ incremental: 0, fullParses: 1 }) - expect(errors).toEqual([]) - expect(sessionsMatching('zygomorphic')).toEqual([SESSION_ID]) - expect(sessionsMatching('opening')).toEqual([SESSION_ID]) - expect(store.files().map((row) => row.state)).toEqual(['current']) -}) diff --git a/src/main/ai-vault-search/session-search-merged-roots.test.ts b/src/main/ai-vault-search/indexing/session-search-merged-roots.test.ts similarity index 92% rename from src/main/ai-vault-search/session-search-merged-roots.test.ts rename to src/main/ai-vault-search/indexing/session-search-merged-roots.test.ts index bfad130fcc9..72cbeeebeda 100644 --- a/src/main/ai-vault-search/session-search-merged-roots.test.ts +++ b/src/main/ai-vault-search/indexing/session-search-merged-roots.test.ts @@ -1,10 +1,10 @@ -import './session-search-worker.test-fixture' +import '../worker/session-search-worker.test-fixture' import { chmod, rm } from 'node:fs/promises' import { delimiter, join } from 'node:path' import { afterEach, beforeEach, expect, it } from 'vitest' -import { resetSessionParseCacheForTests } from '../ai-vault/parse-cache/session-parse-cache-store' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' -import type SyncDatabase from '../sqlite/sync-database' +import { resetSessionParseCacheForTests } from '../../ai-vault/parse-cache/session-parse-cache-store' +import { resetTranscriptConsumersForTests } from '../../ai-vault/transcripts/session-transcript-consumers' +import type SyncDatabase from '../../sqlite/sync-database' import { SessionSearchIndexer } from './session-search-indexer' import { FakeSessionSearchClock, diff --git a/src/main/ai-vault-search/session-search-opencode-index.test.ts b/src/main/ai-vault-search/indexing/session-search-opencode-index.test.ts similarity index 72% rename from src/main/ai-vault-search/session-search-opencode-index.test.ts rename to src/main/ai-vault-search/indexing/session-search-opencode-index.test.ts index 72250fd7ff8..d9590e675d8 100644 --- a/src/main/ai-vault-search/session-search-opencode-index.test.ts +++ b/src/main/ai-vault-search/indexing/session-search-opencode-index.test.ts @@ -1,21 +1,21 @@ -import './session-search-worker.test-fixture' +import '../worker/session-search-worker.test-fixture' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' // Replace worker transport while exercising the real SQLite readers. export const openCodeReadCalls: string[] = [] vi.mock( - '../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn', + '../../ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn', async () => { const list = - await import('../ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-list') + await import('../../ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-list') const parse = - await import('../ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite') + await import('../../ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite') const capture = - await import('../ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-capture') + await import('../../ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-capture') const own = await import('./session-search-opencode-index.test') const { listOpenCode2SqliteSessions } = - await import('../ai-vault/scanners/opencode2/session-scanner-opencode2-sqlite-list') + await import('../../ai-vault/scanners/opencode2/session-scanner-opencode2-sqlite-list') return { listOpenCode2SqliteSessionsViaWorker: listOpenCode2SqliteSessions, resolveOpenCodeSqliteWorkerEntryPath: () => null, @@ -37,16 +37,13 @@ vi.mock( } } ) -import { resetSessionParseCacheForTests } from '../ai-vault/parse-cache/session-parse-cache-store' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' -import { - appendOpenCodeSqliteTurn, - writeOpenCodeSqliteDatabase -} from '../ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-fixture' -import type SyncDatabase from '../sqlite/sync-database' -import { SessionSearchEngine } from './session-search-engine' +import { resetSessionParseCacheForTests } from '../../ai-vault/parse-cache/session-parse-cache-store' +import { resetTranscriptConsumersForTests } from '../../ai-vault/transcripts/session-transcript-consumers' +import { writeOpenCodeSqliteDatabase } from '../../ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-fixture' +import type SyncDatabase from '../../sqlite/sync-database' +import { SessionSearchEngine } from '../query/session-search-engine' import { SessionSearchIndexer } from './session-search-indexer' -import { openSessionSearchDatabase } from './session-search-schema' +import { openSessionSearchDatabase } from '../storage/session-search-schema' import { FakeSessionSearchClock, openSessionSearchIndexerHarness, @@ -159,20 +156,3 @@ it('excludes tool output from both search scopes', async () => { expect(all.hits).toEqual([]) expect(openEngine().search({ query: TOOL_ONLY, scope: 'conversation' }).hits).toEqual([]) }) - -it('re-reads a session that gained a message and replaces its rows', async () => { - writeVault() - const started = await startIndexer() - expect(openEngine().search({ query: 'orthogonal vestibule' }).hits).toHaveLength(0) - - appendOpenCodeSqliteTurn(dbPath(), SESSION, { - role: 'assistant', - parts: ['an orthogonal vestibule appeared'] - }) - await started.reconcile() - - const engine = openEngine() - expect(engine.search({ query: 'orthogonal vestibule' }).hits[0]?.sessionId).toBe(SESSION) - expect(engine.search({ query: ANSWER }).hits).toHaveLength(1) - expect(openCodeReadCalls.filter((call) => call === `capture:${SESSION}`)).toHaveLength(2) -}) diff --git a/src/main/ai-vault-search/session-search-pass.ts b/src/main/ai-vault-search/indexing/session-search-pass.ts similarity index 88% rename from src/main/ai-vault-search/session-search-pass.ts rename to src/main/ai-vault-search/indexing/session-search-pass.ts index c6a2f4af744..f2fc1fbf442 100644 --- a/src/main/ai-vault-search/session-search-pass.ts +++ b/src/main/ai-vault-search/indexing/session-search-pass.ts @@ -1,17 +1,17 @@ -import type { AiVaultScanIssue } from '../../shared/ai-vault/contracts/ai-vault-types' +import type { AiVaultScanIssue } from '../../../shared/ai-vault/contracts/ai-vault-types' import { cursorChatMetaRefusals, withCursorChatMetaScan -} from '../ai-vault/scanners/cursor/session-scanner-cursor-chat-meta' -import { recordSessionScanIssue } from '../ai-vault/session-scan-issues' +} from '../../ai-vault/scanners/cursor/session-scanner-cursor-chat-meta' +import { recordSessionScanIssue } from '../../ai-vault/session-scan-issues' import { mergeDegradedRoots, scanIssueDegradedRoots, unreadableRoots, type SessionSearchDegradedRoot -} from './session-search-degraded-roots' -import { retireDeletedSessionSearchSources } from './session-search-deleted-sources' -import type { SessionSearchDirectoryReader } from './session-search-directory-listings' +} from '../discovery/session-search-degraded-roots' +import { retireDeletedSessionSearchSources } from '../discovery/session-search-deleted-sources' +import type { SessionSearchDirectoryReader } from '../discovery/session-search-directory-listings' import { runSessionSearchIndexPass } from './session-search-index-pass' import { discoverSessionSearchCandidates, @@ -19,9 +19,12 @@ import { sessionSearchEmptiedRoots, sessionSearchRootListings, type SessionSearchScanRoots -} from './session-search-scan-roots' -import type { SessionSearchFileRow, SessionSearchIndexStore } from './session-search-store' -import { sessionSearchEnumeratedContainers } from './session-search-synthetic-sources' +} from '../discovery/session-search-scan-roots' +import type { + SessionSearchFileRow, + SessionSearchIndexStore +} from '../storage/session-search-store-types' +import { sessionSearchEnumeratedContainers } from '../discovery/session-search-synthetic-sources' // Bound recent-cycle retirement work and prioritize rows within the recency window. const RETIREMENT_ROWS_PER_CYCLE = 512 diff --git a/src/main/ai-vault-search/session-search-read-decision.test.ts b/src/main/ai-vault-search/indexing/session-search-read-decision.test.ts similarity index 71% rename from src/main/ai-vault-search/session-search-read-decision.test.ts rename to src/main/ai-vault-search/indexing/session-search-read-decision.test.ts index a6137e3bfa9..1b975a461c8 100644 --- a/src/main/ai-vault-search/session-search-read-decision.test.ts +++ b/src/main/ai-vault-search/indexing/session-search-read-decision.test.ts @@ -1,11 +1,8 @@ import { expect, it } from 'vitest' -import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' -import type { SessionSearchIndexedFile } from './session-search-file-cursor' -import { - SESSION_SEARCH_FAILURES_BEFORE_HELD_OUT, - sessionSearchReadDecision -} from './session-search-read-decision' -import type { SessionSearchFileRow } from './session-search-store' +import type { SessionFileCandidate } from '../../ai-vault/session-scanner-types' +import type { SessionSearchIndexedFile } from '../storage/session-search-file-cursor' +import { sessionSearchReadDecision } from './session-search-read-decision' +import type { SessionSearchFileRow } from '../storage/session-search-store-types' const PATH = '/transcripts/one.jsonl' const MTIME = 1_740_000_000_000 @@ -66,23 +63,6 @@ it('reads whole rather than appending onto a cursor that continues nothing', () expect(decide({ file: { sizeBytes: 40 }, cursor })).toBe('whole') }) -it('retries a failed read until it has failed enough times at one stat', () => { - for (let failures = 1; failures < SESSION_SEARCH_FAILURES_BEFORE_HELD_OUT; failures++) { - expect( - decide({ row: row({ state: 'failed', failCount: failures, failedMtimeMs: MTIME }) }) - ).toBe('any') - } - expect( - decide({ - row: row({ - state: 'failed', - failCount: SESSION_SEARCH_FAILURES_BEFORE_HELD_OUT, - failedMtimeMs: MTIME - }) - }) - ).toBe('skip') -}) - it('starts trying again the moment a held-out file changes', () => { expect( decide({ diff --git a/src/main/ai-vault-search/session-search-read-decision.ts b/src/main/ai-vault-search/indexing/session-search-read-decision.ts similarity index 84% rename from src/main/ai-vault-search/session-search-read-decision.ts rename to src/main/ai-vault-search/indexing/session-search-read-decision.ts index f4c8b76f79d..9e17c4a3ec1 100644 --- a/src/main/ai-vault-search/session-search-read-decision.ts +++ b/src/main/ai-vault-search/indexing/session-search-read-decision.ts @@ -1,7 +1,10 @@ -import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' -import type { SessionParseReadRequirement } from '../ai-vault/parse-cache/session-scanner-parse-cache' -import { requiresWholeRead, type SessionSearchIndexedFile } from './session-search-file-cursor' -import type { SessionSearchFileRow } from './session-search-store' +import type { SessionFileCandidate } from '../../ai-vault/session-scanner-types' +import type { SessionParseReadRequirement } from '../../ai-vault/parse-cache/session-scanner-parse-cache' +import { + requiresWholeRead, + type SessionSearchIndexedFile +} from '../storage/session-search-file-cursor' +import type { SessionSearchFileRow } from '../storage/session-search-store-types' // Allow transient rewrite failures before holding out a file at an unchanged mtime. export const SESSION_SEARCH_FAILURES_BEFORE_HELD_OUT = 3 diff --git a/src/main/ai-vault-search/session-search-root-refresh.test.ts b/src/main/ai-vault-search/indexing/session-search-root-refresh.test.ts similarity index 57% rename from src/main/ai-vault-search/session-search-root-refresh.test.ts rename to src/main/ai-vault-search/indexing/session-search-root-refresh.test.ts index 4d77eca8317..0db32de20e8 100644 --- a/src/main/ai-vault-search/session-search-root-refresh.test.ts +++ b/src/main/ai-vault-search/indexing/session-search-root-refresh.test.ts @@ -1,15 +1,13 @@ -import './session-search-worker.test-fixture' -import { join } from 'node:path' +import '../worker/session-search-worker.test-fixture' +import 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { SessionSearchIndexer } from './session-search-indexer' import { - FakeSessionSearchClock, openSessionSearchIndexerHarness, - writeClaudeTranscript, type SessionSearchIndexerHarness } from './session-search-indexer-test-fixture' -import { resetSessionParseCacheForTests } from '../ai-vault/parse-cache/session-parse-cache-store' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' +import { resetSessionParseCacheForTests } from '../../ai-vault/parse-cache/session-parse-cache-store' +import { resetTranscriptConsumersForTests } from '../../ai-vault/transcripts/session-transcript-consumers' let harness: SessionSearchIndexerHarness let indexer: SessionSearchIndexer | undefined @@ -26,38 +24,6 @@ afterEach(async () => { await harness.cleanup() }) -it('refreshes roots on scheduled full sweeps and reuses them on recent cycles', async () => { - const clock = new FakeSessionSearchClock() - let roots = harness.roots - const resolveRoots = vi.fn(async () => roots) - indexer = new SessionSearchIndexer({ - databasePath: harness.databasePath, - roots, - resolveRoots, - historyDays: null, - clock, - fullSweepEveryCycles: 1 - }) - await indexer.start() - expect(resolveRoots).toHaveBeenCalledTimes(1) - const newRoot = join(harness.root, 'late') - const id = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' - await writeClaudeTranscript(join(newRoot, 'project', `${id}.jsonl`), ['a late conversation'], id) - roots = { ...roots, claudeProjectsDir: newRoot } - clock.advance(20_000) - await indexer.settled() - expect(resolveRoots).toHaveBeenCalledTimes(1) - expect(indexer.status().filesIndexed).toBe(0) - clock.advance(20_000) - await indexer.settled() - expect(resolveRoots).toHaveBeenCalledTimes(2) - expect(indexer.status().filesIndexed).toBe(1) - clock.advance(20_000) - await indexer.settled() - expect(resolveRoots).toHaveBeenCalledTimes(2) - expect(indexer.status().filesIndexed).toBe(1) -}) - it('does not access a closed store when pending discovery completes', async () => { const pending = Promise.withResolvers() const errors = vi.fn() diff --git a/src/main/ai-vault-search/session-search-synthetic-corpus.ts b/src/main/ai-vault-search/indexing/session-search-synthetic-corpus.ts similarity index 100% rename from src/main/ai-vault-search/session-search-synthetic-corpus.ts rename to src/main/ai-vault-search/indexing/session-search-synthetic-corpus.ts diff --git a/src/main/ai-vault-search/session-search-transcript-fixtures.ts b/src/main/ai-vault-search/indexing/session-search-transcript-fixtures.ts similarity index 95% rename from src/main/ai-vault-search/session-search-transcript-fixtures.ts rename to src/main/ai-vault-search/indexing/session-search-transcript-fixtures.ts index b8bf2968658..869dd4fc79c 100644 --- a/src/main/ai-vault-search/session-search-transcript-fixtures.ts +++ b/src/main/ai-vault-search/indexing/session-search-transcript-fixtures.ts @@ -3,8 +3,8 @@ import { createSessionParseStats, parseAgentSessionFileCached, type SessionParseStats -} from '../ai-vault/parse-cache/session-scanner-parse-cache' -import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' +} from '../../ai-vault/parse-cache/session-scanner-parse-cache' +import type { SessionFileCandidate } from '../../ai-vault/session-scanner-types' export const CLAUDE_SESSION_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' export const CODEX_SESSION_ID = '019f0000-1111-7222-8333-444444444444' diff --git a/src/main/ai-vault-search/session-search-work-loop.ts b/src/main/ai-vault-search/indexing/session-search-work-loop.ts similarity index 100% rename from src/main/ai-vault-search/session-search-work-loop.ts rename to src/main/ai-vault-search/indexing/session-search-work-loop.ts diff --git a/src/main/ai-vault-search/session-search-engine-test-fixture.ts b/src/main/ai-vault-search/query/session-search-engine-test-fixture.ts similarity index 87% rename from src/main/ai-vault-search/session-search-engine-test-fixture.ts rename to src/main/ai-vault-search/query/session-search-engine-test-fixture.ts index e109989bffc..c5f14b4fefb 100644 --- a/src/main/ai-vault-search/session-search-engine-test-fixture.ts +++ b/src/main/ai-vault-search/query/session-search-engine-test-fixture.ts @@ -1,13 +1,13 @@ -import type { TranscriptMessageRole } from '../ai-vault/transcripts/session-transcript-consumers' -import type SyncDatabase from '../sqlite/sync-database' +import type { TranscriptMessageRole } from '../../ai-vault/transcripts/session-transcript-consumers' +import type SyncDatabase from '../../sqlite/sync-database' import { SessionSearchEngine, type SessionSearchEngineOptions } from './session-search-engine' -import { cwdKey } from './session-search-file-records' -import { identifierShadowText } from './session-search-identifier-split' -import { SessionSearchStore } from './session-search-store' +import { cwdKey } from '../storage/session-search-file-records' +import { identifierShadowText } from '../storage/session-search-identifier-split' +import { SessionSearchStore } from '../storage/session-search-store' import { openSessionSearchIndexFile, type SessionSearchIndexFile -} from './session-search-index-test-fixture' +} from '../storage/session-search-index-test-fixture' export type SessionSearchHarness = { /** Engine connection; store writes through a separate connection to the same file. */ diff --git a/src/main/ai-vault-search/session-search-engine-types.ts b/src/main/ai-vault-search/query/session-search-engine-types.ts similarity index 94% rename from src/main/ai-vault-search/session-search-engine-types.ts rename to src/main/ai-vault-search/query/session-search-engine-types.ts index 14bc6c16cd1..95063138d38 100644 --- a/src/main/ai-vault-search/session-search-engine-types.ts +++ b/src/main/ai-vault-search/query/session-search-engine-types.ts @@ -1,5 +1,5 @@ -import type { AiVaultAgent } from '../../shared/ai-vault/contracts/ai-vault-types' -import type { TranscriptMessageRole } from '../ai-vault/transcripts/session-transcript-consumers' +import type { AiVaultAgent } from '../../../shared/ai-vault/contracts/ai-vault-types' +import type { TranscriptMessageRole } from '../../ai-vault/transcripts/session-transcript-consumers' // Bound planning cost for long queries, including single-token pastes. export const SESSION_SEARCH_QUERY_MAX_LENGTH = 512 diff --git a/src/main/ai-vault-search/session-search-engine.test.ts b/src/main/ai-vault-search/query/session-search-engine.test.ts similarity index 76% rename from src/main/ai-vault-search/session-search-engine.test.ts rename to src/main/ai-vault-search/query/session-search-engine.test.ts index e829c0e4cc2..1de029935a0 100644 --- a/src/main/ai-vault-search/session-search-engine.test.ts +++ b/src/main/ai-vault-search/query/session-search-engine.test.ts @@ -1,9 +1,9 @@ import { afterEach, describe, expect, it } from 'vitest' -import { AiVaultSearchRequestSchema } from '../../shared/ai-vault/search/ai-vault-search-contract' +import '../../../shared/ai-vault/search/ai-vault-search-contract' import type { SessionSearchResponse } from './session-search-engine-types' -import { planSessionSearchQuery } from './session-search-query-planner' -import { EMPTY_SNIPPET, sessionSearchSnippet } from './session-search-snippet' +import './session-search-query-planner' +import './session-search-snippet' import { addSyntheticSession, openSessionSearchHarness, @@ -55,21 +55,6 @@ describe('the conversation scope is a column filter, and it binds the whole quer expect(narrowed.planner.route).toBe('and') expect(ids(narrowed)).toEqual(['1']) }) - - it('never snippets a conversation hit out of tool output', async () => { - const { db, engine } = await open('ss-engine-scope-snippet') - addSyntheticSession(db, { id: 1, text: 'harbor pilot', toolText: 'harbor tool output line' }) - const [hit] = engine.search({ query: 'harbor', scope: 'conversation' }).hits - expect(hit?.evidence?.snippet).toContain('pilot') - expect(hit?.evidence?.snippet).not.toContain('output') - addSyntheticSession(db, { id: 2, text: 'harbor tool output line', role: 'tool' }) - const rowid = Number( - (db.prepare('SELECT max(id) AS id FROM messages').get() as { id: number }).id - ) - const plan = planSessionSearchQuery('harbor') - expect(sessionSearchSnippet(db, 'conversation', rowid, plan, 'or')).toEqual(EMPTY_SNIPPET) - expect(sessionSearchSnippet(db, 'all', rowid, plan, 'or').text).toContain('output') - }) }) describe('a session is one hit, however many of its rows matched', () => { @@ -97,16 +82,6 @@ describe('filters narrow retrieval, not just the page', () => { '2' ]) }) - - it('reads a sub-millisecond `since` as the instant it names, whatever its offset', async () => { - const { db, engine } = await open('ss-engine-since-sub-ms') - addSyntheticSession(db, { id: 1, text: 'needle', updatedAt: '2026-01-01T08:00:00.000Z' }) - addSyntheticSession(db, { id: 2, text: 'needle', updatedAt: '2026-01-01T08:00:00.001Z' }) - for (const since of ['2026-01-01T10:00:00.0005+02:00', '2026-01-01T08:00:00.0005Z']) { - const { filters } = AiVaultSearchRequestSchema.parse({ query: 'needle', filters: { since } }) - expect(ids(engine.search({ query: 'needle', filters }))).toEqual(['2']) - } - }) }) describe('evidence', () => { diff --git a/src/main/ai-vault-search/session-search-engine.ts b/src/main/ai-vault-search/query/session-search-engine.ts similarity index 93% rename from src/main/ai-vault-search/session-search-engine.ts rename to src/main/ai-vault-search/query/session-search-engine.ts index 3dd603b5ced..39a3f1c669e 100644 --- a/src/main/ai-vault-search/session-search-engine.ts +++ b/src/main/ai-vault-search/query/session-search-engine.ts @@ -1,12 +1,13 @@ -import type SyncDatabase from '../sqlite/sync-database' -import type { TranscriptMessageRole } from '../ai-vault/transcripts/session-transcript-consumers' -import { sliceAtCodeUnitLimit } from '../ai-vault/session-scanner-text-normalization' +import type SyncDatabase from '../../sqlite/sync-database' +import type { TranscriptMessageRole } from '../../ai-vault/transcripts/session-transcript-consumers' +import '../../ai-vault/session-scanner-text-normalization' +import { sliceAtCodeUnitLimit } from '../../../shared/surrogate-safe-text-slice' import { hasAiVaultSearchQueryOperators, splitAiVaultSearchQuery, type AiVaultSearchQuerySplit -} from '../../shared/ai-vault/search/ai-vault-search-query-operators' -import { matchesAiVaultQueryOperators } from '../../shared/ai-vault/session-display/ai-vault-session-filters' +} from '../../../shared/ai-vault/search/ai-vault-search-query-operators' +import { matchesAiVaultQueryOperators } from '../../../shared/ai-vault/session-display/ai-vault-session-filters' import { SESSION_SEARCH_QUERY_MAX_LENGTH, type SessionSearchHit, @@ -15,12 +16,12 @@ import { type SessionSearchScope, type SessionSearchSourcePresence } from './session-search-engine-types' -import { resolveSessionSearchLimit } from '../../shared/ai-vault/search/ai-vault-search-limit' +import { resolveSessionSearchLimit } from '../../../shared/ai-vault/search/ai-vault-search-limit' import { readIndexContentRevision, readIndexGeneration, readIndexIncarnation -} from './session-search-index-generation' +} from '../storage/session-search-index-generation' import { rankSessionHits, type MessageRow, @@ -45,7 +46,7 @@ import { type Retrieved } from './session-search-retrieval' import { sessionRowFilter } from './session-search-row-filter' -import { ensureSessionSearchQuerySchema } from './session-search-query-schema' +import { ensureSessionSearchQuerySchema } from '../storage/session-search-query-schema' import { EMPTY_SNIPPET, sessionSearchSnippet } from './session-search-snippet' import { sessionSourcePresence } from './session-search-source-presence' diff --git a/src/main/ai-vault-search/session-search-hit-ranking.test.ts b/src/main/ai-vault-search/query/session-search-hit-ranking.test.ts similarity index 100% rename from src/main/ai-vault-search/session-search-hit-ranking.test.ts rename to src/main/ai-vault-search/query/session-search-hit-ranking.test.ts diff --git a/src/main/ai-vault-search/session-search-hit-ranking.ts b/src/main/ai-vault-search/query/session-search-hit-ranking.ts similarity index 94% rename from src/main/ai-vault-search/session-search-hit-ranking.ts rename to src/main/ai-vault-search/query/session-search-hit-ranking.ts index 6aa943c9982..e7a642b80d3 100644 --- a/src/main/ai-vault-search/session-search-hit-ranking.ts +++ b/src/main/ai-vault-search/query/session-search-hit-ranking.ts @@ -1,5 +1,5 @@ -import type { AiVaultAgent } from '../../shared/ai-vault/contracts/ai-vault-types' -import { isCollapsibleContentHash } from './session-search-content-hash' +import type { AiVaultAgent } from '../../../shared/ai-vault/contracts/ai-vault-types' +import { isCollapsibleContentHash } from '../storage/session-search-content-hash' import type { SessionSearchSort } from './session-search-engine-types' const LENGTH_PRIOR = 0.02 diff --git a/src/main/ai-vault-search/session-search-page-cursor.ts b/src/main/ai-vault-search/query/session-search-page-cursor.ts similarity index 100% rename from src/main/ai-vault-search/session-search-page-cursor.ts rename to src/main/ai-vault-search/query/session-search-page-cursor.ts diff --git a/src/main/ai-vault-search/session-search-paging.test.ts b/src/main/ai-vault-search/query/session-search-paging.test.ts similarity index 72% rename from src/main/ai-vault-search/session-search-paging.test.ts rename to src/main/ai-vault-search/query/session-search-paging.test.ts index 50437ff5fe0..893efa78462 100644 --- a/src/main/ai-vault-search/session-search-paging.test.ts +++ b/src/main/ai-vault-search/query/session-search-paging.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it } from 'vitest' -import type { SessionSearchRequest } from './session-search-engine-types' + import type { SessionSearchRankedCursor } from './session-search-ranked-cursor' import { addSyntheticSession, @@ -9,8 +9,7 @@ import { import { decodeSessionSearchCursor, encodeSessionSearchCursor, - SessionSearchCursorError, - sessionSearchPageKey + SessionSearchCursorError } from './session-search-page-cursor' let harness: SessionSearchHarness | null = null @@ -38,26 +37,6 @@ async function withSessions(count: number, options = {}): Promise { - it('pages through every session exactly once, in one stable order', async () => { - const { engine } = await withSessions(25) - const request: SessionSearchRequest = { query: 'needle', limit: 10 } - const seen: string[] = [] - let cursor: string | null = null - let pages = 0 - do { - const page = engine.search(cursor ? { ...request, cursor } : request) - seen.push(...page.hits.map((hit) => hit.sessionId)) - cursor = page.page.cursor - pages++ - expect(pages).toBeLessThan(10) - } while (cursor !== null) - - expect(pages).toBe(3) - expect(seen).toHaveLength(25) - expect(new Set(seen).size).toBe(25) - expect(engine.search(request).hits.map((hit) => hit.sessionId)).toEqual(seen.slice(0, 10)) - }) - it('lets a caller change page size mid-walk', async () => { const { engine } = await withSessions(12) const first = engine.search({ query: 'needle', limit: 5 }) @@ -106,35 +85,6 @@ describe('a cursor is refused rather than reinterpreted', () => { expect((error as SessionSearchCursorError).rejection).toBe('different-query') } }) - - it.each([ - ['scope', { scope: 'conversation' as const }], - ['sort', { filters: { sort: 'newest' as const } }], - ['agents', { filters: { agents: ['codex' as const] } }], - ['scopePaths', { filters: { scopePaths: ['/repo/app'] } }], - ['since', { filters: { since: '2026-09-01T00:00:00.000Z' } }] - ])('rejects a cursor presented with a different %s', async (_field, changed) => { - const { engine } = await withSessions(25) - const request: SessionSearchRequest = { - query: 'needle', - limit: 10, - scope: 'all', - filters: { sort: 'relevance', agents: ['claude'], scopePaths: ['/'], since: undefined } - } - const first = engine.search(request) - expect(first.page.cursor).not.toBeNull() - try { - engine.search({ - ...request, - ...changed, - filters: { ...request.filters, ...('filters' in changed ? changed.filters : {}) }, - cursor: first.page.cursor! - }) - expect.unreachable('a narrowing the ranked list depends on must invalidate the cursor') - } catch (error) { - expect((error as SessionSearchCursorError).rejection).toBe('different-query') - } - }) }) describe('cursor encoding', () => { @@ -209,20 +159,6 @@ describe('the candidate limit is a tunable default, and says when it cut', () => }) }) -it('round-trips an existing offset cursor through the engine with its raw generation fence', async () => { - const { db, engine } = await withSessions(4) - const request = { query: 'needle', limit: 1 } - const first = engine.search(request) - const incarnation = String( - db.prepare("SELECT value FROM meta WHERE key = 'index_incarnation'").get()!.value - ) - const key = sessionSearchPageKey(request) - const cursor = encodeSessionSearchCursor(first.generation, 1, key, incarnation) - const second = engine.search({ ...request, cursor }) - expect(second.hits[0]?.sessionId).not.toBe(first.hits[0]?.sessionId) - expect(decodeSessionSearchCursor(second.page.cursor!, first.generation, key, incarnation)).toBe(2) -}) - it('validates frozen cursor bounds, query scopes and message ownership before exposing a hit', async () => { const { engine, db } = await withSessions(4) addSyntheticSession(db, { id: 9, cwd: '/private', text: 'hiddenneedle' }) diff --git a/src/main/ai-vault-search/session-search-posting-window.test.ts b/src/main/ai-vault-search/query/session-search-posting-window.test.ts similarity index 100% rename from src/main/ai-vault-search/session-search-posting-window.test.ts rename to src/main/ai-vault-search/query/session-search-posting-window.test.ts diff --git a/src/main/ai-vault-search/session-search-postings.ts b/src/main/ai-vault-search/query/session-search-postings.ts similarity index 97% rename from src/main/ai-vault-search/session-search-postings.ts rename to src/main/ai-vault-search/query/session-search-postings.ts index f1a77244c28..26125597d82 100644 --- a/src/main/ai-vault-search/session-search-postings.ts +++ b/src/main/ai-vault-search/query/session-search-postings.ts @@ -1,4 +1,4 @@ -import type SyncDatabase from '../sqlite/sync-database' +import type SyncDatabase from '../../sqlite/sync-database' import type { SessionSearchScope } from './session-search-engine-types' import type { MessageRow } from './session-search-hit-ranking' import { scopedExpression } from './session-search-query-planner' diff --git a/src/main/ai-vault-search/session-search-query-planner.test.ts b/src/main/ai-vault-search/query/session-search-query-planner.test.ts similarity index 100% rename from src/main/ai-vault-search/session-search-query-planner.test.ts rename to src/main/ai-vault-search/query/session-search-query-planner.test.ts diff --git a/src/main/ai-vault-search/session-search-query-planner.ts b/src/main/ai-vault-search/query/session-search-query-planner.ts similarity index 97% rename from src/main/ai-vault-search/session-search-query-planner.ts rename to src/main/ai-vault-search/query/session-search-query-planner.ts index 8b88042738f..d117a586e26 100644 --- a/src/main/ai-vault-search/session-search-query-planner.ts +++ b/src/main/ai-vault-search/query/session-search-query-planner.ts @@ -1,5 +1,5 @@ import type { SessionSearchScope } from './session-search-engine-types' -import { identifierShadowTerms } from './session-search-identifier-split' +import { identifierShadowTerms } from '../storage/session-search-identifier-split' // Match unicode61 token characters; session-search-fts5-contract.test.ts checks against SQLite. const INDEX_TOKEN = /[\p{L}\p{N}\p{M}\p{Co}_./+-]+/gu diff --git a/src/main/ai-vault-search/session-search-ranked-cursor.ts b/src/main/ai-vault-search/query/session-search-ranked-cursor.ts similarity index 100% rename from src/main/ai-vault-search/session-search-ranked-cursor.ts rename to src/main/ai-vault-search/query/session-search-ranked-cursor.ts diff --git a/src/main/ai-vault-search/session-search-retrieval.ts b/src/main/ai-vault-search/query/session-search-retrieval.ts similarity index 98% rename from src/main/ai-vault-search/session-search-retrieval.ts rename to src/main/ai-vault-search/query/session-search-retrieval.ts index b2996785434..e51785a407b 100644 --- a/src/main/ai-vault-search/session-search-retrieval.ts +++ b/src/main/ai-vault-search/query/session-search-retrieval.ts @@ -1,8 +1,8 @@ -import type SyncDatabase from '../sqlite/sync-database' +import type SyncDatabase from '../../sqlite/sync-database' import type { SessionSearchRoute, SessionSearchScope } from './session-search-engine-types' import type { SessionSearchFrozenHit } from './session-search-ranked-cursor' import { SessionSearchCursorError } from './session-search-page-cursor' -import { readIndexGeneration } from './session-search-index-generation' +import { readIndexGeneration } from '../storage/session-search-index-generation' import type { RankedSession, MessageRow, SessionRow } from './session-search-hit-ranking' import { andExpression, diff --git a/src/main/ai-vault-search/session-search-row-filter.test.ts b/src/main/ai-vault-search/query/session-search-row-filter.test.ts similarity index 78% rename from src/main/ai-vault-search/session-search-row-filter.test.ts rename to src/main/ai-vault-search/query/session-search-row-filter.test.ts index 4f0ab24cb2e..495055ea5d2 100644 --- a/src/main/ai-vault-search/session-search-row-filter.test.ts +++ b/src/main/ai-vault-search/query/session-search-row-filter.test.ts @@ -1,12 +1,12 @@ import { afterEach, describe, expect, it } from 'vitest' -import type SyncDatabase from '../sqlite/sync-database' +import type SyncDatabase from '../../sqlite/sync-database' import type { SessionSearchFilters } from './session-search-engine-types' -import { cwdKey } from './session-search-file-records' +import { cwdKey } from '../storage/session-search-file-records' import { sessionRowFilter } from './session-search-row-filter' import { openSessionSearchIndexFile, type SessionSearchIndexFile -} from './session-search-index-test-fixture' +} from '../storage/session-search-index-test-fixture' let index: SessionSearchIndexFile | null = null @@ -51,26 +51,6 @@ function selected(db: SyncDatabase, filters: SessionSearchFilters = {}): number[ } describe('a cwd scope is the sidebar key, or anything below it', () => { - it.each([ - ['C:\\Work\\App', 'c:/work/app', true], - ['C:\\Work\\App\\src', 'c:/work/app', true], - ['/work/APP/src', '/work/app', false], - ['/work/caf\u00e9', '/work/cafe\u0301', true], - ['/work/app-other', '/work/app', false], - ['/work/a_b/src', '/work/a_b', true], - ['/work/axb/src', '/work/a_b', false], - ['/work/lone\ud800/src', '/work/lone\ud800', true], - ['/', '/', true], - ['/work/app', '/', true], - ['C:\\Work\\App', '/', false], - ['C:\\', 'C:\\', true], - ['C:\\Work\\App', 'C:\\', true] - ])('scopes %s under %s: %s', async (cwd, scope, expected) => { - const db = await openIndex() - addSession(db, 1, cwd) - expect(selected(db, { scopePaths: [scope] })).toEqual(expected ? [1] : []) - }) - it('narrows to nothing when no scope the caller gave could be keyed', async () => { const db = await openIndex() addSession(db, 1, '/work/app') diff --git a/src/main/ai-vault-search/session-search-row-filter.ts b/src/main/ai-vault-search/query/session-search-row-filter.ts similarity index 98% rename from src/main/ai-vault-search/session-search-row-filter.ts rename to src/main/ai-vault-search/query/session-search-row-filter.ts index 1d105e91ab0..e380caedec7 100644 --- a/src/main/ai-vault-search/session-search-row-filter.ts +++ b/src/main/ai-vault-search/query/session-search-row-filter.ts @@ -1,4 +1,4 @@ -import { cwdKey } from './session-search-file-records' +import { cwdKey } from '../storage/session-search-file-records' import type { SessionSearchFilters } from './session-search-engine-types' type SessionRowPredicate = { diff --git a/src/main/ai-vault-search/query/session-search-snippet-marks.test.ts b/src/main/ai-vault-search/query/session-search-snippet-marks.test.ts new file mode 100644 index 00000000000..6f10c8da185 --- /dev/null +++ b/src/main/ai-vault-search/query/session-search-snippet-marks.test.ts @@ -0,0 +1,29 @@ +import { afterEach, expect, it } from 'vitest' +import './session-search-engine-types' +import { + addSyntheticSession, + openSessionSearchHarness, + type SessionSearchHarness +} from './session-search-engine-test-fixture' + +let harness: SessionSearchHarness | null = null + +afterEach(async () => { + await harness?.close() + harness = null +}) + +const TOOL = 'zebrafish appears only in the tool output here' + +it('picks by comparison, so a private-use code point in content cannot pose as a mark', async () => { + harness = await openSessionSearchHarness('ss-snippet-marks-private-use') + addSyntheticSession(harness.db, { + id: 1, + text: 'the \uE000 glyph a font printed here', + toolText: TOOL + }) + + const [hit] = harness.engine.search({ query: 'zebrafish' }).hits + expect(hit?.evidence?.snippet).toContain('zebrafish') + expect(hit?.evidence?.snippet).not.toContain('glyph') +}) diff --git a/src/main/ai-vault-search/session-search-snippet.ts b/src/main/ai-vault-search/query/session-search-snippet.ts similarity index 98% rename from src/main/ai-vault-search/session-search-snippet.ts rename to src/main/ai-vault-search/query/session-search-snippet.ts index 61f2ccaccff..b6aabf4ec0a 100644 --- a/src/main/ai-vault-search/session-search-snippet.ts +++ b/src/main/ai-vault-search/query/session-search-snippet.ts @@ -1,4 +1,4 @@ -import type SyncDatabase from '../sqlite/sync-database' +import type SyncDatabase from '../../sqlite/sync-database' import { SESSION_SEARCH_SNIPPET_MARK_CLOSE, SESSION_SEARCH_SNIPPET_MARK_OPEN diff --git a/src/main/ai-vault-search/session-search-source-presence.ts b/src/main/ai-vault-search/query/session-search-source-presence.ts similarity index 93% rename from src/main/ai-vault-search/session-search-source-presence.ts rename to src/main/ai-vault-search/query/session-search-source-presence.ts index 8e55f0b01b1..a432a0a1c6e 100644 --- a/src/main/ai-vault-search/session-search-source-presence.ts +++ b/src/main/ai-vault-search/query/session-search-source-presence.ts @@ -1,4 +1,4 @@ -import type SyncDatabase from '../sqlite/sync-database' +import type SyncDatabase from '../../sqlite/sync-database' import type { SessionSearchSourcePresence } from './session-search-engine-types' /** Read indexed presence without filesystem probes; no file row means unverifiable, not deleted. */ diff --git a/src/main/ai-vault-search/session-search-typo-policy.test.ts b/src/main/ai-vault-search/query/session-search-typo-policy.test.ts similarity index 52% rename from src/main/ai-vault-search/session-search-typo-policy.test.ts rename to src/main/ai-vault-search/query/session-search-typo-policy.test.ts index 399160092f3..094b1244fb5 100644 --- a/src/main/ai-vault-search/session-search-typo-policy.test.ts +++ b/src/main/ai-vault-search/query/session-search-typo-policy.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' -import type SyncDatabase from '../sqlite/sync-database' -import { openSessionSearchIndexFile } from './session-search-index-test-fixture' -import { ensureSessionSearchQuerySchema } from './session-search-query-schema' +import type SyncDatabase from '../../sqlite/sync-database' +import { openSessionSearchIndexFile } from '../storage/session-search-index-test-fixture' +import { ensureSessionSearchQuerySchema } from '../storage/session-search-query-schema' import { SessionSearchTypoRepair } from './session-search-typo-repair' function addSession(db: SyncDatabase, id: number): void { @@ -19,33 +19,6 @@ function addTerm(db: SyncDatabase, sessionRowId: number, term: string): void { } describe('typo repair policy', () => { - it.each([ - { input: 'coalesces', candidate: 'coalesced', copies: 2, exact: true, expected: null }, - { input: 'coalescs', candidate: 'coalesces', copies: 1, exact: false, expected: null }, - { input: 'coalescs', candidate: 'coalesces', copies: 2, exact: false, expected: 'coalesces' }, - { input: 'café', candidate: 'cafe', copies: 1, exact: false, expected: null }, - { input: 'car', candidate: 'cars', copies: 2, exact: false, expected: null }, - { input: 'calm', candidate: 'clam', copies: 2, exact: false, expected: null } - ])( - 'repairs $input to $expected with $copies postings (exact=$exact)', - async ({ input, candidate, copies, exact, expected }) => { - const index = await openSessionSearchIndexFile('ss-typo-policy') - try { - ensureSessionSearchQuerySchema(index.db) - addSession(index.db, 1) - for (let i = 0; i < copies; i++) { - addTerm(index.db, 1, candidate) - } - if (exact) { - addTerm(index.db, 1, input) - } - expect(new SessionSearchTypoRepair(index.db).correct(input, 'all')).toBe(expected) - } finally { - await index.close() - } - } - ) - it('falls through to the best candidate a reader can still reach', async () => { const index = await openSessionSearchIndexFile('ss-typo-orphaned') try { diff --git a/src/main/ai-vault-search/session-search-typo-repair.ts b/src/main/ai-vault-search/query/session-search-typo-repair.ts similarity index 98% rename from src/main/ai-vault-search/session-search-typo-repair.ts rename to src/main/ai-vault-search/query/session-search-typo-repair.ts index 7577d83121f..6a4675ac351 100644 --- a/src/main/ai-vault-search/session-search-typo-repair.ts +++ b/src/main/ai-vault-search/query/session-search-typo-repair.ts @@ -1,4 +1,4 @@ -import type SyncDatabase from '../sqlite/sync-database' +import type SyncDatabase from '../../sqlite/sync-database' import type { SessionSearchScope } from './session-search-engine-types' import { orExpression, planSessionSearchQuery, quoteFtsTerm } from './session-search-query-planner' import { SessionSearchPostings } from './session-search-postings' diff --git a/src/main/ai-vault-search/session-search-typo-scope.test.ts b/src/main/ai-vault-search/query/session-search-typo-scope.test.ts similarity index 100% rename from src/main/ai-vault-search/session-search-typo-scope.test.ts rename to src/main/ai-vault-search/query/session-search-typo-scope.test.ts diff --git a/src/main/ai-vault-search/session-search-scope-catalog.ts b/src/main/ai-vault-search/scope/session-search-scope-catalog.ts similarity index 80% rename from src/main/ai-vault-search/session-search-scope-catalog.ts rename to src/main/ai-vault-search/scope/session-search-scope-catalog.ts index b47d407b90d..4ac66132e4a 100644 --- a/src/main/ai-vault-search/session-search-scope-catalog.ts +++ b/src/main/ai-vault-search/scope/session-search-scope-catalog.ts @@ -1,7 +1,7 @@ -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { Project, ProjectHostSetup } from '../../shared/project-types' -import type { Repo } from '../../shared/repo-types' -import type { WorktreeMeta } from '../../shared/worktree/meta-types' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { Project, ProjectHostSetup } from '../../../shared/project-types' +import type { Repo } from '../../../shared/repo-types' +import type { WorktreeMeta } from '../../../shared/worktree/meta-types' // Use the answering host’s persisted registrations to avoid Git scans. export type SessionSearchScopeCatalog = { diff --git a/src/main/ai-vault-search/session-search-scope-paths.ts b/src/main/ai-vault-search/scope/session-search-scope-paths.ts similarity index 86% rename from src/main/ai-vault-search/session-search-scope-paths.ts rename to src/main/ai-vault-search/scope/session-search-scope-paths.ts index 401595c61f7..cd1768c8211 100644 --- a/src/main/ai-vault-search/session-search-scope-paths.ts +++ b/src/main/ai-vault-search/scope/session-search-scope-paths.ts @@ -4,10 +4,10 @@ import { isRuntimePathAbsolute, normalizeRuntimePathForComparison, resolveRuntimePath -} from '../../shared/cross-platform-path' -import { isFolderRepo } from '../../shared/repo-kind' -import { resolveConfiguredWorktreeBasePaths } from '../../shared/worktree/configured-worktree-base-path' -import { buildKnownOrcaWorkspaceLayouts } from '../../shared/worktree/ownership' +} from '../../../shared/cross-platform-path' +import { isFolderRepo } from '../../../shared/repo-kind' +import { resolveConfiguredWorktreeBasePaths } from '../../../shared/worktree/configured-worktree-base-path' +import { buildKnownOrcaWorkspaceLayouts } from '../../../shared/worktree/ownership' import type { SessionSearchScopeCatalog } from './session-search-scope-catalog' type ScopeRepo = SessionSearchScopeCatalog['repos'][number] diff --git a/src/main/ai-vault-search/session-search-scope-resolution.test.ts b/src/main/ai-vault-search/scope/session-search-scope-resolution.test.ts similarity index 100% rename from src/main/ai-vault-search/session-search-scope-resolution.test.ts rename to src/main/ai-vault-search/scope/session-search-scope-resolution.test.ts diff --git a/src/main/ai-vault-search/session-search-scope-resolution.ts b/src/main/ai-vault-search/scope/session-search-scope-resolution.ts similarity index 92% rename from src/main/ai-vault-search/session-search-scope-resolution.ts rename to src/main/ai-vault-search/scope/session-search-scope-resolution.ts index 76154e1bd10..485c3fcfbb1 100644 --- a/src/main/ai-vault-search/session-search-scope-resolution.ts +++ b/src/main/ai-vault-search/scope/session-search-scope-resolution.ts @@ -1,14 +1,14 @@ -import { toAiVaultProjectKey } from '../../shared/ai-vault/scanning/ai-vault-project-key' -import type { AiVaultSearchScopeIdentity } from '../../shared/ai-vault/search/ai-vault-search-scope' +import { toAiVaultProjectKey } from '../../../shared/ai-vault/scanning/ai-vault-project-key' +import type { AiVaultSearchScopeIdentity } from '../../../shared/ai-vault/search/ai-vault-search-scope' import { getRepoIdFromWorktreeId, getRepoMainWorktreeId, splitWorktreeIdForFilesystem, worktreeIdsEqual -} from '../../shared/worktree/id' -import { areRuntimePathsEqual } from '../../shared/worktree/ownership' +} from '../../../shared/worktree/id' +import { areRuntimePathsEqual } from '../../../shared/worktree/ownership' import type { SessionSearchScopeCatalog } from './session-search-scope-catalog' -import type { SessionSearchHostScope } from './session-search-service' +import type { SessionSearchHostScope } from '../session-search-service' import { managedWorktreeDirectories, ScopePathSet } from './session-search-scope-paths' type ScopeRepo = SessionSearchScopeCatalog['repos'][number] diff --git a/src/main/ai-vault-search/session-search-store-scope-catalog.test.ts b/src/main/ai-vault-search/scope/session-search-store-scope-catalog.test.ts similarity index 96% rename from src/main/ai-vault-search/session-search-store-scope-catalog.test.ts rename to src/main/ai-vault-search/scope/session-search-store-scope-catalog.test.ts index d91c327a43b..6a1ebe8ae11 100644 --- a/src/main/ai-vault-search/session-search-store-scope-catalog.test.ts +++ b/src/main/ai-vault-search/scope/session-search-store-scope-catalog.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import type { WorktreeMeta } from '../../shared/worktree/meta-types' +import type { WorktreeMeta } from '../../../shared/worktree/meta-types' import { sessionSearchScopeCatalogFromStore } from './session-search-store-scope-catalog' function meta(hostId: WorktreeMeta['hostId']): WorktreeMeta { diff --git a/src/main/ai-vault-search/session-search-store-scope-catalog.ts b/src/main/ai-vault-search/scope/session-search-store-scope-catalog.ts similarity index 81% rename from src/main/ai-vault-search/session-search-store-scope-catalog.ts rename to src/main/ai-vault-search/scope/session-search-store-scope-catalog.ts index 0862148fe99..82afb32b335 100644 --- a/src/main/ai-vault-search/session-search-store-scope-catalog.ts +++ b/src/main/ai-vault-search/scope/session-search-store-scope-catalog.ts @@ -2,11 +2,11 @@ import { getRepoExecutionHostId, normalizeExecutionHostId, type ExecutionHostId -} from '../../shared/execution-host' -import type { ProjectHostSetup } from '../../shared/project-types' -import type { WorktreeMeta } from '../../shared/worktree/meta-types' -import type { GlobalSettings } from '../../shared/global-settings-types' -import { readAllWorktreeMetaForHost } from '../persistence/host-qualified-worktree-meta' +} from '../../../shared/execution-host' +import type { ProjectHostSetup } from '../../../shared/project-types' +import type { WorktreeMeta } from '../../../shared/worktree/meta-types' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import { readAllWorktreeMetaForHost } from '../../persistence/host-qualified-worktree-meta' import type { SessionSearchScopeCatalog } from './session-search-scope-catalog' export type SessionSearchScopeStore = { diff --git a/src/main/ai-vault-search/session-search-agent-compatibility.test.ts b/src/main/ai-vault-search/session-search-agent-compatibility.test.ts index be0f6440b17..6d35163240d 100644 --- a/src/main/ai-vault-search/session-search-agent-compatibility.test.ts +++ b/src/main/ai-vault-search/session-search-agent-compatibility.test.ts @@ -6,12 +6,7 @@ import { searchResults } from '../../shared/ai-vault/search/ai-vault-search-test-fixture' import { searchSessionService, setSessionSearchService } from './session-search-service-registry' -import { - encodeSessionSearchCursor, - decodeSessionSearchCursor, - sessionSearchPageKey, - SessionSearchCursorError -} from './session-search-page-cursor' +import './query/session-search-page-cursor' afterEach(() => setSessionSearchService(null)) @@ -86,62 +81,6 @@ test.each(['relay'] as const)( } ) -test('projects agents before cursor identity and preserves every other ranking field', async () => { - const service = fakeSearchService() - service.search.mockImplementation(async (request) => { - const key = sessionSearchPageKey(request) - if (request.cursor) { - try { - decodeSessionSearchCursor(request.cursor, 7, key, 'test-index') - } catch (error) { - if (error instanceof SessionSearchCursorError) { - return { kind: 'malformed-cursor' } - } - throw error - } - } - return { - ...searchResults(), - page: { cursor: encodeSessionSearchCursor(7, 1, key, 'test-index'), hasMore: true } - } - }) - setSessionSearchService(service) - const request = { - query: 'proof', - supportedAgents: ['codex'], - scope: 'conversation' as const, - limit: 42, - debug: true, - filters: { - agents: ['codex', 'jcode'] as const, - scopePaths: ['/host/folder'], - since: '2026-08-01T00:00:00.000Z', - sort: 'newest' as const - } - } - const first = await searchSessionService( - { ...request, filters: { ...request.filters, agents: [...request.filters.agents] } }, - 'relay' - ) - if (first.kind !== 'results' || !first.page.cursor) { - throw new Error('Expected a first page with a cursor') - } - const next = { - ...request, - filters: { ...request.filters, agents: [...request.filters.agents] }, - cursor: first.page.cursor - } - expect(await searchSessionService(next, 'relay')).toMatchObject({ kind: 'results' }) - const { supportedAgents: _supportedAgents, ...expected } = next - expect(service.search).toHaveBeenLastCalledWith( - { ...expected, filters: { ...next.filters, agents: ['codex'] } }, - undefined - ) - expect( - await searchSessionService({ ...next, supportedAgents: [...AI_VAULT_AGENTS] }, 'relay') - ).toEqual({ kind: 'malformed-cursor' }) -}) - test('keeps current Jcode hits and removes unrequested agents before publication', async () => { const service = fakeSearchService() service.search.mockResolvedValue({ diff --git a/src/main/ai-vault-search/session-search-anonymous-write-memory.test.ts b/src/main/ai-vault-search/session-search-anonymous-write-memory.test.ts deleted file mode 100644 index a29b3b7b1b8..00000000000 --- a/src/main/ai-vault-search/session-search-anonymous-write-memory.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { expect, it } from 'vitest' -import { SessionSearchIndexWriter } from './session-search-index-writer' -import { - openSessionSearchIndexFile, - syntheticCandidate, - syntheticSession -} from './session-search-index-test-fixture' - -function collectHeap(): number { - if (!globalThis.gc) { - throw new Error('Run this regression with --expose-gc') - } - void /reset/.test('reset') - globalThis.gc() - globalThis.gc() - return process.memoryUsage().heapUsed -} - -it('keeps an unidentified transcript private without retaining its entire text in the heap', async () => { - const index = await openSessionSearchIndexFile('ss-anonymous-memory') - const writer = new SessionSearchIndexWriter(index.db, 64 * 1024) - const write = writer.beginWrite(syntheticCandidate(), 'replace', 0) - if (!write) { - throw new Error('expected a write') - } - try { - const baseline = collectHeap() - for (let i = 0; i < 32; i++) { - write.add({ role: 'assistant', text: `${i} ${'word '.repeat(200_000)}`, timestamp: null }) - } - const retainedBytes = collectHeap() - baseline - expect(index.db.prepare('SELECT count(*) AS n FROM sessions').get()?.n).toBe(0) - expect(index.db.prepare('SELECT count(*) AS n FROM messages').get()?.n).toBe(0) - expect(retainedBytes).toBeLessThan(8 * 1024 * 1024) - expect( - write.commit({ session: syntheticSession(), byteOffset: 32_000_000, incomplete: false }) - ).toBe(true) - const stored = index.db - .prepare('SELECT sum(length(assistant_text)) AS characters FROM messages_fts') - .get() - expect(stored?.characters).toBe(32_000_086) - } finally { - write.discard() - writer.close() - await index.close() - } -}) diff --git a/src/main/ai-vault-search/session-search-content-hash.test.ts b/src/main/ai-vault-search/session-search-content-hash.test.ts deleted file mode 100644 index cba9a6507c8..00000000000 --- a/src/main/ai-vault-search/session-search-content-hash.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { expect, it } from 'vitest' -import { - EMPTY_CONTENT_HASH, - foldContentHash, - isCollapsibleContentHash -} from './session-search-content-hash' -import { userMessages } from './session-search-index-test-fixture' - -it('reaches the same digest whether the prefix arrives whole or in two appends', () => { - const messages = userMessages('turn', 5) - const whole = foldContentHash(EMPTY_CONTENT_HASH, messages) - const resumed = foldContentHash( - foldContentHash(EMPTY_CONTENT_HASH, messages.slice(0, 2)), - messages.slice(2) - ) - - expect(resumed).toEqual(whole) - expect(whole.count).toBe(5) -}) - -it('freezes once the prefix limit is reached so later appends cannot move it', () => { - const capped = foldContentHash(EMPTY_CONTENT_HASH, userMessages('turn', 64)) - expect(capped.count).toBeLessThan(64) - expect(foldContentHash(capped, userMessages('later', 20))).toEqual(capped) -}) - -it('refuses to collapse on a prefix too short to mean anything', () => { - const one = foldContentHash(EMPTY_CONTENT_HASH, userMessages('only turn', 1)) - expect(isCollapsibleContentHash(one.hash, one.count)).toBe(false) - const two = foldContentHash(EMPTY_CONTENT_HASH, userMessages('two turns', 2)) - expect(isCollapsibleContentHash(two.hash, two.count)).toBe(true) - expect(isCollapsibleContentHash(null, 9)).toBe(false) -}) diff --git a/src/main/ai-vault-search/session-search-dependent-transcripts.test.ts b/src/main/ai-vault-search/session-search-dependent-transcripts.test.ts deleted file mode 100644 index abdf31707bc..00000000000 --- a/src/main/ai-vault-search/session-search-dependent-transcripts.test.ts +++ /dev/null @@ -1,193 +0,0 @@ -import { mkdir, stat, unlink, writeFile } from 'node:fs/promises' -import { dirname, join } from 'node:path' -import { afterEach, beforeEach, expect, it } from 'vitest' -import { parseAgentSessionFileCached } from '../ai-vault/parse-cache/session-scanner-parse-cache' -import { resetSessionParseCacheForTests } from '../ai-vault/parse-cache/session-parse-cache-store' -import { resetCodexSessionIndexTitleCacheForTests } from '../ai-vault/scanners/codex/session-scanner-codex-title-index' -import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' -import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' -import { - openSessionSearchIndexFile, - type SessionSearchIndexFile -} from './session-search-index-test-fixture' -import { SessionSearchStore } from './session-search-store' -import { - CODEX_ROLLOUT_FILE, - CODEX_SESSION_ID, - codexRolloutLines, - sessionCandidate -} from './session-search-transcript-fixtures' - -let index: SessionSearchIndexFile -let store: SessionSearchStore -let root: string -let errors: unknown[] -const SESSION_ID = '0b5e1c2a-3d4f-4a5b-8c6d-7e8f9a0b1c2d' - -beforeEach(async () => { - resetTranscriptConsumersForTests() - resetCodexSessionIndexTitleCacheForTests() - index = await openSessionSearchIndexFile('ss-dependent-transcripts') - root = dirname(index.path) - errors = [] - store = new SessionSearchStore(index.path, (error) => errors.push(error)) - registerSessionSearchIndexConsumer(store) -}) - -afterEach(async () => { - resetTranscriptConsumersForTests() - resetSessionParseCacheForTests() - resetCodexSessionIndexTitleCacheForTests() - store.close() - await index.close() -}) - -async function writeSource(path: string, content: string): Promise { - await mkdir(dirname(path), { recursive: true }) - await writeFile(path, content) -} - -async function coldRead(candidate: SessionFileCandidate) { - resetSessionParseCacheForTests() - const session = await parseAgentSessionFileCached(candidate, process.platform) - expect(errors).toEqual([]) - expect(session).not.toBeNull() - return session -} - -function matches(term: string): unknown { - return index.db - .prepare( - `SELECT count(*) AS n FROM messages_fts - JOIN messages m ON m.id = messages_fts.rowid - JOIN sessions s ON s.id = m.session_row_id - WHERE messages_fts MATCH ?` - ) - .get(term) -} - -it.each(['cline', 'kiro'] as const)( - 'removes old searchable messages when the %s sidecar is deleted', - async (agent) => { - const path = join(root, agent, SESSION_ID, `${SESSION_ID}.json`) - const sidecarPath = agent === 'cline' ? path.replace(/\.json$/, '.messages.json') : `${path}l` - await writeSource(path, JSON.stringify({ session_id: SESSION_ID, title: 'Conversation' })) - await writeSource( - sidecarPath, - agent === 'cline' - ? JSON.stringify({ messages: [{ role: 'user', content: 'oldsidecarmessage' }] }) - : `${JSON.stringify({ - kind: 'Prompt', - data: { content: [{ kind: 'text', data: 'oldsidecarmessage' }] } - })}\n` - ) - const candidate = await sessionCandidate(agent, path) - const sidecar = await stat(sidecarPath) - candidate.file.sidecar = { - path: sidecarPath, - mtimeMs: sidecar.mtimeMs, - sizeBytes: sidecar.size - } - await coldRead(candidate) - expect(matches('oldsidecarmessage')).toEqual({ n: 1 }) - - await unlink(sidecarPath) - const after = await sessionCandidate(agent, path) - expect(after.file).toEqual({ ...candidate.file, sidecar: undefined }) - after.file.sidecar = 'none' - expect(await coldRead(after)).toMatchObject({ messageCount: 0 }) - expect(matches('oldsidecarmessage')).toEqual({ n: 0 }) - expect(index.db.prepare('SELECT state FROM files').get()).toEqual({ state: 'current' }) - } -) - -it.each(['opencode', 'kimi', 'grok'] as const)( - 'repairs %s search content after a cold reread of unchanged candidate metadata', - async (agent) => { - const source = await multiFileSource(agent) - await writeSource(source.messagesPath, source.message('olddependentmessage')) - const candidate = await sessionCandidate(agent, source.path) - candidate.file.sidecar = 'none' - await coldRead(candidate) - expect(matches('olddependentmessage')).toEqual({ n: 1 }) - - await writeSource(source.messagesPath, source.message('newdependentmessage')) - expect((await sessionCandidate(agent, source.path)).file).toEqual({ - ...candidate.file, - sidecar: undefined - }) - const session = await coldRead(candidate) - expect(session?.previewMessages).toEqual( - expect.arrayContaining([expect.objectContaining({ text: 'newdependentmessage' })]) - ) - expect(matches('newdependentmessage')).toEqual({ n: 1 }) - expect(matches('olddependentmessage')).toEqual({ n: 0 }) - } -) - -async function multiFileSource(agent: 'opencode' | 'kimi' | 'grok') { - if (agent === 'opencode') { - const path = join(root, 'storage', 'session', 'project', 'ses_fixture.json') - await writeSource(path, JSON.stringify({ id: SESSION_ID, title: 'Conversation' })) - return { - path, - messagesPath: join(root, 'storage', 'message', SESSION_ID, 'msg_fixture.json'), - message: (text: string) => JSON.stringify({ role: 'user', content: text }) - } - } - if (agent === 'kimi') { - const directory = join(root, 'kimi', 'sessions', 'wd_app_abc', `session_${SESSION_ID}`) - const path = join(directory, 'state.json') - await writeSource(path, JSON.stringify({ title: 'Conversation' })) - return { - path, - messagesPath: join(directory, 'agents', 'main', 'wire.jsonl'), - message: (text: string) => - `${JSON.stringify({ - type: 'context.append_message', - message: { role: 'user', origin: { kind: 'user' }, content: text } - })}\n` - } - } - const path = join(root, 'grok', SESSION_ID, 'summary.json') - await writeSource( - path, - JSON.stringify({ info: { id: SESSION_ID }, generated_title: 'Conversation' }) - ) - return { - path, - messagesPath: join(dirname(path), 'chat_history.jsonl'), - message: (text: string) => - `${JSON.stringify({ type: 'user', content: `${text}` })}\n` - } -} - -it('updates the indexed Codex title when only session_index.jsonl changes', async () => { - const home = join(root, 'codex') - const path = join(home, 'sessions', CODEX_ROLLOUT_FILE) - await writeSource(path, `${codexRolloutLines(['pwd'], '/repo/app', 'codexmessage').join('\n')}\n`) - const titleIndex = join(home, 'session_index.jsonl') - await writeSource( - titleIndex, - `${JSON.stringify({ id: CODEX_SESSION_ID, thread_name: 'Original' })}\n` - ) - const candidate = await sessionCandidate('codex', path, home) - candidate.file.sidecar = 'none' - await coldRead(candidate) - expect(index.db.prepare('SELECT title FROM sessions').get()).toEqual({ title: 'Original' }) - - await writeSource( - titleIndex, - `${JSON.stringify({ id: CODEX_SESSION_ID, thread_name: 'Renamed conversation' })}\n` - ) - expect((await sessionCandidate('codex', path, home)).file).toEqual({ - ...candidate.file, - sidecar: undefined - }) - expect(await coldRead(candidate)).toMatchObject({ title: 'Renamed conversation' }) - expect(index.db.prepare('SELECT title FROM sessions').get()).toEqual({ - title: 'Renamed conversation' - }) - expect(matches('codexmessage')).toEqual({ n: 1 }) -}) diff --git a/src/main/ai-vault-search/session-search-enablement.ts b/src/main/ai-vault-search/session-search-enablement.ts index 62e17893cb6..da27f3b3887 100644 --- a/src/main/ai-vault-search/session-search-enablement.ts +++ b/src/main/ai-vault-search/session-search-enablement.ts @@ -6,13 +6,13 @@ import { installSessionSearchPolicySource } from './session-search-policy' import { installSessionSearchScopeCatalogSource, type SessionSearchScopeCatalogSource -} from './session-search-scope-catalog' +} from './scope/session-search-scope-catalog' import { setSessionSearchService } from './session-search-service-registry' import { installSessionSearchDataRoot, sessionSearchServiceInit } from './session-search-service-init' -import { sessionSearchSqliteAvailable } from './session-search-sqlite-support' +import { isSqliteAvailable } from '../sqlite/sync-database' let installed = false /** Register even when disabled so callers distinguish denied consent from an unsupported host. */ @@ -22,7 +22,7 @@ export function installChildSessionSearchService(args: { /** How a Workspace or Project scope becomes this host's own paths. */ getScopeCatalog?: SessionSearchScopeCatalogSource }): { dispose(): void } | null { - if (!sessionSearchSqliteAvailable()) { + if (!isSqliteAvailable()) { return null } installed = true diff --git a/src/main/ai-vault-search/session-search-file-id.test.ts b/src/main/ai-vault-search/session-search-file-id.test.ts deleted file mode 100644 index a29b22ee0a3..00000000000 --- a/src/main/ai-vault-search/session-search-file-id.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { afterEach, beforeEach, expect, it } from 'vitest' -import { SessionSearchIndexConsumer } from './session-search-index-consumer' -import { - openSessionSearchIndexFile, - syntheticCandidate, - syntheticSession, - SYNTHETIC_TRANSCRIPT, - type SessionSearchIndexFile -} from './session-search-index-test-fixture' -import { sessionSearchReadDecision } from './session-search-read-decision' -import { SessionSearchStore } from './session-search-store' - -const LARGE_ID = 25_614_222_884_620_952 -let index: SessionSearchIndexFile -let store: SessionSearchStore -let errors: unknown[] - -beforeEach(async () => { - index = await openSessionSearchIndexFile('ss-file-id') - errors = [] - store = new SessionSearchStore(index.path, (error) => errors.push(error)) -}) - -afterEach(async () => { - store.close() - await index.close() -}) - -it.each([ - { dev: 1, ino: LARGE_ID }, - { dev: LARGE_ID, ino: 1 }, - { dev: Number.MAX_SAFE_INTEGER, ino: Number.MAX_SAFE_INTEGER }, - { dev: 0, ino: 0 }, - { dev: 1, ino: 2 ** 63 } -])('round-trips numeric stat identity across reopen: %j', (identity) => { - const candidate = syntheticCandidate(identity) - const write = store.beginWrite(candidate, 'replace', 0) - expect(write?.commit({ session: syntheticSession(), byteOffset: 4096, incomplete: false })).toBe( - true - ) - store.close() - store = new SessionSearchStore(index.path, (error) => errors.push(error)) - - const row = store.files()[0] - expect(row?.identity).toEqual(identity) - const cursor = store.indexedFile(SYNTHETIC_TRANSCRIPT, identity) - expect(cursor).toEqual({ byteOffset: 4096, mtimeMs: candidate.file.mtimeMs, sizeBytes: 4096 }) - expect(sessionSearchReadDecision({ candidate, row, cursor, cutoffMs: null })).toBe('skip') - - const consumer = new SessionSearchIndexConsumer(store) - const append = consumer.beginRead({ - candidate: syntheticCandidate({ ...identity, sizeBytes: 8192 }), - mode: 'append', - previousByteOffset: 4096 - }) - expect(append).not.toBeNull() - append?.finish({ session: syntheticSession(), byteOffset: 8192, incomplete: false }) - expect(store.indexedFile(SYNTHETIC_TRANSCRIPT, identity)?.byteOffset).toBe(8192) - - for (const replacement of [ - { ...identity, ino: identity.ino + 4096 }, - { ...identity, dev: identity.dev + 4096 } - ]) { - const replaced = syntheticCandidate(replacement) - const replacementCursor = store.indexedFile(SYNTHETIC_TRANSCRIPT, replacement) - expect(replacementCursor).toBeNull() - expect( - sessionSearchReadDecision({ - candidate: replaced, - row, - cursor: replacementCursor, - cutoffMs: null - }) - ).toBe('whole') - expect( - consumer.beginRead({ candidate: replaced, mode: 'append', previousByteOffset: 8192 }) - ).toBeNull() - } - expect(errors).toEqual([]) -}) - -it.each([ - { dev: BigInt(LARGE_ID), ino: 1n }, - { dev: 1n, ino: BigInt(LARGE_ID) }, - { dev: null, ino: BigInt(LARGE_ID) }, - { dev: BigInt(LARGE_ID), ino: null }, - { dev: null, ino: null } -])('reads already-written INTEGER identities and incomplete pairs: $dev / $ino', ({ dev, ino }) => { - index.db - .prepare('INSERT INTO files(path, dev, ino, byte_offset, mtime_ms) VALUES (?, ?, ?, 100, 0)') - .run(SYNTHETIC_TRANSCRIPT, dev, ino) - - expect(store.files()[0]?.identity).toEqual( - dev !== null && ino !== null ? { dev: Number(dev), ino: Number(ino) } : null - ) - const identity = { dev: Number(dev), ino: Number(ino) } - expect(store.indexedFile(SYNTHETIC_TRANSCRIPT, identity)?.byteOffset).toBe(100) - expect(store.indexedFile(SYNTHETIC_TRANSCRIPT, null)?.byteOffset).toBe(100) - expect(errors).toEqual([]) -}) diff --git a/src/main/ai-vault-search/session-search-file-write.test.ts b/src/main/ai-vault-search/session-search-file-write.test.ts deleted file mode 100644 index 5c193720221..00000000000 --- a/src/main/ai-vault-search/session-search-file-write.test.ts +++ /dev/null @@ -1,309 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' -import SyncDatabase from '../sqlite/sync-database' -import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' -import { requiresWholeRead } from './session-search-file-cursor' -import { SessionSearchIndexWriter } from './session-search-index-writer' -import { deleteExpiredSearchFiles } from './session-search-retention-delete' -import { - openSessionSearchIndexFile, - replayTranscriptRead, - syntheticCandidate, - syntheticSession, - SYNTHETIC_TRANSCRIPT, - userMessages, - type SessionSearchIndexFile -} from './session-search-index-test-fixture' -import { SessionSearchStore } from './session-search-store' - -// Read through a second connection to verify only committed transactions become visible. - -let index: SessionSearchIndexFile -let store: SessionSearchStore -let errors: unknown[] - -beforeEach(async () => { - index = await openSessionSearchIndexFile('ss-file-write') - errors = [] - store = new SessionSearchStore(index.path, (error) => errors.push(error)) - registerSessionSearchIndexConsumer(store) -}) - -afterEach(async () => { - vi.restoreAllMocks() - resetTranscriptConsumersForTests() - store.close() - await index.close() -}) - -function matches(db: SyncDatabase, table: string, term: string): number { - return ( - db - .prepare( - `SELECT count(*) AS n FROM ${table} JOIN messages m ON m.id = ${table}.rowid - JOIN sessions s ON s.id = m.session_row_id WHERE ${table} MATCH ?` - ) - .get(term) as { n: number } - ).n -} - -function failOnStatement(pick: (sql: string) => boolean, nth: number): void { - const prepare = SyncDatabase.prototype.prepare - let seen = 0 - vi.spyOn(SyncDatabase.prototype, 'prepare').mockImplementation(function ( - this: SyncDatabase, - sql: string - ) { - if (pick(sql) && ++seen === nth) { - throw new Error('index write crashed mid transaction') - } - return prepare.call(this, sql) - }) -} - -function counts(db: SyncDatabase): Record { - const one = (sql: string): number => (db.prepare(sql).get() as { n: number }).n - return { - sessions: one('SELECT count(*) AS n FROM sessions'), - messages: one('SELECT count(*) AS n FROM messages'), - files: one('SELECT count(*) AS n FROM files'), - full: one('SELECT count(*) AS n FROM messages_fts') - } -} - -it('rolls a whole file back when a write throws part way through its transaction', () => { - replayTranscriptRead({ - messages: userMessages('firstgeneration', 3), - outcome: { byteOffset: 40 } - }) - const before = counts(index.db) - - failOnStatement((sql) => sql.startsWith('INSERT INTO messages('), 50) - replayTranscriptRead({ - messages: userMessages('crashedgeneration', 100), - outcome: { byteOffset: 900 } - }) - vi.restoreAllMocks() - - expect(counts(index.db)).toEqual(before) - expect(matches(index.db, 'messages_fts', 'crashedgeneration')).toBe(0) - expect(matches(index.db, 'messages_fts', 'firstgeneration')).toBe(3) - expect(store.indexedFile(SYNTHETIC_TRANSCRIPT, null)?.byteOffset).toBe(40) - expect(errors).toHaveLength(1) - expect( - index.db.prepare('SELECT state, fail_count FROM files WHERE path = ?').get(SYNTHETIC_TRANSCRIPT) - ).toMatchObject({ state: 'failed', fail_count: 1 }) - - replayTranscriptRead({ - messages: userMessages('afterthecrash', 2), - outcome: { byteOffset: 900 } - }) - expect(matches(index.db, 'messages_fts', 'afterthecrash')).toBe(2) - expect(store.indexedFile(SYNTHETIC_TRANSCRIPT, null)?.byteOffset).toBe(900) -}) - -it('takes the rows back when recording the cursor is what fails', () => { - replayTranscriptRead({ - messages: userMessages('firstgeneration', 3), - outcome: { byteOffset: 40 } - }) - - // Fail the cursor write to prove rows cannot commit without the offset that describes them. - failOnStatement((sql) => sql.startsWith('INSERT INTO files('), 1) - replayTranscriptRead({ - messages: userMessages('crashedgeneration', 5), - outcome: { byteOffset: 900 } - }) - vi.restoreAllMocks() - - expect(counts(index.db)).toMatchObject({ sessions: 1, messages: 3 }) - expect(matches(index.db, 'messages_fts', 'firstgeneration')).toBe(3) - expect(matches(index.db, 'messages_fts', 'crashedgeneration')).toBe(0) - expect(store.indexedFile(SYNTHETIC_TRANSCRIPT, null)?.byteOffset).toBe(40) -}) - -it('shows a reader on another handle one generation or the other, never a mixture', async () => { - replayTranscriptRead({ - messages: userMessages('firstgeneration', 3), - outcome: { byteOffset: 40 } - }) - expect(counts(index.db).messages).toBe(3) - - const write = store.beginWrite(syntheticCandidate(), 'replace', 0)! - for (const message of userMessages('secondgeneration', 7)) { - write.add(message) - expect(counts(index.db).messages).toBe(3) - expect(matches(index.db, 'messages_fts', 'secondgeneration')).toBe(0) - } - expect( - write.commit({ - session: syntheticSession(), - byteOffset: 900, - incomplete: false - }) - ).toBe(true) - - expect(matches(index.db, 'messages_fts', 'firstgeneration')).toBe(0) - expect(matches(index.db, 'messages_fts', 'secondgeneration')).toBe(7) - // Replaced messages become unreachable at commit and are reclaimed asynchronously. - expect(counts(index.db).messages).toBe(10) - await vi.waitFor(() => { - expect(counts(index.db).messages).toBe(7) - }) -}) - -const CHUNKED_MESSAGE = `chunkedneedle ${'filler '.repeat(12)}nd` - -const PROVISIONAL_IDENTITY = { - sessionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', - cwd: '/repo/app', - title: 'provisional title', - createdAt: '2026-05-01T10:00:00.000Z', - updatedAt: '2026-05-01T10:05:00.000Z' -} - -const named = (): typeof PROVISIONAL_IDENTITY => PROVISIONAL_IDENTITY - -it('leaves the session consistent after every chunk of a file too large for one transaction', () => { - expect(CHUNKED_MESSAGE.length).toBe(100) - const writer = new SessionSearchIndexWriter(index.db, 400) - const write = writer.beginWrite(syntheticCandidate(), 'replace', 0, named)! - for (const [position, message] of userMessages(CHUNKED_MESSAGE, 10).entries()) { - write.add(message) - const rows = counts(index.db).messages - expect(rows).toBe(Math.floor((position + 1) / 4) * 4) - expect(matches(index.db, 'messages_fts', 'chunkedneedle')).toBe(rows) - if (rows > 0) { - expect(requiresWholeRead(writer.indexedFile(SYNTHETIC_TRANSCRIPT, null))).toBe(true) - expect(writer.beginWrite(syntheticCandidate(), 'append', 0)).toBeNull() - } - } - expect(counts(index.db).messages).toBe(8) - - expect( - write.commit({ - session: syntheticSession(), - byteOffset: 4096, - incomplete: false - }) - ).toBe(true) - expect(counts(index.db)).toMatchObject({ - sessions: 1, - messages: 10, - full: 10 - }) - expect(writer.indexedFile(SYNTHETIC_TRANSCRIPT, null)?.byteOffset).toBe(4096) -}) - -it('commits a whole-file read over the ceiling in one transaction, never a chunk', () => { - const writer = new SessionSearchIndexWriter(index.db, 400) - const write = writer.beginWrite(syntheticCandidate(), 'replace', 0)! - const exec = SyncDatabase.prototype.exec - let opened = 0 - vi.spyOn(SyncDatabase.prototype, 'exec').mockImplementation(function ( - this: SyncDatabase, - sql: string - ) { - if (sql === 'BEGIN IMMEDIATE') { - opened += 1 - } - exec.call(this, sql) - }) - - for (const message of userMessages(CHUNKED_MESSAGE, 10)) { - write.add(message) - expect(counts(index.db)).toMatchObject({ sessions: 0, messages: 0, files: 0 }) - } - expect(write.commit({ session: syntheticSession(), byteOffset: 4096, incomplete: false })).toBe( - true - ) - vi.restoreAllMocks() - - expect(opened).toBe(1) - expect(counts(index.db)).toMatchObject({ sessions: 1, messages: 10, full: 10 }) - expect(writer.indexedFile(SYNTHETIC_TRANSCRIPT, null)?.byteOffset).toBe(4096) -}) - -it('stops a chunked read whose file was removed between its chunks', () => { - const writer = new SessionSearchIndexWriter(index.db, 400) - const write = writer.beginWrite(syntheticCandidate(), 'replace', 0, named)! - const messages = userMessages(CHUNKED_MESSAGE, 10) - for (const message of messages.slice(0, 4)) { - write.add(message) - } - expect(counts(index.db).messages).toBe(4) - - writer.removeFile(SYNTHETIC_TRANSCRIPT) - const exec = SyncDatabase.prototype.exec - let opened = 0 - vi.spyOn(SyncDatabase.prototype, 'exec').mockImplementation(function ( - this: SyncDatabase, - sql: string - ) { - if (sql === 'BEGIN IMMEDIATE') { - opened += 1 - } - exec.call(this, sql) - }) - for (const message of messages.slice(4)) { - write.add(message) - } - expect(write.commit({ session: syntheticSession(), byteOffset: 4096, incomplete: false })).toBe( - false - ) - vi.restoreAllMocks() - - // Fence once instead of reopening doomed transactions for every remaining message. - expect(opened).toBe(1) - expect(counts(index.db)).toMatchObject({ sessions: 0, messages: 0, files: 0, full: 0 }) -}) - -it('fences a first-ever read whose file was removed before it committed', () => { - const candidate = syntheticCandidate({ path: '/never-indexed.jsonl' }) - const write = store.beginWrite(candidate, 'replace', 0)! - for (const message of userMessages('removedbeforefirstcommit', 3)) { - write.add(message) - } - store.removeFile('/never-indexed.jsonl') - - expect(write.commit({ session: syntheticSession(), byteOffset: 300, incomplete: false })).toBe( - false - ) - expect(counts(index.db)).toMatchObject({ sessions: 0, messages: 0, files: 0, full: 0 }) -}) - -it('replaces a generation by cutting the old one loose, not by deleting it inline', async () => { - const writer = new SessionSearchIndexWriter(index.db) - const first = writer.beginWrite(syntheticCandidate(), 'replace', 0)! - for (const message of userMessages('firstgeneration', 200)) { - first.add(message) - } - expect(first.commit({ session: syntheticSession(), byteOffset: 100, incomplete: false })).toBe( - true - ) - const before = index.db.prepare('SELECT id FROM sessions').get() as { id: number } - expect(counts(index.db).messages).toBe(200) - - const second = writer.beginWrite(syntheticCandidate(), 'replace', 0)! - for (const message of userMessages('secondgeneration', 3)) { - second.add(message) - } - expect(second.commit({ session: syntheticSession(), byteOffset: 200, incomplete: false })).toBe( - true - ) - - // Replacement hides old rows through the session join; reclamation happens after commit. - expect(counts(index.db)).toMatchObject({ sessions: 1, messages: 203, full: 203 }) - expect(matches(index.db, 'messages_fts', 'firstgeneration')).toBe(0) - expect(matches(index.db, 'messages_fts', 'secondgeneration')).toBe(3) - - // AUTOINCREMENT prevents orphaned messages from attaching to a reused session id. - const after = index.db.prepare('SELECT id FROM sessions').get() as { id: number } - expect(after.id).toBeGreaterThan(before.id) - expect(index.db.prepare('SELECT session_row_id FROM files').get()).toEqual({ - session_row_id: after.id - }) - - await deleteExpiredSearchFiles(index.db, null, () => false) - expect(counts(index.db)).toMatchObject({ sessions: 1, messages: 3, full: 3 }) -}) diff --git a/src/main/ai-vault-search/session-search-fts5-contract.test.ts b/src/main/ai-vault-search/session-search-fts5-contract.test.ts deleted file mode 100644 index 367eee1e111..00000000000 --- a/src/main/ai-vault-search/session-search-fts5-contract.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { mkdtemp } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { removeTree } from '../../shared/windows-transient-lock-removal' -import type SyncDatabase from '../sqlite/sync-database' -import { indexTokens } from './session-search-query-planner' -import { ensureSessionSearchQuerySchema } from './session-search-query-schema' -import { openSessionSearchDatabase } from './session-search-schema' - -const FIRST_ROWID = 101 - -let tempRoots: string[] = [] - -afterEach(async () => { - await Promise.all(tempRoots.map((root) => removeTree(root))) - tempRoots = [] -}) - -async function openDatabase(): Promise { - const root = await mkdtemp(join(tmpdir(), 'orca-fts5-contract-')) - tempRoots.push(root) - return openSessionSearchDatabase(join(root, 'index.sqlite')) -} - -function insertMessageRow(db: SyncDatabase, rowid: number, text: string): void { - db.prepare( - `INSERT INTO messages_fts(rowid, user_text, assistant_text, tool_text, identifiers) - VALUES (?, ?, '', '', '')` - ).run(rowid, text) -} - -describe('sessions.file_path is deliberately not unique', () => { - it('accepts two sessions sharing one store path', async () => { - const db = await openDatabase() - const insert = db.prepare( - `INSERT INTO sessions(agent, session_id, file_path, title, resume_command) - VALUES (?, ?, ?, ?, ?)` - ) - const storePath = '/home/user/.local/share/opencode/storage.db' - insert.run('opencode', 'ses_one', storePath, 'first', 'opencode --session ses_one') - expect(() => - insert.run('opencode', 'ses_two', storePath, 'second', 'opencode --session ses_two') - ).not.toThrow() - - const rows = db - .prepare('SELECT session_id FROM sessions WHERE file_path = ? ORDER BY session_id') - .all(storePath) as { session_id: string }[] - expect(rows.map((row) => row.session_id)).toEqual(['ses_one', 'ses_two']) - db.close() - }) -}) - -describe('the planner tokenizer draws the same boundaries as unicode61', () => { - function asIndexed(token: string): string { - return token.toLowerCase().normalize('NFD').replaceAll(/\p{M}/gu, '') - } - - it('produces exactly the terms fts5vocab reports for the same text', async () => { - const db = await openDatabase() - ensureSessionSearchQuerySchema(db) - const corpus = - 'resolveTerminalPath src/main/foo-bar.ts a.b C++ #123 修复 café naïve MAX_TOKEN x' - insertMessageRow(db, FIRST_ROWID, corpus) - const indexed = ( - db.prepare('SELECT term FROM messages_vocab ORDER BY term').all() as { term: string }[] - ).map((row) => row.term) - - expect([...new Set(indexTokens(corpus).map(asIndexed))].sort()).toEqual(indexed) - db.close() - }) -}) diff --git a/src/main/ai-vault-search/session-search-host-registration.test.ts b/src/main/ai-vault-search/session-search-host-registration.test.ts index a863e95d0cf..bca9c53218a 100644 --- a/src/main/ai-vault-search/session-search-host-registration.test.ts +++ b/src/main/ai-vault-search/session-search-host-registration.test.ts @@ -1,4 +1,4 @@ -import './session-search-worker.test-fixture' +import './worker/session-search-worker.test-fixture' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { resetSessionParseCacheForTests } from '../ai-vault/parse-cache/session-parse-cache-store' @@ -8,7 +8,7 @@ import { openSessionSearchIndexerHarness, writeClaudeTranscript, type SessionSearchIndexerHarness -} from './session-search-indexer-test-fixture' +} from './indexing/session-search-indexer-test-fixture' import { searchSessionService } from './session-search-service-registry' import { resetSessionSearchPolicyForTests } from './session-search-policy' import { resetSessionSearchServiceInitForTests } from './session-search-service-init' diff --git a/src/main/ai-vault-search/session-search-in-process-service.ts b/src/main/ai-vault-search/session-search-in-process-service.ts index 66206007f55..6dfb4b0c86d 100644 --- a/src/main/ai-vault-search/session-search-in-process-service.ts +++ b/src/main/ai-vault-search/session-search-in-process-service.ts @@ -1,10 +1,10 @@ import type { AiVaultSearchSettings } from '../../shared/ai-vault/search/ai-vault-search-settings' import { sessionSearchDatabasePath } from './session-search-database-path' -import type { SessionSearchIndexerOptions } from './session-search-indexer-options' +import type { SessionSearchIndexerOptions } from './indexing/session-search-indexer-options' import { SessionSearchInstance } from './session-search-instance' -import type { SessionSearchScanRoots } from './session-search-scan-roots' +import type { SessionSearchScanRoots } from './discovery/session-search-scan-roots' import { setSessionSearchService } from './session-search-service-registry' -import { sessionSearchSqliteAvailable } from './session-search-sqlite-support' +import { isSqliteAvailable } from '../sqlite/sync-database' /** Own the index where the scanner cannot publish transcript reads; skip hosts without SQLite. */ export function installInProcessSessionSearchService(args: { @@ -14,7 +14,7 @@ export function installInProcessSessionSearchService(args: { settings: AiVaultSearchSettings onError?: (error: unknown) => void }): { apply(settings: AiVaultSearchSettings): void; dispose(): void } | null { - if (!sessionSearchSqliteAvailable()) { + if (!isSqliteAvailable()) { return null } const instance = new SessionSearchInstance({ diff --git a/src/main/ai-vault-search/session-search-index-consumer.test.ts b/src/main/ai-vault-search/session-search-index-consumer.test.ts deleted file mode 100644 index 167a7c3e340..00000000000 --- a/src/main/ai-vault-search/session-search-index-consumer.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { afterEach, beforeEach, expect, it } from 'vitest' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' -import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' -import { - openSessionSearchIndexFile, - replayTranscriptRead, - SYNTHETIC_TRANSCRIPT, - userMessages, - type SessionSearchIndexFile -} from './session-search-index-test-fixture' -import { SessionSearchStore } from './session-search-store' - -let index: SessionSearchIndexFile -let store: SessionSearchStore -let errors: unknown[] - -beforeEach(async () => { - index = await openSessionSearchIndexFile('ss-index-consumer') - errors = [] - store = new SessionSearchStore(index.path, (error) => errors.push(error)) - registerSessionSearchIndexConsumer(store) -}) - -afterEach(async () => { - resetTranscriptConsumersForTests() - store.close() - await index.close() -}) - -function owed(): { state: string; fail_count: number } | undefined { - return index.db - .prepare('SELECT state, fail_count FROM files WHERE path = ?') - .get(SYNTHETIC_TRANSCRIPT) as { state: string; fail_count: number } | undefined -} - -it('keeps the session list running when the index write fails', async () => { - replayTranscriptRead({ - messages: userMessages('healthy', 2), - outcome: { byteOffset: 100 } - }) - index.db.exec('DROP TABLE messages_fts') - - expect(() => - replayTranscriptRead({ - mode: 'append', - previousByteOffset: 100, - messages: userMessages('broken', 400), - outcome: { byteOffset: 500 } - }) - ).not.toThrow() - expect(errors.length).toBeGreaterThan(0) - expect(owed()?.state).not.toBe('current') -}) diff --git a/src/main/ai-vault-search/session-search-instance.test.ts b/src/main/ai-vault-search/session-search-instance.test.ts index b55320d7f63..09dffb79ff8 100644 --- a/src/main/ai-vault-search/session-search-instance.test.ts +++ b/src/main/ai-vault-search/session-search-instance.test.ts @@ -1,4 +1,4 @@ -import './session-search-worker.test-fixture' +import './worker/session-search-worker.test-fixture' import { existsSync } from 'node:fs' import { unlink, utimes } from 'node:fs/promises' import * as fileRemoval from '../../shared/windows-transient-lock-removal' @@ -6,15 +6,15 @@ import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { resetSessionParseCacheForTests } from '../ai-vault/parse-cache/session-parse-cache-store' import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' -import * as searchSchema from './session-search-schema' -import { SessionSearchReaders } from './session-search-readers' +import './storage/session-search-schema' +import './worker/session-search-readers' import { SessionSearchInstance } from './session-search-instance' -import { SessionSearchIndexer } from './session-search-indexer' +import { SessionSearchIndexer } from './indexing/session-search-indexer' import { openSessionSearchIndexerHarness, writeClaudeTranscript, type SessionSearchIndexerHarness -} from './session-search-indexer-test-fixture' +} from './indexing/session-search-indexer-test-fixture' const RECENT_SESSION_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' const ANCIENT_SESSION_ID = 'bbbbbbbb-cccc-4ddd-8eee-ffffffffffff' @@ -231,26 +231,6 @@ it('keeps pagination stable when the clock crosses retention before a purge', as expect(errors).toEqual([]) }) -it('propagates query failures while status remains available without a reader', async () => { - const subject = newInstance() - await subject.apply({ enabled: true, historyDays: null }) - await subject.settled() - const before = await subject.status() - vi.spyOn(SessionSearchReaders.prototype, 'query').mockRejectedValue(new Error('reader failed')) - await expect(subject.search({ query: 'needle' })).rejects.toThrow('reader failed') - expect(await subject.status()).toEqual(before) -}) - -it('rejects a failed clear and keeps the transition chain usable for another clear', async () => { - const subject = newInstance() - const remove = vi - .spyOn(searchSchema, 'removeSessionSearchDatabaseAsync') - .mockRejectedValueOnce(new Error('unlink denied')) - await expect(subject.clear()).rejects.toThrow('unlink denied') - await expect(subject.clear()).resolves.toBeUndefined() - expect(remove).toHaveBeenCalledTimes(2) -}) - it('keeps serving while an asynchronous clear deletion outlives its deadline', async () => { const subject = newInstance() let reject!: (error: Error) => void diff --git a/src/main/ai-vault-search/session-search-instance.ts b/src/main/ai-vault-search/session-search-instance.ts index af3242e1c91..1212377d340 100644 --- a/src/main/ai-vault-search/session-search-instance.ts +++ b/src/main/ai-vault-search/session-search-instance.ts @@ -6,12 +6,12 @@ import type { } from '../../shared/ai-vault/search/ai-vault-search-types' import { unavailableSessionSearchStatus } from '../../shared/ai-vault/search/ai-vault-search-client' import type { AiVaultSearchSettings } from '../../shared/ai-vault/search/ai-vault-search-settings' -import { SessionSearchIndexer } from './session-search-indexer' -import { SessionSearchReaders } from './session-search-readers' +import { SessionSearchIndexer } from './indexing/session-search-indexer' +import { SessionSearchReaders } from './worker/session-search-readers' import { sessionSearchHistoryCutoffMs } from './session-search-retention-policy' -import { removeSessionSearchDatabaseAsync } from './session-search-schema' -import type { SessionSearchScanRoots } from './session-search-scan-roots' -import type { SessionSearchIndexerOptions } from './session-search-indexer-options' +import { removeSessionSearchDatabaseAsync } from './storage/session-search-schema' +import type { SessionSearchScanRoots } from './discovery/session-search-scan-roots' +import type { SessionSearchIndexerOptions } from './indexing/session-search-indexer-options' import type { SessionSearchHostScope } from './session-search-service' export type SessionSearchInstanceOptions = { diff --git a/src/main/ai-vault-search/session-search-list-reparse.test.ts b/src/main/ai-vault-search/session-search-list-reparse.test.ts deleted file mode 100644 index a2ae6384da0..00000000000 --- a/src/main/ai-vault-search/session-search-list-reparse.test.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { afterEach, beforeEach, expect, it } from 'vitest' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' -import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' -import { - openSessionSearchIndexFile, - replayTranscriptRead, - syntheticCandidate, - userMessages, - type SessionSearchIndexFile -} from './session-search-index-test-fixture' -import { SessionSearchStore } from './session-search-store' - -let index: SessionSearchIndexFile -let store: SessionSearchStore -const messages = userMessages('Searchable conversation', 2) - -beforeEach(async () => { - index = await openSessionSearchIndexFile('ss-list-reparse') - store = new SessionSearchStore(index.path) - registerSessionSearchIndexConsumer(store) -}) - -afterEach(async () => { - resetTranscriptConsumersForTests() - store.close() - await index.close() -}) - -function sessionRow(): unknown { - return index.db.prepare('SELECT id FROM sessions').get() -} - -it('keeps current search rows when a cold history list rereads the same transcript', () => { - replayTranscriptRead({ messages }) - const before = sessionRow() - replayTranscriptRead({ messages }) - expect(sessionRow()).toEqual(before) - expect(index.db.prepare('SELECT count(*) AS n FROM messages').get()).toEqual({ n: 2 }) -}) - -it('still replaces a changed transcript', () => { - const candidate = syntheticCandidate() - replayTranscriptRead({ candidate, messages }) - const before = sessionRow() - replayTranscriptRead({ - candidate: syntheticCandidate({ mtimeMs: candidate.file.mtimeMs + 1 }), - messages - }) - expect(sessionRow()).not.toEqual(before) -}) - -it('still replaces a transcript whose size changed without a timestamp change', () => { - replayTranscriptRead({ messages }) - const before = sessionRow() - replayTranscriptRead({ candidate: syntheticCandidate({ sizeBytes: 5000 }), messages }) - expect(sessionRow()).not.toEqual(before) -}) - -it('refreshes metadata supplied by a sidecar despite an unchanged transcript', () => { - replayTranscriptRead({ messages }) - const before = sessionRow() - replayTranscriptRead({ - candidate: syntheticCandidate({ - sidecar: { path: 'metadata.json', mtimeMs: 1, sizeBytes: 10 } - }), - messages - }) - expect(sessionRow()).not.toEqual(before) -}) - -it('rereads when the transcript size is unknown', () => { - replayTranscriptRead({ messages }) - const before = sessionRow() - replayTranscriptRead({ candidate: syntheticCandidate({ sizeBytes: undefined }), messages }) - expect(sessionRow()).not.toEqual(before) -}) - -it('still replaces a different file with identical size and timestamp', () => { - replayTranscriptRead({ candidate: syntheticCandidate({ dev: 1, ino: 10 }), messages }) - const before = sessionRow() - replayTranscriptRead({ candidate: syntheticCandidate({ dev: 1, ino: 11 }), messages }) - expect(sessionRow()).not.toEqual(before) -}) - -it('rereads a row indexed without a file identity once the stat supplies one', () => { - replayTranscriptRead({ messages }) - const before = sessionRow() - const identified = syntheticCandidate({ dev: 1, ino: 10 }) - replayTranscriptRead({ candidate: identified, messages }) - expect(sessionRow()).not.toEqual(before) - const repaired = sessionRow() - replayTranscriptRead({ candidate: identified, messages }) - expect(sessionRow()).toEqual(repaired) -}) - -it.each(['due', 'failed'] as const)('repairs an unchanged transcript marked %s', (state) => { - replayTranscriptRead({ messages }) - const before = sessionRow() - store.setFileState(syntheticCandidate().file.path, state) - replayTranscriptRead({ messages }) - expect(sessionRow()).not.toEqual(before) - expect(index.db.prepare('SELECT state FROM files').get()).toEqual({ state: 'current' }) -}) - -it('repairs a partial index even when the stat matches', () => { - replayTranscriptRead({ messages }) - const before = sessionRow() - index.db.exec('UPDATE files SET byte_offset = -1') - replayTranscriptRead({ messages }) - expect(sessionRow()).not.toEqual(before) -}) - -it('still indexes new appended messages', () => { - replayTranscriptRead({ messages }) - replayTranscriptRead({ - candidate: syntheticCandidate({ sizeBytes: 5000 }), - mode: 'append', - previousByteOffset: 4096, - messages, - outcome: { byteOffset: 5000 } - }) - expect(index.db.prepare('SELECT count(*) AS n FROM messages').get()).toEqual({ n: 4 }) -}) - -it('keeps the index current when a second fold appends a span it already holds', () => { - // Pi and OMP can publish the same append when folding one shared transcript. - replayTranscriptRead({ messages }) - const append = { - candidate: syntheticCandidate({ sizeBytes: 5000 }), - mode: 'append' as const, - previousByteOffset: 4096, - messages, - outcome: { byteOffset: 5000 } - } - replayTranscriptRead(append) - replayTranscriptRead(append) - expect(index.db.prepare('SELECT count(*) AS n FROM messages').get()).toEqual({ n: 4 }) - expect(index.db.prepare('SELECT state FROM files').get()).toEqual({ state: 'current' }) -}) diff --git a/src/main/ai-vault-search/session-search-message-rows.test.ts b/src/main/ai-vault-search/session-search-message-rows.test.ts deleted file mode 100644 index dced66242dc..00000000000 --- a/src/main/ai-vault-search/session-search-message-rows.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { expect, it } from 'vitest' - -import { insertSearchMessage, searchMessageRows } from './session-search-message-rows' -import { openSessionSearchIndexFile } from './session-search-index-test-fixture' - -it.each(['/repo/pericardium.ts', 'PROJ-12345', 'C++', 'cafe\u0301ine'])( - 'preserves the exact FTS token %s at a chunk boundary', - async (token) => { - const index = await openSessionSearchIndexFile('ss-rows-tokenchars') - try { - const text = ' '.repeat(7998) + token - const chunks = [...searchMessageRows([{ role: 'user', text, timestamp: null }])] - expect(chunks.map((row) => row.text).join('')).toBe(text) - for (const row of chunks) { - insertSearchMessage(index.db, 1, row) - } - expect( - index.db - .prepare('SELECT count(*) AS n FROM messages_fts WHERE messages_fts MATCH ?') - .get(`"${token}"`) - ).toEqual({ n: 1 }) - } finally { - await index.close() - } - } -) - -it.each(['\u0305', '\u030d', '\u0332'])( - 'cuts at a combining mark unicode61 treats as a separator: %s', - async (mark) => { - const index = await openSessionSearchIndexFile('ss-rows-unicode-separator') - try { - const text = `${'x'.repeat(7997)}${mark}pericardium` - for (const row of searchMessageRows([{ role: 'user', text, timestamp: null }])) { - insertSearchMessage(index.db, 1, row) - } - expect( - index.db - .prepare("SELECT count(*) AS n FROM messages_fts WHERE messages_fts MATCH 'pericardium'") - .get() - ).toEqual({ n: 1 }) - } finally { - await index.close() - } - } -) - -it('cuts at punctuation when the window holds no whitespace at all', async () => { - const index = await openSessionSearchIndexFile('ss-rows-minified') - try { - // Put the limit inside a JSON value with punctuation but no whitespace available as boundaries. - const text = `{"pad":"${'x'.repeat(7976)}","note":"pericardium"}` - expect(JSON.parse(text)).toEqual({ pad: 'x'.repeat(7976), note: 'pericardium' }) - expect(text.slice(7994, 8005)).toBe('pericardium') - expect(/\s/.test(text)).toBe(false) - - const chunks = [...searchMessageRows([{ role: 'user', text, timestamp: null }])] - expect(chunks.map((row) => row.text).join('')).toBe(text) - for (const row of chunks) { - insertSearchMessage(index.db, 1, row) - } - - expect( - index.db - .prepare('SELECT count(*) AS n FROM messages_fts WHERE messages_fts MATCH ?') - .get('pericardium') - ).toEqual({ n: 1 }) - } finally { - await index.close() - } -}) - -it('drops tool output and preserves the full conversation', () => { - const output = `pericardium ${'padding '.repeat(140_000)}` - expect([...searchMessageRows([{ role: 'tool', text: output, timestamp: null }])]).toEqual([]) - const rows = [...searchMessageRows([{ role: 'assistant', text: output, timestamp: null }])] - expect(rows.map((row) => row.text).join('')).toBe(output) -}) diff --git a/src/main/ai-vault-search/session-search-orphan-rows.test.ts b/src/main/ai-vault-search/session-search-orphan-rows.test.ts deleted file mode 100644 index 4a2a48c9003..00000000000 --- a/src/main/ai-vault-search/session-search-orphan-rows.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import type SyncDatabase from '../sqlite/sync-database' -import { - addSyntheticSession, - openSessionSearchHarness, - type SessionSearchHarness -} from './session-search-engine-test-fixture' -import { identifierShadowText } from './session-search-identifier-split' -import { planSessionSearchQuery } from './session-search-query-planner' -import { sessionSearchSnippet } from './session-search-snippet' -import { SessionSearchTypoRepair } from './session-search-typo-repair' - -// Purges leave orphaned FTS rows until reclamation; retrieval, snippets and typo repair must exclude them. - -const ORPHAN_SESSION_ROW = 99 -const ORPHAN_TEXT = 'orphaned marmoset secret' - -let harness: SessionSearchHarness | null = null - -afterEach(async () => { - await harness?.close() - harness = null -}) - -function plantOrphans(db: SyncDatabase, text: string = ORPHAN_TEXT): number[] { - const rowids: number[] = [] - for (let n = 0; n < 2; n++) { - const rowid = Number( - db - .prepare("INSERT INTO messages(session_row_id,role,ts) VALUES (?,'user',?)") - .run(ORPHAN_SESSION_ROW, '2026-09-10T00:00:00.000Z').lastInsertRowid - ) - db.prepare( - 'INSERT INTO messages_fts(rowid,user_text,assistant_text,tool_text,identifiers) VALUES (?,?,?,?,?)' - ).run(rowid, text, '', '', identifierShadowText(text)) - rowids.push(rowid) - } - return rowids -} - -async function withOrphans(): Promise<{ harness: SessionSearchHarness; rowids: number[] }> { - harness = await openSessionSearchHarness('ss-orphan-rows') - addSyntheticSession(harness.db, { id: 1, text: 'the haystack line here' }) - const rowids = plantOrphans(harness.db) - expect( - harness.db - .prepare("SELECT count(*) AS c FROM messages_fts WHERE messages_fts MATCH 'marmoset'") - .get() - ).toEqual({ c: 2 }) - expect( - harness.db.prepare("SELECT doc FROM messages_vocab WHERE term = 'marmoset'").get() - ).toEqual({ doc: 2 }) - return { harness, rowids } -} - -it.each([ - ['phrase', '"orphaned marmoset"'], - ['and', 'orphaned secret'], - ['single-token literal', 'marmoset'], - ['or', 'marmoset haystack orphaned'], - ['typo repair', 'marmosett'], - ['operator only', 'repo:app'] -])('returns no orphaned row on the %s route', async (_route, query) => { - const { harness: open } = await withOrphans() - for (const scope of ['all', 'conversation'] as const) { - const hits = open.engine.search({ query, scope }).hits - expect(hits.map((hit) => hit.sessionId)).not.toContain(String(ORPHAN_SESSION_ROW)) - expect(hits.filter((hit) => hit.evidence?.snippet.includes('marmoset'))).toEqual([]) - } -}) - -it('never repairs a term onto a spelling only orphaned rows carry', async () => { - const { harness: open } = await withOrphans() - // Vocabulary alone would propose marmoset, but its occurrences are all orphaned. - expect(new SessionSearchTypoRepair(open.db).correct('marmosett', 'all')).toBeNull() - expect(open.engine.search({ query: 'marmosett' }).planner.repairedTerms).toBeUndefined() -}) - -it('snippets nothing for an orphaned row, even asked for it by rowid', async () => { - const { harness: open, rowids } = await withOrphans() - const plan = planSessionSearchQuery('marmoset') - for (const scope of ['all', 'conversation'] as const) { - expect(sessionSearchSnippet(open.db, scope, rowids[0]!, plan, 'or')).toEqual({ - text: '', - truncated: false - }) - } -}) - -describe('a purge reclaiming rows nothing can reach', () => { - it('picks the same repair when an unreachable spelling was the more common one', async () => { - // Add orphaned occurrences to the less common live spelling to test that repair ranks only live rows. - harness = await openSessionSearchHarness('ss-orphan-drain-tie') - const db = harness.db - for (let id = 1; id <= 4; id++) { - addSyntheticSession(db, { id, text: `marmosetx session${id}` }) - } - for (let id = 5; id <= 9; id++) { - addSyntheticSession(db, { id, text: `marmosetq session${id}` }) - } - plantOrphans(db, 'marmosetx') - - const before = harness.engine.search({ query: 'marmosett' }) - expect(before.planner.repairedTerms).toEqual(['marmosetq']) - await harness.store.purgeOlderThan(null) - expect(harness.engine.search({ query: 'marmosett' }).planner.repairedTerms).toEqual( - before.planner.repairedTerms - ) - }) -}) diff --git a/src/main/ai-vault-search/session-search-reader-snapshot.test.ts b/src/main/ai-vault-search/session-search-reader-snapshot.test.ts deleted file mode 100644 index 44280d52502..00000000000 --- a/src/main/ai-vault-search/session-search-reader-snapshot.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { openSessionSearchHarness, addSyntheticSession } from './session-search-engine-test-fixture' - -it('keeps a page on one read snapshot while commits invalidate later page requests', async () => { - const harness = await openSessionSearchHarness('ss-reader-snapshot') - const { db, store, engine } = harness - addSyntheticSession(db, { id: 1, text: 'snapshotneedle' }) - addSyntheticSession(db, { id: 2, text: 'snapshotneedle' }) - const baseline = engine.search({ query: 'snapshotneedle', limit: 1 }) - const baselineSessions = baseline.hits.map((hit) => hit.sessionId) - const prepare = db.prepare.bind(db) - let changed = false - const boundary = vi.spyOn(db, 'prepare').mockImplementation((sql) => { - const statement = prepare(sql) - if (sql.includes('SELECT value FROM meta')) { - const get = statement.get.bind(statement) - statement.get = (...args) => { - const result = get(...args) - if (!changed) { - changed = true - // Why: the writer's separate connection removes the page's own hit mid-assembly; the page must not see it. - store.removeFile(`/synthetic/${baselineSessions[0]}.jsonl`) - } - return result - } - } - return statement - }) - try { - const first = engine.search({ query: 'snapshotneedle', limit: 1 }) - expect(changed).toBe(true) - expect(first.hits.map((hit) => hit.sessionId)).toEqual(baselineSessions) - expect(first.page.cursor).toBeTruthy() - boundary.mockRestore() - expect(() => - engine.search({ query: 'snapshotneedle', limit: 1, cursor: first.page.cursor! }) - ).toThrow() - } finally { - boundary.mockRestore() - await harness.close() - } -}) diff --git a/src/main/ai-vault-search/session-search-restart-reindex.test.ts b/src/main/ai-vault-search/session-search-restart-reindex.test.ts deleted file mode 100644 index a4e5deb8997..00000000000 --- a/src/main/ai-vault-search/session-search-restart-reindex.test.ts +++ /dev/null @@ -1,214 +0,0 @@ -import './session-search-worker.test-fixture' -import { appendFile, chmod, mkdir, stat, writeFile } from 'node:fs/promises' -import { dirname, join } from 'node:path' -import { afterEach, beforeEach, expect, it } from 'vitest' -import { resetSessionParseCacheForTests } from '../ai-vault/parse-cache/session-parse-cache-store' -import { asRecord } from '../ai-vault/session-scanner-record-value' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' -import type SyncDatabase from '../sqlite/sync-database' -import { SessionSearchIndexer } from './session-search-indexer' -import { - claudeLines, - FakeSessionSearchClock, - openSessionSearchIndexerHarness, - renameReplaceTranscript, - type SessionSearchIndexerHarness -} from './session-search-indexer-test-fixture' - -// chmod cannot deny reads to root or reliably enforce mode bits on Windows. -const CAN_DENY_READ = process.platform !== 'win32' && process.getuid?.() !== 0 -const SESSION_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' - -let harness: SessionSearchIndexerHarness -let indexer: SessionSearchIndexer | null -let errors: unknown[] - -beforeEach(async () => { - resetSessionParseCacheForTests() - resetTranscriptConsumersForTests() - errors = [] - harness = await openSessionSearchIndexerHarness('ss-restart') - indexer = null -}) - -afterEach(async () => { - await indexer?.close() - resetTranscriptConsumersForTests() - resetSessionParseCacheForTests() - await harness.cleanup() -}) - -function newIndexer(): SessionSearchIndexer { - indexer = new SessionSearchIndexer({ - databasePath: harness.databasePath, - roots: harness.roots, - historyDays: null, - clock: new FakeSessionSearchClock(), - reconcileIntervalMs: 20_000, - onError: (error) => errors.push(error) - }) - return indexer -} - -function transcriptPath(): string { - return join(harness.claudeProjectDir, `${SESSION_ID}.jsonl`) -} - -function sessionsMatching(term: string): unknown[] { - return harness.read((db: SyncDatabase) => - db - .prepare( - `SELECT DISTINCT s.session_id AS id FROM messages_fts - JOIN messages m ON m.id = messages_fts.rowid - JOIN sessions s ON s.id = m.session_row_id - WHERE messages_fts MATCH ? ORDER BY s.session_id` - ) - .all(term) - .map((row) => asRecord(row)?.id) - ) -} - -function fileRow(path: string): Record | null { - return harness.read((db: SyncDatabase) => - asRecord( - db - .prepare( - 'SELECT state, fail_count AS failCount, byte_offset AS byteOffset FROM files WHERE path = ?' - ) - .get(path) - ) - ) -} - -function fileState(path: string): unknown { - return fileRow(path)?.state -} - -function indexedByteOffset(path: string): unknown { - return fileRow(path)?.byteOffset -} - -function messageIds(): unknown[] { - return harness.read((db: SyncDatabase) => - db - .prepare('SELECT id FROM messages ORDER BY id') - .all() - .map((row) => asRecord(row)?.id) - ) -} - -function lines(turns: readonly string[], startIndex = 0): string { - return `${claudeLines(turns, SESSION_ID, startIndex).join('\n')}\n` -} - -/** Index, then drop in-memory parser resume points as an app restart does. */ -async function indexThenRestart(path: string, content: string): Promise { - await mkdir(dirname(path), { recursive: true }) - await writeFile(path, content) - await newIndexer().start() - const ids = messageIds() - await indexer?.close() - resetSessionParseCacheForTests() - resetTranscriptConsumersForTests() - return ids -} - -it('appends to its own rows when a transcript grows after a restart', async () => { - const path = transcriptPath() - const before = await indexThenRestart(path, lines(['indexed before the restart'])) - - await appendFile(path, lines(['quarantine after restart'], 10)) - await newIndexer().start() - - const after = messageIds() - expect(after.slice(0, before.length)).toEqual(before) - expect(after).toHaveLength(before.length + 2) - expect(sessionsMatching('restart')).toEqual([SESSION_ID]) - expect(sessionsMatching('quarantine')).toEqual([SESSION_ID]) - expect(fileState(path)).toBe('current') - expect(indexedByteOffset(path)).toBe((await stat(path)).size) - expect(errors).toEqual([]) -}) - -it('appends a line that was a partial tail at the restart once it completes', async () => { - const path = transcriptPath() - const tail = lines(['completed tail line'], 10) - const before = await indexThenRestart(path, lines(['complete line']) + tail.slice(0, 20)) - - await appendFile(path, tail.slice(20) + lines(['grown afterwards'], 20)) - await newIndexer().start() - - expect(messageIds().slice(0, before.length)).toEqual(before) - expect(sessionsMatching('completed')).toEqual([SESSION_ID]) - expect(sessionsMatching('grown')).toEqual([SESSION_ID]) - expect(indexedByteOffset(path)).toBe((await stat(path)).size) -}) - -it.each([ - { - name: 'an equal-length in-place rewrite', - rewrite: (path: string) => writeFile(path, lines(['replaced']) + lines(['and grew'], 10)) - }, - { - name: 'a truncate that regrows past the old cursor', - rewrite: (path: string) => - writeFile(path, lines(['replaced']) + lines(['and grew much longer than before'], 10)) - }, - { - name: 'a rewrite whose line now spans the old cursor', - rewrite: (path: string) => writeFile(path, lines([`replaced ${'x'.repeat(400)}`])) - }, - { - name: 'a rename onto a new inode', - rewrite: async (path: string) => { - await renameReplaceTranscript(path, ['replaced'], SESSION_ID) - await appendFile(path, lines(['and grew'], 10)) - } - } -])('replaces stale rows after a restart when the prefix changed: $name', async ({ rewrite }) => { - const path = transcriptPath() - await indexThenRestart(path, lines(['obsolete'])) - - await rewrite(path) - await newIndexer().start() - await indexer?.reconcile() - - expect(sessionsMatching('obsolete')).toEqual([]) - expect(sessionsMatching('replaced')).toEqual([SESSION_ID]) - expect(fileState(path)).toBe('current') - expect(indexedByteOffset(path)).toBe((await stat(path)).size) - expect(errors).toEqual([]) -}) - -it.skipIf(!CAN_DENY_READ)( - 'counts a failed read after a restart toward holding the file out', - async () => { - const path = transcriptPath() - await indexThenRestart(path, lines(['indexed before the restart'])) - await appendFile(path, lines(['unreadable growth'], 10)) - await chmod(path, 0o000) - try { - await newIndexer().start() - expect(fileRow(path)).toMatchObject({ state: 'failed', failCount: 1 }) - } finally { - await chmod(path, 0o644) - } - } -) - -it('appends after a restart across a prefix of several read chunks ending in a partial line', async () => { - const path = transcriptPath() - const turns = Array.from({ length: 400 }, (_, turn) => `bulk turn ${turn} ${'y'.repeat(200)}`) - const tail = lines(['spanning tail line'], 1_000) - const prefix = lines(turns) - expect(Buffer.byteLength(prefix)).toBeGreaterThan(3 * 64 * 1024) - const before = await indexThenRestart(path, prefix + tail.slice(0, 30)) - - await appendFile(path, tail.slice(30) + lines(['grown afterwards'], 2_000)) - await newIndexer().start() - - expect(messageIds().slice(0, before.length)).toEqual(before) - expect(sessionsMatching('spanning')).toEqual([SESSION_ID]) - expect(sessionsMatching('grown')).toEqual([SESSION_ID]) - expect(indexedByteOffset(path)).toBe((await stat(path)).size) -}) diff --git a/src/main/ai-vault-search/session-search-schema.test.ts b/src/main/ai-vault-search/session-search-schema.test.ts deleted file mode 100644 index 3d9e90de253..00000000000 --- a/src/main/ai-vault-search/session-search-schema.test.ts +++ /dev/null @@ -1,158 +0,0 @@ -import type * as NodeFs from 'node:fs' -import { mkdtemp, readFile, stat, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { Worker } from 'node:worker_threads' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { removeTree } from '../../shared/windows-transient-lock-removal' -import { asRecord } from '../ai-vault/session-scanner-record-value' -import SyncDatabase from '../sqlite/sync-database' -import { - SESSION_SEARCH_SCHEMA_VERSION, - addSessionSearchPrefixHashColumn, - openSessionSearchDatabase, - removeSessionSearchDatabase -} from './session-search-schema' - -const recordedRmSync = vi.hoisted(() => vi.fn()) -vi.mock('node:fs', async () => { - const actual = await vi.importActual('node:fs') - return { - ...actual, - rmSync: (...args: Parameters) => { - recordedRmSync(...args) - return actual.rmSync(...args) - } - } -}) - -let roots: string[] = [] - -afterEach(async () => { - await Promise.all(roots.map((root) => removeTree(root))) - roots = [] -}) - -async function tempDatabasePath(): Promise { - const root = await mkdtemp(join(tmpdir(), 'orca-session-search-schema-')) - roots.push(root) - return join(root, 'index.sqlite') -} - -function schemaVersion(db: SyncDatabase): string | undefined { - return ( - db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get() as - | { value: string } - | undefined - )?.value -} - -describe('openSessionSearchDatabase', () => { - it('keeps a version 8 index that predates prefix hashes and adds the column', async () => { - const path = await tempDatabasePath() - const first = openSessionSearchDatabase(path) - first.exec('ALTER TABLE files DROP COLUMN prefix_hash') - first.prepare("INSERT INTO files(path,byte_offset,mtime_ms) VALUES ('a',1,1)").run() - first.close() - - const second = openSessionSearchDatabase(path) - expect(second.prepare('SELECT path, prefix_hash FROM files').all()).toEqual([ - { path: 'a', prefix_hash: null } - ]) - second.close() - }) - - it('adds the prefix hash column once when another opener migrates under its lock', async () => { - const path = await tempDatabasePath() - const setup = openSessionSearchDatabase(path) - setup.exec('ALTER TABLE files DROP COLUMN prefix_hash') - setup.close() - const opener = new SyncDatabase(path) - opener.pragma('busy_timeout = 5000') - // The other opener holds its uncommitted ALTER while this one runs the migration. - const rival = new Worker( - ` - const { parentPort, workerData } = require('node:worker_threads') - const db = new (require('node:sqlite').DatabaseSync)(workerData.path) - db.exec('PRAGMA busy_timeout=5000; BEGIN IMMEDIATE') - db.exec('ALTER TABLE files ADD COLUMN prefix_hash TEXT') - parentPort.postMessage('locked') - setTimeout(() => { db.exec('COMMIT'); db.close(); parentPort.close() }, 300) - `, - { eval: true, workerData: { path } } - ) - try { - await new Promise((resolve, reject) => { - rival.once('message', () => resolve()) - rival.once('error', reject) - }) - expect(() => addSessionSearchPrefixHashColumn(opener)).not.toThrow() - const columns = opener - .prepare('PRAGMA table_info(files)') - .all() - .filter((column) => asRecord(column)?.name === 'prefix_hash') - expect(columns).toHaveLength(1) - } finally { - opener.close() - await rival.terminate() - } - }) - - it('replaces the file on a version mismatch instead of dropping tables in place', async () => { - const path = await tempDatabasePath() - const stale = openSessionSearchDatabase(path) - stale.prepare("INSERT INTO files(path,byte_offset,mtime_ms) VALUES ('a',1,1)").run() - stale - .prepare("UPDATE meta SET value = ? WHERE key = 'schema_version'") - .run(String(SESSION_SEARCH_SCHEMA_VERSION - 1)) - stale.exec('ALTER TABLE messages DROP COLUMN text_truncated') - stale.close() - // Remove stale WAL sidecars so SQLite cannot replay them into the rebuilt cache. - await writeFile(`${path}-wal`, 'stale wal bytes') - const before = await stat(path) - - const fresh = openSessionSearchDatabase(path) - expect(schemaVersion(fresh)).toBe(String(SESSION_SEARCH_SCHEMA_VERSION)) - expect(fresh.prepare('SELECT COUNT(*) AS c FROM files').get()).toEqual({ - c: 0 - }) - expect(fresh.prepare('SELECT text_truncated FROM messages').all()).toEqual([]) - fresh.close() - // Inodes may be reused immediately; verify sidecar removal instead. - await expect(stat(`${path}-wal`)).rejects.toMatchObject({ code: 'ENOENT' }) - expect((await stat(path)).mtimeMs).toBeGreaterThanOrEqual(before.mtimeMs) - }) - - it('removes the database with every sidecar', async () => { - const path = await tempDatabasePath() - openSessionSearchDatabase(path).close() - await writeFile(`${path}-shm`, '') - removeSessionSearchDatabase(path) - for (const suffix of ['', '-wal', '-shm']) { - await expect(stat(`${path}${suffix}`)).rejects.toMatchObject({ - code: 'ENOENT' - }) - } - }) -}) - -it('rebuilds a file too corrupt to open instead of refusing forever', async () => { - const path = await tempDatabasePath() - const healthy = openSessionSearchDatabase(path) - healthy.prepare("INSERT INTO files(path,byte_offset,mtime_ms) VALUES ('a',1,1)").run() - healthy.close() - // Corrupt data pages while retaining the header so failure occurs after opening. - const bytes = await readFile(path) - bytes.fill(0x7f, 4096, Math.min(bytes.length, 12_288)) - await writeFile(path, bytes) - - const rebuilt = openSessionSearchDatabase(path) - try { - expect(schemaVersion(rebuilt)).toBe(String(SESSION_SEARCH_SCHEMA_VERSION)) - expect(rebuilt.prepare('SELECT COUNT(*) AS c FROM files').get()).toEqual({ - c: 0 - }) - } finally { - rebuilt.close() - } -}) diff --git a/src/main/ai-vault-search/session-search-service-registry.ts b/src/main/ai-vault-search/session-search-service-registry.ts index b953da06a16..b77affb256b 100644 --- a/src/main/ai-vault-search/session-search-service-registry.ts +++ b/src/main/ai-vault-search/session-search-service-registry.ts @@ -5,8 +5,8 @@ import { AiVaultSearchStatusSchema } from '../../shared/ai-vault/search/ai-vault-search-contract' import { unavailableSessionSearchStatus } from '../../shared/ai-vault/search/ai-vault-search-client' -import { sessionSearchScopeCatalog } from './session-search-scope-catalog' -import { resolveSessionSearchScope } from './session-search-scope-resolution' +import { sessionSearchScopeCatalog } from './scope/session-search-scope-catalog' +import { resolveSessionSearchScope } from './scope/session-search-scope-resolution' import type { AiVaultSearchResponse, AiVaultSearchStatus diff --git a/src/main/ai-vault-search/session-search-service.test.ts b/src/main/ai-vault-search/session-search-service.test.ts deleted file mode 100644 index f7bc3801439..00000000000 --- a/src/main/ai-vault-search/session-search-service.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - openSessionSearchHarness, - addSyntheticSession, - type SessionSearchHarness -} from './session-search-engine-test-fixture' -import { createSessionSearchService } from './session-search-service' -import { - AiVaultSearchResponseSchema, - AiVaultSearchStatusSchema -} from '../../shared/ai-vault/search/ai-vault-search-contract' -import { unavailableSessionSearchStatus } from '../../shared/ai-vault/search/ai-vault-search-client' - -let harness: SessionSearchHarness | undefined - -afterEach(async () => { - await harness?.close() - harness = undefined -}) - -async function fixture() { - harness = await openSessionSearchHarness('public-contract') - const { enabled: _enabled, generation: _generation, ...status } = unavailableSessionSearchStatus() - // Indexer status requires root paths and message counts that are optional on the wire. - const indexer = { - status: () => ({ ...status, messagesIndexed: 0, degradedRoots: [], sessionsByAgent: {} }), - reconcile: vi.fn(async () => {}) - } - const service = createSessionSearchService({ engine: harness.engine, indexer }) - return { ...harness, service, indexer } -} - -describe('real index to public service adapter', () => { - it('pages a real store, maps evidence and diagnostics, and rejects stale or malformed cursors', async () => { - const { db, store, service } = await fixture() - addSyntheticSession(db, { id: 1 }) - addSyntheticSession(db, { id: 2, filePath: null }) - const first = await service.search({ query: 'needle', limit: 1, debug: true }) - expect(AiVaultSearchResponseSchema.parse(first)).toEqual(first) - expect(first.kind).toBe('results') - if (first.kind !== 'results') { - throw new Error('Expected results') - } - expect(first.debug?.plannerReport.scope).toBe('all') - expect(first).not.toHaveProperty('route') - expect(first).not.toHaveProperty('tier') - expect(first.page.hasMore).toBe(true) - const next = await service.search({ query: 'needle', cursor: first.page.cursor!, limit: 1 }) - expect(next.kind).toBe('results') - if (next.kind !== 'results') { - throw new Error('Expected results') - } - expect(next.hits[0].sessionId).not.toBe(first.hits[0].sessionId) - expect(next).not.toHaveProperty('debug') - const hits = [...first.hits, ...next.hits] - expect(hits.find((hit) => hit.source.presence === 'present')?.resumeCommand).toBe('resume') - expect(hits.find((hit) => hit.source.presence === 'unverifiable')).not.toHaveProperty( - 'resumeCommand' - ) - expect(await service.search({ query: 'other', cursor: first.page.cursor! })).toEqual({ - kind: 'malformed-cursor' - }) - await store.purgeOlderThan(1740000000001) - expect(await service.search({ query: 'needle', cursor: first.page.cursor! })).toMatchObject({ - kind: 'stale-cursor', - expectedGeneration: first.generation - }) - expect(await service.search({ query: 'needle', cursor: '' })).toEqual({ - kind: 'malformed-cursor' - }) - expect(await service.search({ query: 'needle', cursor: 'garbage' })).toEqual({ - kind: 'malformed-cursor' - }) - expect(await service.search({ query: 'needle' })).toMatchObject({ - kind: 'results', - hits: [expect.objectContaining({ sessionId: '2' })] - }) - }) - it('preserves null evidence for folder operators and delegates recent reconciliation', async () => { - const { db, service, indexer } = await fixture() - addSyntheticSession(db, { id: 1, cwd: '/folder/no-git-required' }) - const result = await service.search({ query: 'path:no-git-required' }) - expect(result).toMatchObject({ - kind: 'results', - hits: [expect.objectContaining({ evidence: null })] - }) - await service.reconcile() - expect(indexer.reconcile).toHaveBeenCalledExactlyOnceWith({ full: true }) - const status = await service.status() - expect(AiVaultSearchStatusSchema.parse(status)).toEqual(status) - expect(status.generation).toBeGreaterThan(0) - }) -}) diff --git a/src/main/ai-vault-search/session-search-service.ts b/src/main/ai-vault-search/session-search-service.ts index 1d26518be52..c8b0a08be68 100644 --- a/src/main/ai-vault-search/session-search-service.ts +++ b/src/main/ai-vault-search/session-search-service.ts @@ -3,9 +3,9 @@ import type { AiVaultSearchResponse, AiVaultSearchStatus } from '../../shared/ai-vault/search/ai-vault-search-types' -import type { SessionSearchEngine } from './session-search-engine' -import type { SessionSearchIndexer } from './session-search-indexer' -import { SessionSearchCursorError } from './session-search-page-cursor' +import type { SessionSearchEngine } from './query/session-search-engine' +import type { SessionSearchIndexer } from './indexing/session-search-indexer' +import { SessionSearchCursorError } from './query/session-search-page-cursor' /** Host scope bypasses the client path cap; absent scope leaves request filters unchanged. */ export type SessionSearchHostScope = diff --git a/src/main/ai-vault-search/session-search-snippet-marks.test.ts b/src/main/ai-vault-search/session-search-snippet-marks.test.ts deleted file mode 100644 index 92002754665..00000000000 --- a/src/main/ai-vault-search/session-search-snippet-marks.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { afterEach, expect, it } from 'vitest' -import { - SESSION_SEARCH_SNIPPET_MARK_CLOSE, - SESSION_SEARCH_SNIPPET_MARK_OPEN -} from './session-search-engine-types' -import { - addSyntheticSession, - openSessionSearchHarness, - type SessionSearchHarness -} from './session-search-engine-test-fixture' - -let harness: SessionSearchHarness | null = null - -afterEach(async () => { - await harness?.close() - harness = null -}) - -const BASH = 'run this: if [[ -f /home/me/.aws/credentials ]]; then cat it; fi' -const TOOL = 'zebrafish appears only in the tool output here' - -it('shows the column that matched, not the one that happens to contain brackets', async () => { - harness = await openSessionSearchHarness('ss-snippet-marks') - addSyntheticSession(harness.db, { id: 1, text: BASH, toolText: TOOL }) - addSyntheticSession(harness.db, { id: 2, text: 'run this script please', toolText: TOOL }) - - const hits = harness.engine.search({ query: 'zebrafish' }).hits - expect(hits).toHaveLength(2) - for (const hit of hits) { - expect(hit.evidence?.snippet).toContain( - `${SESSION_SEARCH_SNIPPET_MARK_OPEN}zebrafish${SESSION_SEARCH_SNIPPET_MARK_CLOSE}` - ) - expect(hit.evidence?.snippet).not.toContain('credentials') - } -}) - -it('falls back to any column for an identifier-only match, brackets or not', async () => { - harness = await openSessionSearchHarness('ss-snippet-marks-fallback') - addSyntheticSession(harness.db, { - id: 1, - text: 'numpy printed [[1, 2], [3, 4]] before the call', - toolText: 'zebra-fish-count = 4' - }) - - const [hit] = harness.engine.search({ query: 'zebra' }).hits - expect(hit?.evidence?.snippet).toContain( - `${SESSION_SEARCH_SNIPPET_MARK_OPEN}zebra${SESSION_SEARCH_SNIPPET_MARK_CLOSE}` - ) - expect(hit?.evidence?.snippet).not.toContain('numpy') -}) - -it('picks by comparison, so a private-use code point in content cannot pose as a mark', async () => { - harness = await openSessionSearchHarness('ss-snippet-marks-private-use') - addSyntheticSession(harness.db, { - id: 1, - text: 'the \uE000 glyph a font printed here', - toolText: TOOL - }) - - const [hit] = harness.engine.search({ query: 'zebrafish' }).hits - expect(hit?.evidence?.snippet).toContain('zebrafish') - expect(hit?.evidence?.snippet).not.toContain('glyph') -}) - -it('marks only what FTS5 marked, so a glyph in the text stays a glyph', async () => { - harness = await openSessionSearchHarness('ss-snippet-marks-literal-private-use') - addSyntheticSession(harness.db, { id: 1, text: 'a \uE000 glyph then zebrafish and \uE001 after' }) - - const snippet = harness.engine.search({ query: 'zebrafish' }).hits[0]?.evidence?.snippet ?? '' - expect(snippet).toContain( - `${SESSION_SEARCH_SNIPPET_MARK_OPEN}zebrafish${SESSION_SEARCH_SNIPPET_MARK_CLOSE}` - ) - expect(snippet).toContain('a \uE000 glyph') - expect(snippet).toContain('\uE001 after') - expect(snippet.split(SESSION_SEARCH_SNIPPET_MARK_OPEN)).toHaveLength(2) -}) - -it('does not cut a snippet at a private-use code point the transcript wrote', async () => { - harness = await openSessionSearchHarness('ss-snippet-marks-literal-truncation') - const long = (letter: string): string => - Array.from({ length: 5 }, () => `${letter.repeat(55)}/tail`).join(' ') - addSyntheticSession(harness.db, { id: 1, text: `zebrafish ${long('p')} \uE000 ${long('q')}` }) - - const snippet = harness.engine.search({ query: 'zebrafish' }).hits[0]?.evidence?.snippet ?? '' - expect(snippet).toContain( - `${SESSION_SEARCH_SNIPPET_MARK_OPEN}zebrafish${SESSION_SEARCH_SNIPPET_MARK_CLOSE}` - ) - expect(snippet).toContain('qqqqq') -}) - -it('marks a phrase hit as one run, stop words included', async () => { - harness = await openSessionSearchHarness('ss-snippet-phrase-run') - addSyntheticSession(harness.db, { - id: 1, - text: 'Agent: the code already has several fixes for blank restores, including replaying' - }) - - const result = harness.engine.search({ query: 'the code already has several fixes' }) - expect(result.planner.route).toBe('phrase') - expect(result.hits[0]?.evidence?.snippet).toContain( - `${SESSION_SEARCH_SNIPPET_MARK_OPEN}the code already has several fixes${SESSION_SEARCH_SNIPPET_MARK_CLOSE}` - ) -}) - -it('marks every typed word of an AND hit, stop words included', async () => { - harness = await openSessionSearchHarness('ss-snippet-and-words') - addSyntheticSession(harness.db, { id: 1, text: 'fixes for the restore path, several of them' }) - - const result = harness.engine.search({ query: 'several fixes for the restore' }) - expect(result.planner.route).toBe('and') - const snippet = result.hits[0]?.evidence?.snippet ?? '' - for (const word of ['several', 'fixes', 'for', 'the', 'restore']) { - expect(snippet).toContain( - `${SESSION_SEARCH_SNIPPET_MARK_OPEN}${word}${SESSION_SEARCH_SNIPPET_MARK_CLOSE}` - ) - } -}) diff --git a/src/main/ai-vault-search/session-search-sqlite-support.ts b/src/main/ai-vault-search/session-search-sqlite-support.ts deleted file mode 100644 index 76409b1de7a..00000000000 --- a/src/main/ai-vault-search/session-search-sqlite-support.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { isSqliteAvailable } from '../sqlite/sync-database' - -/** Older remote hosts may lack SQLite or backup(); leave search unregistered on those runtimes. */ -export function sessionSearchSqliteAvailable(): boolean { - return isSqliteAvailable() -} diff --git a/src/main/ai-vault-search/session-search-tool-purge.test.ts b/src/main/ai-vault-search/session-search-tool-purge.test.ts deleted file mode 100644 index 8402ae6fb71..00000000000 --- a/src/main/ai-vault-search/session-search-tool-purge.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { expect, it } from 'vitest' -import { addSyntheticSession, openSessionSearchHarness } from './session-search-engine-test-fixture' -import { readIndexContentRevision, readIndexGeneration } from './session-search-index-generation' -import { encodeSessionSearchCursor, sessionSearchPageKey } from './session-search-page-cursor' -import { SessionSearchToolPurge } from './session-search-tool-purge' - -it('purges legacy tool rows across batches while preserving conversations and raw generation fences', async () => { - const index = await openSessionSearchHarness('ss-tool-purge') - try { - addSyntheticSession(index.db, { id: 1, text: 'userkept' }) - addSyntheticSession(index.db, { id: 2, role: 'assistant', text: 'assistantkept' }) - addSyntheticSession(index.db, { id: 3, role: 'tool', text: 'toolremoved', rows: 600 }) - const before = readIndexGeneration(index.db) - expect(index.engine.search({ query: 'toolremoved' }).hits).toHaveLength(0) - let messages = 602 - const errors: unknown[] = [] - const purge = new SessionSearchToolPurge( - index.db, - () => false, - (delta) => { - messages += delta - }, - (error) => errors.push(error) - ) - await purge.request() - expect(errors).toEqual([]) - expect(index.engine.search({ query: 'toolremoved' }).hits).toEqual([]) - expect(index.engine.search({ query: 'userkept' }).hits[0]?.sessionId).toBe('1') - expect(index.engine.search({ query: 'assistantkept' }).hits[0]?.sessionId).toBe('2') - expect(messages).toBe(2) - expect(readIndexGeneration(index.db)).toBeGreaterThan(before) - addSyntheticSession(index.db, { id: 4, role: 'tool', text: 'newlegacytool' }) - await purge.request() - expect(index.engine.search({ query: 'newlegacytool' }).hits).toEqual([]) - } finally { - await index.close() - } -}) - -it.each(['relevance', 'newest'] as const)( - 'continues frozen %s ordering and fork folding throughout tool cleanup', - async (sort) => { - const index = await openSessionSearchHarness('ss-frozen-purge') - try { - for (let id = 1; id <= 7; id++) { - addSyntheticSession(index.db, { - id, - text: 'needle', - messageCount: id, - updatedAt: `2026-09-0${id}T00:00:00.000Z` - }) - } - index.db.exec( - "UPDATE sessions SET content_hash = 'shared', content_hash_count = 8 WHERE id IN (2,7)" - ) - addSyntheticSession(index.db, { - id: 20, - role: 'tool', - text: 'needle noisy words', - rows: 2500 - }) - // Orphan deletes fire generation triggers in addition to the purge's explicit bump. - index.db.exec('DELETE FROM sessions WHERE id = 20') - const before = readIndexContentRevision(index.db) - const request = { query: 'needle', limit: 1, filters: { sort } } - const first = index.engine.search(request) - const incarnation = String( - index.db.prepare("SELECT value FROM meta WHERE key = 'index_incarnation'").get()!.value - ) - const legacy = encodeSessionSearchCursor( - first.generation, - 1, - sessionSearchPageKey(request), - incarnation - ) - const seen = [...first.hits] - let cursor = first.page.cursor - const errors: unknown[] = [] - await new SessionSearchToolPurge( - index.db, - () => false, - () => { - if (cursor) { - const page = index.engine.search({ ...request, cursor }) - expect(page.generation).toBe(first.generation) - seen.push(...page.hits) - cursor = page.page.cursor - } - }, - (error) => errors.push(error) - ).request() - expect(errors).toEqual([]) - expect(cursor).toBeNull() - expect(seen.map((hit) => hit.sessionId)).toEqual( - sort === 'newest' ? ['7', '6', '5', '4', '3', '1'] : ['1', '3', '4', '5', '6', '7'] - ) - expect(seen.find((hit) => hit.sessionId === '7')?.duplicateCount).toBe(2) - expect(readIndexContentRevision(index.db)).toBe(before) - expect(readIndexGeneration(index.db)).toBeGreaterThan(first.generation) - expect(() => index.engine.search({ ...request, cursor: legacy })).toThrow('stale-generation') - } finally { - await index.close() - } - } -) - -type HarnessDb = Awaited>['db'] - -function readMeta(db: HarnessDb, key: string): string | undefined { - const row = db.prepare('SELECT value FROM meta WHERE key = ?').get(key) - return row ? String(row.value) : undefined -} - -function countTool(db: HarnessDb): number { - return Number(db.prepare("SELECT COUNT(*) AS n FROM messages WHERE role = 'tool'").get()!.n) -} - -function newPurge(db: HarnessDb, closed = () => false, onChange = (): void => {}) { - return new SessionSearchToolPurge(db, closed, onChange, (error) => { - throw error - }) -} - -it('purges legacy tool rows written after the mark, including reused tail rowids', async () => { - const index = await openSessionSearchHarness('ss-tool-purge-downgrade') - try { - addSyntheticSession(index.db, { id: 1, text: 'userkept', rows: 20 }) - const purge = newPurge(index.db) - await purge.request() - const mark = Number(readMeta(index.db, 'tool_purge_scanned_rowid')) - expect(mark).toBeGreaterThanOrEqual(20) - // A downgraded build deletes the tail, then reuses those rowids for tool rows. - index.db.exec('DELETE FROM messages WHERE id > 10') - index.db.exec('DELETE FROM messages_fts WHERE rowid > 10') - addSyntheticSession(index.db, { id: 3, role: 'tool', text: 'reusedtool', rows: 5 }) - const reused = index.db.prepare("SELECT MIN(id) AS id FROM messages WHERE role = 'tool'").get() - expect(Number(reused!.id)).toBeLessThanOrEqual(mark) - expect(Number(readMeta(index.db, 'tool_purge_floor_rowid'))).toBe(10) - addSyntheticSession(index.db, { id: 4, role: 'tool', text: 'latertool', rows: 400 }) - await purge.request() - expect(countTool(index.db)).toBe(0) - expect(index.engine.search({ query: 'reusedtool' }).hits).toEqual([]) - expect(index.engine.search({ query: 'userkept' }).hits[0]?.sessionId).toBe('1') - expect(readMeta(index.db, 'tool_purge_floor_rowid')).toBeUndefined() - expect(Number(readMeta(index.db, 'tool_purge_scanned_rowid'))).toBeGreaterThanOrEqual(415) - } finally { - await index.close() - } -}) - -it('keeps the claimed start when a pass is cancelled', async () => { - const index = await openSessionSearchHarness('ss-tool-purge-cancel') - try { - addSyntheticSession(index.db, { id: 1, role: 'tool', text: 'toolremoved', rows: 600 }) - let closed = false - let cancels = 1 - const purge = newPurge( - index.db, - () => closed, - () => { - closed = cancels-- > 0 - } - ) - await purge.request() - expect(countTool(index.db)).toBe(344) - expect(readMeta(index.db, 'tool_purge_scanned_rowid')).toBe('0') - closed = false - await purge.request() - expect(countTool(index.db)).toBe(0) - } finally { - await index.close() - } -}) diff --git a/src/main/ai-vault-search/session-search-worker.test.ts b/src/main/ai-vault-search/session-search-worker.test.ts deleted file mode 100644 index 139c28d3ce4..00000000000 --- a/src/main/ai-vault-search/session-search-worker.test.ts +++ /dev/null @@ -1,216 +0,0 @@ -import './session-search-worker.test-fixture' -import { mkdtemp, writeFile, rm, stat } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it } from 'vitest' -import { SessionSearchWorkerStore } from './session-search-worker-store' -import { SessionSearchReaders } from './session-search-readers' -import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' -import { syntheticCandidate } from './session-search-index-test-fixture' -import { readWholeTranscript } from '../ai-vault/transcripts/session-transcript-reader' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' -import { createHash } from 'node:crypto' -import SyncDatabase from '../sqlite/sync-database' - -let root: string | undefined -let store: SessionSearchWorkerStore | undefined -let readers: SessionSearchReaders | undefined - -afterEach(async () => { - resetTranscriptConsumersForTests() - store?.close() - await Promise.all([store?.retired(), readers?.close()]) - if (root) { - await rm(root, { recursive: true, force: true }) - } -}) - -// Real workers import the parser graph; allow cold module loading plus SQLite publication. -it( - 'indexes a non-JSONL pass larger than transfer credits without losing rows or original-message hashes', - async () => { - root = await mkdtemp(join(tmpdir(), 'ss-worker-flow-')) - const path = join(root, 'index.sqlite') - const file = join(root, 'conversation.json') - const text = 'observable payload '.repeat(7000) - await writeFile( - file, - JSON.stringify({ - id: 'worker-session', - working_dir: root, - messages: [ - ...Array.from({ length: 40 }, () => ({ role: 'user', content: text })), - { role: 'assistant', content: 'workerneedle reached the end' } - ] - }) - ) - const info = await stat(file) - const candidate = { - ...syntheticCandidate({ path: file, mtimeMs: info.mtimeMs, sizeBytes: info.size }), - agent: 'jcode' as const - } - store = new SessionSearchWorkerStore(path, (error) => { - throw error - }) - await store.prepare() - registerSessionSearchIndexConsumer(store) - const listed = await readWholeTranscript({ candidate, platform: process.platform }) - await store.flush() - expect(listed?.messageCount).toBe(41) - expect(store.stateCounts()).toMatchObject({ current: 0, due: 0, failed: 0, messages: 0 }) - expect(store.coversTranscript(candidate)).toBe(false) - await readWholeTranscript({ candidate, platform: process.platform, indexing: true }) - await store.flush() - readers = new SessionSearchReaders(path, null) - expect((await readers.query({ query: 'workerneedle' })).result).toMatchObject({ - kind: 'results', - hits: [{ sessionId: 'worker-session' }] - }) - expect(store.coversTranscript(candidate)).toBe(true) - expect(store.stateCounts().failed).toBe(0) - const db = new SyncDatabase(path, { readonly: true }) - try { - let digest = '' - for (let i = 0; i < 8; i++) { - digest = createHash('sha256').update(digest).update('\0user\0').update(text).digest('hex') - } - expect( - db.prepare('SELECT content_hash, content_hash_count FROM sessions').get() - ).toMatchObject({ content_hash: digest, content_hash_count: 8 }) - } finally { - db.close() - } - }, - // Why: these start real writer and reader worker threads (tsx-loaded) and stream multi-MiB transcripts. - 30_000 -) - -it('cancels a dead writer handle and lets a fresh pass recover without failing the transcript', async () => { - root = await mkdtemp(join(tmpdir(), 'ss-worker-recovery-')) - const path = join(root, 'index.sqlite') - class RestartableStore extends SessionSearchWorkerStore { - stopWriter(): void { - this.client.stop() - } - } - const subject = new RestartableStore(path, (error) => { - throw error - }) - store = subject - await subject.prepare() - const candidate = syntheticCandidate() - const interrupted = subject.beginWrite(candidate, 'replace', 0, undefined, true)! - interrupted.add({ role: 'user', text: 'interrupted payload', timestamp: null }) - subject.stopWriter() - await expect(interrupted.drain!()).rejects.toMatchObject({ name: 'AbortError' }) - expect(interrupted.cancelled?.()).toBe(true) - await subject.prepare() - expect(subject.stateCounts().failed).toBe(0) - const recovered = subject.beginWrite(candidate, 'replace', 0, undefined, true)! - recovered.add({ role: 'user', text: 'recoveredneedle', timestamp: null }) - const { syntheticSession } = await import('./session-search-index-test-fixture') - recovered.commit({ session: syntheticSession(), byteOffset: 4096, incomplete: false }) - await subject.flush() - readers = new SessionSearchReaders(path, null) - expect((await readers.query({ query: 'recoveredneedle' })).result).toMatchObject({ - kind: 'results', - hits: [{ sessionId: 'fixture' }] - }) - expect(subject.stateCounts().failed).toBe(0) -}) - -it( - 'drains a near-10-MiB JSONL record even when one synchronous emission exceeds transfer credits', - async () => { - root = await mkdtemp(join(tmpdir(), 'ss-worker-burst-')) - const path = join(root, 'index.sqlite') - const file = join(root, 'burst.jsonl') - const text = `largestburstneedle ${'x '.repeat(5 * 1024 * 1024 - 1024)}` - const { writeClaudeTranscript } = await import('./session-search-indexer-test-fixture') - await writeClaudeTranscript(file, [text], 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee') - const info = await stat(file) - const candidate = syntheticCandidate({ - path: file, - mtimeMs: info.mtimeMs, - sizeBytes: info.size - }) - store = new SessionSearchWorkerStore(path, (error) => { - throw error - }) - await store.prepare() - registerSessionSearchIndexConsumer(store) - const { readResumableTranscript } = - await import('../ai-vault/transcripts/session-transcript-reader') - const { createClaudeSessionResumeState } = - await import('../ai-vault/scanners/claude/session-scanner-primary-parsers') - await readResumableTranscript({ - candidate, - platform: process.platform, - resume: null, - indexing: true, - stateFactory: (channel) => createClaudeSessionResumeState(candidate.file, channel) - }) - await store.flush() - expect(store.coversTranscript(candidate)).toBe(true) - expect(store.stateCounts().failed).toBe(0) - readers = new SessionSearchReaders(path, null) - expect((await readers.query({ query: 'largestburstneedle' })).result).toMatchObject({ - kind: 'results', - hits: [{ sessionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' }] - }) - }, - // Why: these start real writer and reader worker threads (tsx-loaded) and stream multi-MiB transcripts. - 30_000 -) - -it('commits the original-message digest when a drained conversation ends with only tool rows', async () => { - root = await mkdtemp(join(tmpdir(), 'ss-worker-hash-tail-')) - const path = join(root, 'index.sqlite') - store = new SessionSearchWorkerStore(path, (error) => { - throw error - }) - await store.prepare() - const write = store.beginWrite(syntheticCandidate(), 'replace', 0, undefined, true)! - write.add({ role: 'user', text: 'prompt', timestamp: null }) - await write.drain!() - await store.flush() - write.add({ role: 'tool', text: 'tooltail', timestamp: null }) - const { syntheticSession } = await import('./session-search-index-test-fixture') - expect(write.commit({ session: syntheticSession(), byteOffset: 4096, incomplete: false })).toBe( - true - ) - await store.flush() - const db = new SyncDatabase(path, { readonly: true }) - try { - expect(db.prepare('SELECT content_hash, content_hash_count FROM sessions').get()).toEqual({ - content_hash: '20d617e013f1dbefe8ce6afe43ad44ec558ae2e087d44804ce2f789cc04538a8', - content_hash_count: 2 - }) - expect(db.prepare('SELECT count(*) AS n FROM messages').get()).toEqual({ n: 1 }) - } finally { - db.close() - } -}) - -it('opens a cold reader and searches committed rows while a writer batch remains uncommitted', async () => { - root = await mkdtemp(join(tmpdir(), 'ss-reader-independent-')) - const path = join(root, 'index.sqlite') - const { SessionSearchStore } = await import('./session-search-store') - const { addSyntheticSession } = await import('./session-search-engine-test-fixture') - const writer = new SessionSearchStore(path) - try { - addSyntheticSession(writer.connection, { id: 1, text: 'independentneedle' }) - writer.connection.exec('BEGIN IMMEDIATE') - writer.connection.prepare("UPDATE sessions SET title = 'uncommitted' WHERE id = 1").run() - readers = new SessionSearchReaders(path, null) - expect((await readers.query({ query: 'independentneedle' })).result).toMatchObject({ - kind: 'results', - hits: [{ sessionId: '1', title: 'fixture' }] - }) - } finally { - if (writer.connection.isTransaction) { - writer.connection.exec('ROLLBACK') - } - writer.close() - } -}) diff --git a/src/main/ai-vault-search/session-search-write-buffer.test.ts b/src/main/ai-vault-search/session-search-write-buffer.test.ts deleted file mode 100644 index ce3128c0a4f..00000000000 --- a/src/main/ai-vault-search/session-search-write-buffer.test.ts +++ /dev/null @@ -1,148 +0,0 @@ -import { expect, it, vi } from 'vitest' -import SyncDatabase from '../sqlite/sync-database' -import { SessionSearchWriteBuffer, SessionSearchStagingBudget } from './session-search-write-buffer' -import { SessionSearchIndexWriter } from './session-search-index-writer' -import { - openSessionSearchIndexFile, - syntheticCandidate, - syntheticSession -} from './session-search-index-test-fixture' - -it('keeps text, timestamps, truncation, and order across spills and closes its temporary database', () => { - const close = vi.spyOn(SyncDatabase.prototype, 'close') - const buffer = new SessionSearchWriteBuffer(1) - const rows = [ - { - role: 'user' as const, - text: '😀\u0000\nfirst', - timestamp: '2026-10-19T00:00:00.000Z', - textTruncated: true as const - }, - { role: 'tool' as const, text: '工具\r\nsecond', timestamp: null }, - { role: 'assistant' as const, text: 'last', timestamp: null } - ] - try { - buffer.add(rows[0]) - buffer.spill() - buffer.add(rows[1]) - buffer.spill() - buffer.add(rows[2]) - expect([...buffer.rows()]).toEqual(rows) - buffer.clear() - buffer.clear() - expect(close).toHaveBeenCalledTimes(1) - expect([...buffer.rows()]).toEqual([]) - expect(buffer.hasSpilled).toBe(false) - } finally { - buffer.clear() - close.mockRestore() - } -}) - -it.each([1, 1_000_000])( - 'persists truncation through search writes with a %i-character buffer', - async (commitChars) => { - const index = await openSessionSearchIndexFile('ss-truncation-staging') - const writer = new SessionSearchIndexWriter(index.db, commitChars) - const write = writer.beginWrite(syntheticCandidate(), 'replace', 0) - if (!write) { - throw new Error('Expected write') - } - try { - write.add({ - role: 'user', - text: 'reader prefix '.repeat(1000), - timestamp: null, - textTruncated: true - }) - write.add({ role: 'assistant', text: 'complete reply', timestamp: null }) - write.add({ role: 'tool', text: 'output '.repeat(1000), timestamp: null }) - expect( - write.commit({ session: syntheticSession(), byteOffset: 100, incomplete: false }) - ).toBe(true) - expect( - index.db.prepare('SELECT role, text_truncated FROM messages ORDER BY id').all() - ).toEqual([ - { role: 'user', text_truncated: 1 }, - { role: 'user', text_truncated: 1 }, - { role: 'assistant', text_truncated: 0 } - ]) - } finally { - write.discard() - writer.close() - await index.close() - } - } -) - -it.each(['discard', 'close', 'removed', 'rollback'] as const)( - 'releases anonymous staging on %s without publishing rows', - async (end) => { - const index = await openSessionSearchIndexFile('ss-staging-lifetime') - const writer = new SessionSearchIndexWriter(index.db, 1) - const close = vi.spyOn(SyncDatabase.prototype, 'close') - const write = writer.beginWrite(syntheticCandidate(), 'replace', 0) - if (!write) { - throw new Error('Expected write') - } - try { - write.add({ role: 'user', text: 'private message', timestamp: null }) - if (end === 'discard') { - write.discard() - } - if (end === 'close') { - writer.close() - } - if (end === 'removed') { - writer.removeFile(syntheticCandidate().file.path) - expect( - write.commit({ session: syntheticSession(), byteOffset: 10, incomplete: false }) - ).toBe(false) - } - if (end === 'rollback') { - index.db.exec( - `CREATE TRIGGER reject_message BEFORE INSERT ON messages BEGIN SELECT RAISE(ABORT, 'test write failure'); END` - ) - expect(() => - write.commit({ session: syntheticSession(), byteOffset: 10, incomplete: false }) - ).toThrow('test write failure') - } - expect(close).toHaveBeenCalledTimes(1) - expect(index.db.prepare('SELECT count(*) AS n FROM sessions').get()?.n).toBe(0) - expect(index.db.prepare('SELECT count(*) AS n FROM messages').get()?.n).toBe(0) - } finally { - write.discard() - writer.close() - close.mockRestore() - await index.close() - } - } -) - -it('shares resident staging across handles without changing publication readiness or row order', () => { - const budget = new SessionSearchStagingBudget() - const buffers = Array.from( - { length: 4 }, - () => new SessionSearchWriteBuffer(32 * 1024 * 1024, budget) - ) - const text = '界'.repeat(8000) - try { - for (const buffer of buffers) { - for (let row = 0; row < 200; row++) { - buffer.add({ role: 'user', text: `${row}:${text}`, timestamp: null }) - } - } - expect(budget.bytes).toBeLessThanOrEqual(8 * 1024 * 1024) - for (const buffer of buffers) { - expect(buffer.ready).toBe(false) - expect([...buffer.rows()].map((row) => row.text)).toEqual( - Array.from({ length: 200 }, (_, row) => `${row}:${text}`) - ) - } - } finally { - for (const buffer of buffers) { - buffer.release() - } - } - expect(budget.bytes).toBe(0) -}) diff --git a/src/main/ai-vault-search/session-search-content-hash.ts b/src/main/ai-vault-search/storage/session-search-content-hash.ts similarity index 92% rename from src/main/ai-vault-search/session-search-content-hash.ts rename to src/main/ai-vault-search/storage/session-search-content-hash.ts index 286d90bf751..539345ff4a1 100644 --- a/src/main/ai-vault-search/session-search-content-hash.ts +++ b/src/main/ai-vault-search/storage/session-search-content-hash.ts @@ -1,5 +1,5 @@ import { createHash } from 'node:crypto' -import type { TranscriptMessage } from '../ai-vault/transcripts/session-transcript-consumers' +import type { TranscriptMessage } from '../../ai-vault/transcripts/session-transcript-consumers' // Forked transcripts share an opening prefix even after their tails diverge. const CONTENT_HASH_MESSAGE_LIMIT = 8 diff --git a/src/main/ai-vault-search/session-search-file-cursor.ts b/src/main/ai-vault-search/storage/session-search-file-cursor.ts similarity index 91% rename from src/main/ai-vault-search/session-search-file-cursor.ts rename to src/main/ai-vault-search/storage/session-search-file-cursor.ts index 57a8561cb09..9463c34e31b 100644 --- a/src/main/ai-vault-search/session-search-file-cursor.ts +++ b/src/main/ai-vault-search/storage/session-search-file-cursor.ts @@ -1,4 +1,4 @@ -import type { FileWithMtime } from '../ai-vault/session-scanner-types' +import type { FileWithMtime } from '../../ai-vault/session-scanner-types' // Index and parse-cache cursors can diverge when either declines a read; track them independently. diff --git a/src/main/ai-vault-search/session-search-file-records.ts b/src/main/ai-vault-search/storage/session-search-file-records.ts similarity index 90% rename from src/main/ai-vault-search/session-search-file-records.ts rename to src/main/ai-vault-search/storage/session-search-file-records.ts index 785173bdca8..ef8b3f115a7 100644 --- a/src/main/ai-vault-search/session-search-file-records.ts +++ b/src/main/ai-vault-search/storage/session-search-file-records.ts @@ -1,10 +1,10 @@ import { fileIdentity } from './session-search-file-cursor' -import type { AiVaultSession } from '../../shared/ai-vault/contracts/ai-vault-types' -import type { TranscriptSessionIdentity } from '../ai-vault/transcripts/session-transcript-consumers' -import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' -import type SyncDatabase from '../sqlite/sync-database' +import type { AiVaultSession } from '../../../shared/ai-vault/contracts/ai-vault-types' +import type { TranscriptSessionIdentity } from '../../ai-vault/transcripts/session-transcript-consumers' +import type { SessionFileCandidate } from '../../ai-vault/session-scanner-types' +import type SyncDatabase from '../../sqlite/sync-database' import { EMPTY_CONTENT_HASH, type SessionContentHash } from './session-search-content-hash' -import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' +import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' /** Use the sidebar’s path normalization so indexed cwd keys join its folder groups. */ export function cwdKey(cwd: string | null): string | null { diff --git a/src/main/ai-vault-search/storage/session-search-file-write.test.ts b/src/main/ai-vault-search/storage/session-search-file-write.test.ts new file mode 100644 index 00000000000..7b94f93c9ac --- /dev/null +++ b/src/main/ai-vault-search/storage/session-search-file-write.test.ts @@ -0,0 +1,102 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { resetTranscriptConsumersForTests } from '../../ai-vault/transcripts/session-transcript-consumers' +import '../../sqlite/sync-database' +import type SyncDatabase from '../../sqlite/sync-database' +import { registerSessionSearchIndexConsumer } from '../indexing/session-search-index-consumer' +import './session-search-file-cursor' +import './session-search-index-writer' +import './session-search-retention-delete' +import { + openSessionSearchIndexFile, + replayTranscriptRead, + syntheticCandidate, + syntheticSession, + userMessages, + type SessionSearchIndexFile +} from './session-search-index-test-fixture' +import { SessionSearchStore } from './session-search-store' + +// Read through a second connection to verify only committed transactions become visible. + +let index: SessionSearchIndexFile +let store: SessionSearchStore +let errors: unknown[] + +beforeEach(async () => { + index = await openSessionSearchIndexFile('ss-file-write') + errors = [] + store = new SessionSearchStore(index.path, (error) => errors.push(error)) + registerSessionSearchIndexConsumer(store) +}) + +afterEach(async () => { + vi.restoreAllMocks() + resetTranscriptConsumersForTests() + store.close() + await index.close() +}) + +function matches(db: SyncDatabase, table: string, term: string): number { + return ( + db + .prepare( + `SELECT count(*) AS n FROM ${table} JOIN messages m ON m.id = ${table}.rowid + JOIN sessions s ON s.id = m.session_row_id WHERE ${table} MATCH ?` + ) + .get(term) as { n: number } + ).n +} + +function counts(db: SyncDatabase): Record { + const one = (sql: string): number => (db.prepare(sql).get() as { n: number }).n + return { + sessions: one('SELECT count(*) AS n FROM sessions'), + messages: one('SELECT count(*) AS n FROM messages'), + files: one('SELECT count(*) AS n FROM files'), + full: one('SELECT count(*) AS n FROM messages_fts') + } +} + +it('shows a reader on another handle one generation or the other, never a mixture', async () => { + replayTranscriptRead({ + messages: userMessages('firstgeneration', 3), + outcome: { byteOffset: 40 } + }) + expect(counts(index.db).messages).toBe(3) + + const write = store.beginWrite(syntheticCandidate(), 'replace', 0)! + for (const message of userMessages('secondgeneration', 7)) { + write.add(message) + expect(counts(index.db).messages).toBe(3) + expect(matches(index.db, 'messages_fts', 'secondgeneration')).toBe(0) + } + expect( + write.commit({ + session: syntheticSession(), + byteOffset: 900, + incomplete: false + }) + ).toBe(true) + + expect(matches(index.db, 'messages_fts', 'firstgeneration')).toBe(0) + expect(matches(index.db, 'messages_fts', 'secondgeneration')).toBe(7) + // Replaced messages become unreachable at commit and are reclaimed asynchronously. + expect(counts(index.db).messages).toBe(10) + await vi.waitFor(() => { + expect(counts(index.db).messages).toBe(7) + }) +}) + +it('fences a first-ever read whose file was removed before it committed', () => { + const candidate = syntheticCandidate({ path: '/never-indexed.jsonl' }) + const write = store.beginWrite(candidate, 'replace', 0)! + for (const message of userMessages('removedbeforefirstcommit', 3)) { + write.add(message) + } + store.removeFile('/never-indexed.jsonl') + + expect(write.commit({ session: syntheticSession(), byteOffset: 300, incomplete: false })).toBe( + false + ) + expect(counts(index.db)).toMatchObject({ sessions: 0, messages: 0, files: 0, full: 0 }) +}) diff --git a/src/main/ai-vault-search/session-search-identifier-split.ts b/src/main/ai-vault-search/storage/session-search-identifier-split.ts similarity index 100% rename from src/main/ai-vault-search/session-search-identifier-split.ts rename to src/main/ai-vault-search/storage/session-search-identifier-split.ts diff --git a/src/main/ai-vault-search/session-search-index-generation.test.ts b/src/main/ai-vault-search/storage/session-search-index-generation.test.ts similarity index 50% rename from src/main/ai-vault-search/session-search-index-generation.test.ts rename to src/main/ai-vault-search/storage/session-search-index-generation.test.ts index d23f82cc416..298866f6c1f 100644 --- a/src/main/ai-vault-search/session-search-index-generation.test.ts +++ b/src/main/ai-vault-search/storage/session-search-index-generation.test.ts @@ -2,17 +2,17 @@ import { mkdtemp, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' -import { removeTree } from '../../shared/windows-transient-lock-removal' -import type SyncDatabase from '../sqlite/sync-database' -import { SessionSearchEngine } from './session-search-engine' -import { readIndexGeneration } from './session-search-index-generation' -import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' -import { resetSessionParseCacheForTests } from '../ai-vault/parse-cache/session-parse-cache-store' -import { resetTranscriptConsumersForTests } from '../ai-vault/transcripts/session-transcript-consumers' -import type { SessionSearchCursorError } from './session-search-page-cursor' +import { removeTree } from '../../../shared/windows-transient-lock-removal' +import type SyncDatabase from '../../sqlite/sync-database' +import { SessionSearchEngine } from '../query/session-search-engine' +import './session-search-index-generation' +import { registerSessionSearchIndexConsumer } from '../indexing/session-search-index-consumer' +import { resetSessionParseCacheForTests } from '../../ai-vault/parse-cache/session-parse-cache-store' +import { resetTranscriptConsumersForTests } from '../../ai-vault/transcripts/session-transcript-consumers' +import type { SessionSearchCursorError } from '../query/session-search-page-cursor' import { openSessionSearchDatabase } from './session-search-schema' import { SessionSearchStore } from './session-search-store' -import { parseTranscript, userRecord } from './session-search-transcript-fixtures' +import { parseTranscript, userRecord } from '../indexing/session-search-transcript-fixtures' let roots: string[] = [] let handles: SyncDatabase[] = [] @@ -56,27 +56,6 @@ async function indexOneTranscript(root: string, store: SessionSearchStore): Prom return path } -it('moves the generation when a purge reclaims rows nothing can reach', async () => { - // Orphan deletion changes typo vocabulary even though retrieval already excludes those messages. - const root = await tempRoot() - const path = join(root, 'index.sqlite') - const db = reader(path) - const store = new SessionSearchStore(path, (error) => { - throw error - }) - try { - await indexOneTranscript(root, store) - db.prepare('DELETE FROM sessions').run() - const orphaned = readIndexGeneration(db) - expect(db.prepare('SELECT COUNT(*) AS c FROM messages').get()).not.toEqual({ c: 0 }) - await store.purgeOlderThan(null) - expect(db.prepare('SELECT COUNT(*) AS c FROM messages').get()).toEqual({ c: 0 }) - expect(readIndexGeneration(db)).toBeGreaterThan(orphaned) - } finally { - store.close() - } -}) - it('fences a reader against another database handle moving the index', async () => { // A process-local generation would miss another process’s writes and admit stale cursors. const root = await tempRoot() @@ -106,31 +85,3 @@ it('fences a reader against another database handle moving the index', async () writer.close() } }) - -it('re-creates a fence something dropped, on the next search', async () => { - const root = await tempRoot() - const path = join(root, 'index.sqlite') - const db = reader(path) - const store = new SessionSearchStore(path, (error) => { - throw error - }) - try { - const transcript = await indexOneTranscript(root, store) - const engine = new SessionSearchEngine(db) - db.exec('DROP TRIGGER search_generation_file_update') - engine.search({ query: 'needle' }) - - expect( - db - .prepare("SELECT name FROM sqlite_master WHERE type = 'trigger' AND name = ?") - .get('search_generation_file_update') - ).toEqual({ name: 'search_generation_file_update' }) - - // Update only the restored trigger’s table so other trigger types cannot mask a missing repair. - const restored = readIndexGeneration(db) - db.exec(`UPDATE files SET mtime_ms = mtime_ms + 1 WHERE path = '${transcript}'`) - expect(readIndexGeneration(db)).toBeGreaterThan(restored) - } finally { - store.close() - } -}) diff --git a/src/main/ai-vault-search/session-search-index-generation.ts b/src/main/ai-vault-search/storage/session-search-index-generation.ts similarity index 97% rename from src/main/ai-vault-search/session-search-index-generation.ts rename to src/main/ai-vault-search/storage/session-search-index-generation.ts index ce08c96b903..5cd4c8e56fe 100644 --- a/src/main/ai-vault-search/session-search-index-generation.ts +++ b/src/main/ai-vault-search/storage/session-search-index-generation.ts @@ -1,4 +1,4 @@ -import type SyncDatabase from '../sqlite/sync-database' +import type SyncDatabase from '../../sqlite/sync-database' const GENERATION_KEY = 'index_generation' const INCARNATION_KEY = 'index_incarnation' diff --git a/src/main/ai-vault-search/session-search-index-test-fixture.ts b/src/main/ai-vault-search/storage/session-search-index-test-fixture.ts similarity index 86% rename from src/main/ai-vault-search/session-search-index-test-fixture.ts rename to src/main/ai-vault-search/storage/session-search-index-test-fixture.ts index 37401effbe0..028556d617c 100644 --- a/src/main/ai-vault-search/session-search-index-test-fixture.ts +++ b/src/main/ai-vault-search/storage/session-search-index-test-fixture.ts @@ -1,16 +1,16 @@ import { mkdtemp } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { removeTree } from '../../shared/windows-transient-lock-removal' -import type { AiVaultSession } from '../../shared/ai-vault/contracts/ai-vault-types' -import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' -import { TranscriptMessageChannel } from '../ai-vault/transcripts/session-transcript-channel' +import { removeTree } from '../../../shared/windows-transient-lock-removal' +import type { AiVaultSession } from '../../../shared/ai-vault/contracts/ai-vault-types' +import type { SessionFileCandidate } from '../../ai-vault/session-scanner-types' +import { TranscriptMessageChannel } from '../../ai-vault/transcripts/session-transcript-channel' import type { TranscriptMessage, TranscriptReadOutcome, TranscriptReadStart -} from '../ai-vault/transcripts/session-transcript-consumers' -import type SyncDatabase from '../sqlite/sync-database' +} from '../../ai-vault/transcripts/session-transcript-consumers' +import type SyncDatabase from '../../sqlite/sync-database' import { openSessionSearchDatabase } from './session-search-schema' export const SYNTHETIC_TRANSCRIPT = 'synthetic-transcript' diff --git a/src/main/ai-vault-search/session-search-index-writer.test.ts b/src/main/ai-vault-search/storage/session-search-index-writer.test.ts similarity index 83% rename from src/main/ai-vault-search/session-search-index-writer.test.ts rename to src/main/ai-vault-search/storage/session-search-index-writer.test.ts index bac55ac7f3c..ae45dd2d591 100644 --- a/src/main/ai-vault-search/session-search-index-writer.test.ts +++ b/src/main/ai-vault-search/storage/session-search-index-writer.test.ts @@ -127,30 +127,3 @@ it('treats half a recorded identity as no identity at all', () => { expect(store.indexedFile(SYNTHETIC_TRANSCRIPT, { dev: 8, ino: 99 })?.byteOffset).toBe(100) expect(store.beginWrite(syntheticCandidate({ dev: 8, ino: 99 }), 'append', 100)).not.toBeNull() }) - -it.each([ - [null, { dev: null, ino: null }], - [ - { dev: 7, ino: 11 }, - { dev: 7, ino: 11 } - ] -])('never combines partial stats with the previous identity %j', (initial, expected) => { - const observations = [initial ?? {}, { dev: 9 }, { ino: 13 }, { dev: 17, ino: 19 }] - for (const [position, identity] of observations.entries()) { - const write = store.beginWrite( - syntheticCandidate(identity), - position ? 'append' : 'replace', - position * 100 - )! - expect( - write.commit({ - session: syntheticSession(), - byteOffset: (position + 1) * 100, - incomplete: false - }) - ).toBe(true) - expect(index.db.prepare('SELECT dev, ino FROM files').get()).toEqual( - position === 3 ? { dev: 17, ino: 19 } : expected - ) - } -}) diff --git a/src/main/ai-vault-search/session-search-index-writer.ts b/src/main/ai-vault-search/storage/session-search-index-writer.ts similarity index 97% rename from src/main/ai-vault-search/session-search-index-writer.ts rename to src/main/ai-vault-search/storage/session-search-index-writer.ts index 228e57af9ba..a5610ce0506 100644 --- a/src/main/ai-vault-search/session-search-index-writer.ts +++ b/src/main/ai-vault-search/storage/session-search-index-writer.ts @@ -1,11 +1,11 @@ -import { traceSessionSearch } from './session-search-trace' -import type SyncDatabase from '../sqlite/sync-database' -import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' +import { traceSessionSearch } from '../session-search-trace' +import type SyncDatabase from '../../sqlite/sync-database' +import type { SessionFileCandidate } from '../../ai-vault/session-scanner-types' import type { TranscriptMessage, TranscriptReadOutcome, TranscriptSessionIdentity -} from '../ai-vault/transcripts/session-transcript-consumers' +} from '../../ai-vault/transcripts/session-transcript-consumers' import { SessionSearchWriteBuffer, SessionSearchStagingBudget } from './session-search-write-buffer' import { EMPTY_CONTENT_HASH, diff --git a/src/main/ai-vault-search/storage/session-search-message-rows.test.ts b/src/main/ai-vault-search/storage/session-search-message-rows.test.ts new file mode 100644 index 00000000000..52e3bd1bfb5 --- /dev/null +++ b/src/main/ai-vault-search/storage/session-search-message-rows.test.ts @@ -0,0 +1,11 @@ +import { expect, it } from 'vitest' + +import { searchMessageRows } from './session-search-message-rows' +import './session-search-index-test-fixture' + +it('drops tool output and preserves the full conversation', () => { + const output = `pericardium ${'padding '.repeat(140_000)}` + expect([...searchMessageRows([{ role: 'tool', text: output, timestamp: null }])]).toEqual([]) + const rows = [...searchMessageRows([{ role: 'assistant', text: output, timestamp: null }])] + expect(rows.map((row) => row.text).join('')).toBe(output) +}) diff --git a/src/main/ai-vault-search/session-search-message-rows.ts b/src/main/ai-vault-search/storage/session-search-message-rows.ts similarity index 95% rename from src/main/ai-vault-search/session-search-message-rows.ts rename to src/main/ai-vault-search/storage/session-search-message-rows.ts index 43265fe4a15..4b15ce39d81 100644 --- a/src/main/ai-vault-search/session-search-message-rows.ts +++ b/src/main/ai-vault-search/storage/session-search-message-rows.ts @@ -1,5 +1,5 @@ -import type SyncDatabase from '../sqlite/sync-database' -import type { TranscriptMessage } from '../ai-vault/transcripts/session-transcript-consumers' +import type SyncDatabase from '../../sqlite/sync-database' +import type { TranscriptMessage } from '../../ai-vault/transcripts/session-transcript-consumers' import { identifierShadowText } from './session-search-identifier-split' const CHUNK_TARGET_CHARS = 8000 diff --git a/src/main/ai-vault-search/session-search-query-schema.ts b/src/main/ai-vault-search/storage/session-search-query-schema.ts similarity index 96% rename from src/main/ai-vault-search/session-search-query-schema.ts rename to src/main/ai-vault-search/storage/session-search-query-schema.ts index 450409de94d..abe2811cf08 100644 --- a/src/main/ai-vault-search/session-search-query-schema.ts +++ b/src/main/ai-vault-search/storage/session-search-query-schema.ts @@ -1,4 +1,4 @@ -import type SyncDatabase from '../sqlite/sync-database' +import type SyncDatabase from '../../sqlite/sync-database' import { SESSION_SEARCH_GENERATION_SQL, SESSION_SEARCH_GENERATION_TRIGGERS diff --git a/src/main/ai-vault-search/session-search-retention-delete.test.ts b/src/main/ai-vault-search/storage/session-search-retention-delete.test.ts similarity index 97% rename from src/main/ai-vault-search/session-search-retention-delete.test.ts rename to src/main/ai-vault-search/storage/session-search-retention-delete.test.ts index fada0f64bf3..5b9e0515ecd 100644 --- a/src/main/ai-vault-search/session-search-retention-delete.test.ts +++ b/src/main/ai-vault-search/storage/session-search-retention-delete.test.ts @@ -1,9 +1,12 @@ import { expect, it, vi } from 'vitest' -import type SyncDatabase from '../sqlite/sync-database' +import type SyncDatabase from '../../sqlite/sync-database' import { deleteExpiredSearchFiles, drainOrphanedMessages } from './session-search-retention-delete' import { openSessionSearchIndexFile } from './session-search-index-test-fixture' import { SessionSearchStore } from './session-search-store' -import { addSyntheticSession, openSessionSearchHarness } from './session-search-engine-test-fixture' +import { + addSyntheticSession, + openSessionSearchHarness +} from '../query/session-search-engine-test-fixture' import { readIndexContentRevision, readIndexGeneration } from './session-search-index-generation' function seed(db: SyncDatabase, id: number, rows: number, mtime: number): void { diff --git a/src/main/ai-vault-search/session-search-retention-delete.ts b/src/main/ai-vault-search/storage/session-search-retention-delete.ts similarity index 96% rename from src/main/ai-vault-search/session-search-retention-delete.ts rename to src/main/ai-vault-search/storage/session-search-retention-delete.ts index 1257b33c670..5b220eccf3b 100644 --- a/src/main/ai-vault-search/session-search-retention-delete.ts +++ b/src/main/ai-vault-search/storage/session-search-retention-delete.ts @@ -1,6 +1,6 @@ -import { traceSessionSearch } from './session-search-trace' +import { traceSessionSearch } from '../session-search-trace' import { setImmediate as yieldToEventLoop } from 'node:timers/promises' -import type SyncDatabase from '../sqlite/sync-database' +import type SyncDatabase from '../../sqlite/sync-database' import { deleteSearchMessages } from './session-search-message-rows' import { readIndexGeneration, recordIndexMaintenance } from './session-search-index-generation' diff --git a/src/main/ai-vault-search/session-search-row-identity.test.ts b/src/main/ai-vault-search/storage/session-search-row-identity.test.ts similarity index 98% rename from src/main/ai-vault-search/session-search-row-identity.test.ts rename to src/main/ai-vault-search/storage/session-search-row-identity.test.ts index 1a1efe96010..aba7f10760d 100644 --- a/src/main/ai-vault-search/session-search-row-identity.test.ts +++ b/src/main/ai-vault-search/storage/session-search-row-identity.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, it } from 'vitest' -import type SyncDatabase from '../sqlite/sync-database' +import type SyncDatabase from '../../sqlite/sync-database' import { deleteExpiredSearchFiles } from './session-search-retention-delete' import { openSessionSearchIndexFile, diff --git a/src/main/ai-vault-search/storage/session-search-schema.test.ts b/src/main/ai-vault-search/storage/session-search-schema.test.ts new file mode 100644 index 00000000000..333e3eb79bc --- /dev/null +++ b/src/main/ai-vault-search/storage/session-search-schema.test.ts @@ -0,0 +1,64 @@ +import type * as NodeFs from 'node:fs' +import { mkdtemp, stat, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import 'node:worker_threads' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { removeTree } from '../../../shared/windows-transient-lock-removal' +import '../../ai-vault/session-scanner-record-value' +import '../../sqlite/sync-database' +import { openSessionSearchDatabase } from './session-search-schema' +import { removeVersionedCacheDatabase } from '../../sqlite/versioned-cache-database' + +const recordedRmSync = vi.hoisted(() => vi.fn()) +vi.mock('node:fs', async () => { + const actual = await vi.importActual('node:fs') + return { + ...actual, + rmSync: (...args: Parameters) => { + recordedRmSync(...args) + return actual.rmSync(...args) + } + } +}) + +let roots: string[] = [] + +afterEach(async () => { + await Promise.all(roots.map((root) => removeTree(root))) + roots = [] +}) + +async function tempDatabasePath(): Promise { + const root = await mkdtemp(join(tmpdir(), 'orca-session-search-schema-')) + roots.push(root) + return join(root, 'index.sqlite') +} + +describe('openSessionSearchDatabase', () => { + it('keeps a version 8 index that predates prefix hashes and adds the column', async () => { + const path = await tempDatabasePath() + const first = openSessionSearchDatabase(path) + first.exec('ALTER TABLE files DROP COLUMN prefix_hash') + first.prepare("INSERT INTO files(path,byte_offset,mtime_ms) VALUES ('a',1,1)").run() + first.close() + + const second = openSessionSearchDatabase(path) + expect(second.prepare('SELECT path, prefix_hash FROM files').all()).toEqual([ + { path: 'a', prefix_hash: null } + ]) + second.close() + }) + + it('removes the database with every sidecar', async () => { + const path = await tempDatabasePath() + openSessionSearchDatabase(path).close() + await writeFile(`${path}-shm`, '') + removeVersionedCacheDatabase(path) + for (const suffix of ['', '-wal', '-shm']) { + await expect(stat(`${path}${suffix}`)).rejects.toMatchObject({ + code: 'ENOENT' + }) + } + }) +}) diff --git a/src/main/ai-vault-search/session-search-schema.ts b/src/main/ai-vault-search/storage/session-search-schema.ts similarity index 91% rename from src/main/ai-vault-search/session-search-schema.ts rename to src/main/ai-vault-search/storage/session-search-schema.ts index 9c5e46ea64e..adddb55eb8b 100644 --- a/src/main/ai-vault-search/session-search-schema.ts +++ b/src/main/ai-vault-search/storage/session-search-schema.ts @@ -1,11 +1,8 @@ -import { removeTree } from '../../shared/windows-transient-lock-removal' +import { removeTree } from '../../../shared/windows-transient-lock-removal' import { randomUUID } from 'node:crypto' -import type SyncDatabase from '../sqlite/sync-database' -import { - openVersionedCacheDatabase, - removeVersionedCacheDatabase -} from '../sqlite/versioned-cache-database' -import { asRecord } from '../ai-vault/session-scanner-record-value' +import type SyncDatabase from '../../sqlite/sync-database' +import { openVersionedCacheDatabase } from '../../sqlite/versioned-cache-database' +import { asRecord } from '../../ai-vault/session-scanner-record-value' // Cache transcript content verbatim; outbound snippet policy belongs at the transport boundary. @@ -117,10 +114,6 @@ export function addSessionSearchPrefixHashColumn(db: SyncDatabase): void { } } -export function removeSessionSearchDatabase(path: string): void { - removeVersionedCacheDatabase(path) -} - /** Async lock retries keep scanner/server deadlines responsive after all workers have retired. */ export async function removeSessionSearchDatabaseAsync(path: string): Promise { if (path === ':memory:') { diff --git a/src/main/ai-vault-search/session-search-store-types.ts b/src/main/ai-vault-search/storage/session-search-store-types.ts similarity index 100% rename from src/main/ai-vault-search/session-search-store-types.ts rename to src/main/ai-vault-search/storage/session-search-store-types.ts diff --git a/src/main/ai-vault-search/session-search-store.ts b/src/main/ai-vault-search/storage/session-search-store.ts similarity index 94% rename from src/main/ai-vault-search/session-search-store.ts rename to src/main/ai-vault-search/storage/session-search-store.ts index 07b99bd622d..16b8b5d6ce8 100644 --- a/src/main/ai-vault-search/session-search-store.ts +++ b/src/main/ai-vault-search/storage/session-search-store.ts @@ -5,17 +5,10 @@ import type { SessionSearchResumableCursor, SessionSearchStateCounts } from './session-search-store-types' -export type { - SessionSearchFileRow, - SessionSearchFileState, - SessionSearchResumableCursor, - SessionSearchStateCounts, - SessionSearchIndexStore -} from './session-search-store-types' -import type SyncDatabase from '../sqlite/sync-database' -import { asRecord } from '../ai-vault/session-scanner-record-value' -import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' -import type { TranscriptSessionIdentity } from '../ai-vault/transcripts/session-transcript-consumers' +import type SyncDatabase from '../../sqlite/sync-database' +import { asRecord } from '../../ai-vault/session-scanner-record-value' +import type { SessionFileCandidate } from '../../ai-vault/session-scanner-types' +import type { TranscriptSessionIdentity } from '../../ai-vault/transcripts/session-transcript-consumers' import { fileIdentity, type SessionSearchFileIdentity, @@ -27,7 +20,7 @@ import { type SessionSearchFileWrite } from './session-search-index-writer' import { deleteExpiredSearchFiles, drainOrphanedMessages } from './session-search-retention-delete' -import { reportSessionSearchBackgroundError } from './session-search-trace' +import { reportSessionSearchBackgroundError } from '../session-search-trace' import { openSessionSearchDatabase } from './session-search-schema' export class SessionSearchStore { diff --git a/src/main/ai-vault-search/storage/session-search-tool-purge.test.ts b/src/main/ai-vault-search/storage/session-search-tool-purge.test.ts new file mode 100644 index 00000000000..d81c77eabbd --- /dev/null +++ b/src/main/ai-vault-search/storage/session-search-tool-purge.test.ts @@ -0,0 +1,41 @@ +import { expect, it } from 'vitest' +import { + addSyntheticSession, + openSessionSearchHarness +} from '../query/session-search-engine-test-fixture' +import { readIndexGeneration } from './session-search-index-generation' +import '../query/session-search-page-cursor' +import { SessionSearchToolPurge } from './session-search-tool-purge' + +it('purges legacy tool rows across batches while preserving conversations and raw generation fences', async () => { + const index = await openSessionSearchHarness('ss-tool-purge') + try { + addSyntheticSession(index.db, { id: 1, text: 'userkept' }) + addSyntheticSession(index.db, { id: 2, role: 'assistant', text: 'assistantkept' }) + addSyntheticSession(index.db, { id: 3, role: 'tool', text: 'toolremoved', rows: 600 }) + const before = readIndexGeneration(index.db) + expect(index.engine.search({ query: 'toolremoved' }).hits).toHaveLength(0) + let messages = 602 + const errors: unknown[] = [] + const purge = new SessionSearchToolPurge( + index.db, + () => false, + (delta) => { + messages += delta + }, + (error) => errors.push(error) + ) + await purge.request() + expect(errors).toEqual([]) + expect(index.engine.search({ query: 'toolremoved' }).hits).toEqual([]) + expect(index.engine.search({ query: 'userkept' }).hits[0]?.sessionId).toBe('1') + expect(index.engine.search({ query: 'assistantkept' }).hits[0]?.sessionId).toBe('2') + expect(messages).toBe(2) + expect(readIndexGeneration(index.db)).toBeGreaterThan(before) + addSyntheticSession(index.db, { id: 4, role: 'tool', text: 'newlegacytool' }) + await purge.request() + expect(index.engine.search({ query: 'newlegacytool' }).hits).toEqual([]) + } finally { + await index.close() + } +}) diff --git a/src/main/ai-vault-search/session-search-tool-purge.ts b/src/main/ai-vault-search/storage/session-search-tool-purge.ts similarity index 97% rename from src/main/ai-vault-search/session-search-tool-purge.ts rename to src/main/ai-vault-search/storage/session-search-tool-purge.ts index 9db0ca20032..624d2089c86 100644 --- a/src/main/ai-vault-search/session-search-tool-purge.ts +++ b/src/main/ai-vault-search/storage/session-search-tool-purge.ts @@ -1,8 +1,8 @@ import { readIndexGeneration, recordIndexMaintenance } from './session-search-index-generation' import { setImmediate as yieldToEventLoop } from 'node:timers/promises' -import type SyncDatabase from '../sqlite/sync-database' -import type { SqliteRow } from '../sqlite/sqlite-statement' -import { reportSessionSearchBackgroundError, traceSessionSearch } from './session-search-trace' +import type SyncDatabase from '../../sqlite/sync-database' +import type { SqliteRow } from '../../sqlite/sqlite-statement' +import { reportSessionSearchBackgroundError, traceSessionSearch } from '../session-search-trace' const SCANNED_KEY = 'tool_purge_scanned_rowid' const FLOOR_KEY = 'tool_purge_floor_rowid' diff --git a/src/main/ai-vault-search/storage/session-search-write-buffer.test.ts b/src/main/ai-vault-search/storage/session-search-write-buffer.test.ts new file mode 100644 index 00000000000..9b3e1eb0e6b --- /dev/null +++ b/src/main/ai-vault-search/storage/session-search-write-buffer.test.ts @@ -0,0 +1,45 @@ +import { expect, it } from 'vitest' +import '../../sqlite/sync-database' +import './session-search-write-buffer' +import { SessionSearchIndexWriter } from './session-search-index-writer' +import { + openSessionSearchIndexFile, + syntheticCandidate, + syntheticSession +} from './session-search-index-test-fixture' + +it.each([1, 1_000_000])( + 'persists truncation through search writes with a %i-character buffer', + async (commitChars) => { + const index = await openSessionSearchIndexFile('ss-truncation-staging') + const writer = new SessionSearchIndexWriter(index.db, commitChars) + const write = writer.beginWrite(syntheticCandidate(), 'replace', 0) + if (!write) { + throw new Error('Expected write') + } + try { + write.add({ + role: 'user', + text: 'reader prefix '.repeat(1000), + timestamp: null, + textTruncated: true + }) + write.add({ role: 'assistant', text: 'complete reply', timestamp: null }) + write.add({ role: 'tool', text: 'output '.repeat(1000), timestamp: null }) + expect( + write.commit({ session: syntheticSession(), byteOffset: 100, incomplete: false }) + ).toBe(true) + expect( + index.db.prepare('SELECT role, text_truncated FROM messages ORDER BY id').all() + ).toEqual([ + { role: 'user', text_truncated: 1 }, + { role: 'user', text_truncated: 1 }, + { role: 'assistant', text_truncated: 0 } + ]) + } finally { + write.discard() + writer.close() + await index.close() + } + } +) diff --git a/src/main/ai-vault-search/session-search-write-buffer.ts b/src/main/ai-vault-search/storage/session-search-write-buffer.ts similarity index 94% rename from src/main/ai-vault-search/session-search-write-buffer.ts rename to src/main/ai-vault-search/storage/session-search-write-buffer.ts index 21bfb85bdb7..3bf3608cc1b 100644 --- a/src/main/ai-vault-search/session-search-write-buffer.ts +++ b/src/main/ai-vault-search/storage/session-search-write-buffer.ts @@ -1,6 +1,6 @@ -import SyncDatabase from '../sqlite/sync-database' -import type { TranscriptMessage } from '../ai-vault/transcripts/session-transcript-consumers' -import { ownRetainedString } from '../../shared/own-retained-string' +import SyncDatabase from '../../sqlite/sync-database' +import type { TranscriptMessage } from '../../ai-vault/transcripts/session-transcript-consumers' +import { ownRetainedString } from '../../../shared/own-retained-string' /** Shared by all handles; a capped row can overshoot the resident budget by at most 16,256 bytes. */ export class SessionSearchStagingBudget { diff --git a/src/main/ai-vault-search/session-search-write-lifetime.test.ts b/src/main/ai-vault-search/storage/session-search-write-lifetime.test.ts similarity index 93% rename from src/main/ai-vault-search/session-search-write-lifetime.test.ts rename to src/main/ai-vault-search/storage/session-search-write-lifetime.test.ts index b8cdcb51926..94227d3f618 100644 --- a/src/main/ai-vault-search/session-search-write-lifetime.test.ts +++ b/src/main/ai-vault-search/storage/session-search-write-lifetime.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' +import { registerSessionSearchIndexConsumer } from '../indexing/session-search-index-consumer' import { SessionSearchIndexWriter } from './session-search-index-writer' import { openSessionSearchIndexFile, diff --git a/src/main/ai-vault-search/session-search-cursor-snapshot.ts b/src/main/ai-vault-search/worker/session-search-cursor-snapshot.ts similarity index 92% rename from src/main/ai-vault-search/session-search-cursor-snapshot.ts rename to src/main/ai-vault-search/worker/session-search-cursor-snapshot.ts index 71e0a3debb9..ecdf459713d 100644 --- a/src/main/ai-vault-search/session-search-cursor-snapshot.ts +++ b/src/main/ai-vault-search/worker/session-search-cursor-snapshot.ts @@ -1,5 +1,5 @@ -import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' -import type { SessionSearchFileIdentity } from './session-search-file-cursor' +import type { SessionFileCandidate } from '../../ai-vault/session-scanner-types' +import type { SessionSearchFileIdentity } from '../storage/session-search-file-cursor' import type { SessionSearchSnapshotRow } from './session-search-worker-protocol' export abstract class SessionSearchCursorSnapshot { diff --git a/src/main/ai-vault-search/session-search-readers.test.ts b/src/main/ai-vault-search/worker/session-search-readers.test.ts similarity index 100% rename from src/main/ai-vault-search/session-search-readers.test.ts rename to src/main/ai-vault-search/worker/session-search-readers.test.ts diff --git a/src/main/ai-vault-search/session-search-readers.ts b/src/main/ai-vault-search/worker/session-search-readers.ts similarity index 94% rename from src/main/ai-vault-search/session-search-readers.ts rename to src/main/ai-vault-search/worker/session-search-readers.ts index 2ad90b8be8d..54d6390041f 100644 --- a/src/main/ai-vault-search/session-search-readers.ts +++ b/src/main/ai-vault-search/worker/session-search-readers.ts @@ -1,5 +1,5 @@ -import type { AiVaultSearchRequest } from '../../shared/ai-vault/search/ai-vault-search-types' -import type { SessionSearchHostScope } from './session-search-service' +import type { AiVaultSearchRequest } from '../../../shared/ai-vault/search/ai-vault-search-types' +import type { SessionSearchHostScope } from '../session-search-service' import { SessionSearchWorkerClient } from './session-search-worker-client' import type { SearchWorkerCommand, SearchWorkerResponse } from './session-search-worker-protocol' diff --git a/src/main/ai-vault-search/session-search-worker-client.test.ts b/src/main/ai-vault-search/worker/session-search-worker-client.test.ts similarity index 100% rename from src/main/ai-vault-search/session-search-worker-client.test.ts rename to src/main/ai-vault-search/worker/session-search-worker-client.test.ts diff --git a/src/main/ai-vault-search/session-search-worker-client.ts b/src/main/ai-vault-search/worker/session-search-worker-client.ts similarity index 91% rename from src/main/ai-vault-search/session-search-worker-client.ts rename to src/main/ai-vault-search/worker/session-search-worker-client.ts index fb4a9655c1b..68b83387e21 100644 --- a/src/main/ai-vault-search/session-search-worker-client.ts +++ b/src/main/ai-vault-search/worker/session-search-worker-client.ts @@ -1,12 +1,12 @@ -import { recordRelayedSpan } from '../observability/tracer' +import { recordRelayedSpan } from '../../observability/tracer' import { existsSync } from 'node:fs' -import { LazyWorkerThreadHost } from '../worker-threads/lazy-worker-thread-host' -import { spawnWorkerThread } from '../worker-threads/worker-thread-spawn' +import { LazyWorkerThreadHost } from '../../worker-threads/lazy-worker-thread-host' +import { spawnWorkerThread } from '../../worker-threads/worker-thread-spawn' import { currentWorkerEntryLayout, resolveWorkerThreadEntryPath -} from '../worker-threads/worker-thread-entry-path' -import type { WorkerThreadFactory } from '../worker-threads/worker-thread-transport' +} from '../../worker-threads/worker-thread-entry-path' +import type { WorkerThreadFactory } from '../../worker-threads/worker-thread-transport' import type { SearchWorkerCommand, SearchWorkerResponse } from './session-search-worker-protocol' export function sessionSearchWorkerFactory() { diff --git a/src/main/ai-vault-search/session-search-worker-entry.ts b/src/main/ai-vault-search/worker/session-search-worker-entry.ts similarity index 91% rename from src/main/ai-vault-search/session-search-worker-entry.ts rename to src/main/ai-vault-search/worker/session-search-worker-entry.ts index 665eece97b2..dd410a0ea0b 100644 --- a/src/main/ai-vault-search/session-search-worker-entry.ts +++ b/src/main/ai-vault-search/worker/session-search-worker-entry.ts @@ -1,13 +1,14 @@ -import { SessionSearchToolPurge } from './session-search-tool-purge' -import { readIndexGeneration } from './session-search-index-generation' +import { SessionSearchToolPurge } from '../storage/session-search-tool-purge' +import { readIndexGeneration } from '../storage/session-search-index-generation' import { parentPort } from 'node:worker_threads' -import SyncDatabase from '../sqlite/sync-database' -import { withSpan, setActiveSink } from '../observability/tracer' -import { SessionSearchStore, type SessionSearchStateCounts } from './session-search-store' -import { SessionSearchEngine } from './session-search-engine' -import { createSessionSearchService } from './session-search-service' -import type { SessionSearchFileWrite } from './session-search-index-writer' -import type { TranscriptSessionIdentity } from '../ai-vault/transcripts/session-transcript-consumers' +import SyncDatabase from '../../sqlite/sync-database' +import { withSpan, setActiveSink } from '../../observability/tracer' +import { SessionSearchStore } from '../storage/session-search-store' +import type { SessionSearchStateCounts } from '../storage/session-search-store-types' +import { SessionSearchEngine } from '../query/session-search-engine' +import { createSessionSearchService } from '../session-search-service' +import type { SessionSearchFileWrite } from '../storage/session-search-index-writer' +import type { TranscriptSessionIdentity } from '../../ai-vault/transcripts/session-transcript-consumers' import type { SearchWorkerRequest, SearchWorkerResponse, diff --git a/src/main/ai-vault-search/session-search-worker-protocol.ts b/src/main/ai-vault-search/worker/session-search-worker-protocol.ts similarity index 79% rename from src/main/ai-vault-search/session-search-worker-protocol.ts rename to src/main/ai-vault-search/worker/session-search-worker-protocol.ts index a3db6b6c3f8..33b10e35c67 100644 --- a/src/main/ai-vault-search/session-search-worker-protocol.ts +++ b/src/main/ai-vault-search/worker/session-search-worker-protocol.ts @@ -1,20 +1,20 @@ -import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' +import type { SessionFileCandidate } from '../../ai-vault/session-scanner-types' import type { TranscriptMessage, TranscriptReadOutcome, TranscriptSessionIdentity -} from '../ai-vault/transcripts/session-transcript-consumers' +} from '../../ai-vault/transcripts/session-transcript-consumers' import type { AiVaultSearchRequest, AiVaultSearchResponse -} from '../../shared/ai-vault/search/ai-vault-search-types' -import type { SessionSearchHostScope } from './session-search-service' +} from '../../../shared/ai-vault/search/ai-vault-search-types' +import type { SessionSearchHostScope } from '../session-search-service' import type { SessionSearchFileRow, SessionSearchFileState, SessionSearchStateCounts -} from './session-search-store' -import type { SessionContentHash } from './session-search-content-hash' +} from '../storage/session-search-store-types' +import type { SessionContentHash } from '../storage/session-search-content-hash' export type SessionSearchSnapshotRow = SessionSearchFileRow & { byteOffset: number | null diff --git a/src/main/ai-vault-search/session-search-worker-store-base.ts b/src/main/ai-vault-search/worker/session-search-worker-store-base.ts similarity index 95% rename from src/main/ai-vault-search/session-search-worker-store-base.ts rename to src/main/ai-vault-search/worker/session-search-worker-store-base.ts index 01d23522f3e..52771a1985f 100644 --- a/src/main/ai-vault-search/session-search-worker-store-base.ts +++ b/src/main/ai-vault-search/worker/session-search-worker-store-base.ts @@ -1,14 +1,17 @@ import { createAiVaultScanCancelledError, abandonRemoteSessionScanOnCancel -} from '../ai-vault/ai-vault-scan-cancellation' +} from '../../ai-vault/ai-vault-scan-cancellation' import { SessionSearchWorkerClient, SessionSearchOperationError } from './session-search-worker-client' -import { reportSessionSearchBackgroundError } from './session-search-trace' +import { reportSessionSearchBackgroundError } from '../session-search-trace' import { SessionSearchCursorSnapshot } from './session-search-cursor-snapshot' -import type { SessionSearchFileState, SessionSearchStateCounts } from './session-search-store' +import type { + SessionSearchFileState, + SessionSearchStateCounts +} from '../storage/session-search-store-types' import type { SearchWorkerCommand, SearchWorkerResponse } from './session-search-worker-protocol' /** Scanner-side cursor facts only; SQLite and durable staging belong to the writer thread. */ diff --git a/src/main/ai-vault-search/session-search-worker-store.ts b/src/main/ai-vault-search/worker/session-search-worker-store.ts similarity index 92% rename from src/main/ai-vault-search/session-search-worker-store.ts rename to src/main/ai-vault-search/worker/session-search-worker-store.ts index 4a9b92e82ec..f3dc113b30a 100644 --- a/src/main/ai-vault-search/session-search-worker-store.ts +++ b/src/main/ai-vault-search/worker/session-search-worker-store.ts @@ -1,17 +1,17 @@ -import { ownRetainedString } from '../../shared/own-retained-string' -import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' +import { ownRetainedString } from '../../../shared/own-retained-string' +import type { SessionFileCandidate } from '../../ai-vault/session-scanner-types' import type { TranscriptMessage, TranscriptReadOutcome, TranscriptSessionIdentity -} from '../ai-vault/transcripts/session-transcript-consumers' +} from '../../ai-vault/transcripts/session-transcript-consumers' import { createAiVaultScanCancelledError, abandonRemoteSessionScanOnCancel -} from '../ai-vault/ai-vault-scan-cancellation' -import { EMPTY_CONTENT_HASH, foldContentHash } from './session-search-content-hash' -import { searchMessageRows } from './session-search-message-rows' -import type { SessionSearchFileWrite } from './session-search-index-writer' +} from '../../ai-vault/ai-vault-scan-cancellation' +import { EMPTY_CONTENT_HASH, foldContentHash } from '../storage/session-search-content-hash' +import { searchMessageRows } from '../storage/session-search-message-rows' +import type { SessionSearchFileWrite } from '../storage/session-search-index-writer' import type { SearchWorkerCommand, SessionSearchSnapshotRow diff --git a/src/main/ai-vault-search/session-search-worker.test-fixture.ts b/src/main/ai-vault-search/worker/session-search-worker.test-fixture.ts similarity index 84% rename from src/main/ai-vault-search/session-search-worker.test-fixture.ts rename to src/main/ai-vault-search/worker/session-search-worker.test-fixture.ts index 3a3ef931776..8f0dbb25514 100644 --- a/src/main/ai-vault-search/session-search-worker.test-fixture.ts +++ b/src/main/ai-vault-search/worker/session-search-worker.test-fixture.ts @@ -2,13 +2,13 @@ import type * as WorkerClient from './session-search-worker-client' import { createRequire } from 'node:module' import { resolve } from 'node:path' import { vi } from 'vitest' -import { spawnWorkerThread } from '../worker-threads/worker-thread-spawn' +import { spawnWorkerThread } from '../../worker-threads/worker-thread-spawn' vi.mock('./session-search-worker-client', async (importOriginal) => { const actual = await importOriginal() const require = createRequire(import.meta.url) const loader = require.resolve('tsx/cjs') - const entry = resolve('src/main/ai-vault-search/session-search-worker-entry.ts') + const entry = resolve('src/main/ai-vault-search/worker/session-search-worker-entry.ts') return { ...actual, SessionSearchWorkerClient: class extends actual.SessionSearchWorkerClient { diff --git a/src/main/ai-vault-search/worker/session-search-worker.test.ts b/src/main/ai-vault-search/worker/session-search-worker.test.ts new file mode 100644 index 00000000000..3b03e837bbe --- /dev/null +++ b/src/main/ai-vault-search/worker/session-search-worker.test.ts @@ -0,0 +1,80 @@ +import './session-search-worker.test-fixture' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { SessionSearchWorkerStore } from './session-search-worker-store' +import { SessionSearchReaders } from './session-search-readers' +import '../indexing/session-search-index-consumer' +import { syntheticCandidate } from '../storage/session-search-index-test-fixture' +import '../../ai-vault/transcripts/session-transcript-reader' +import { resetTranscriptConsumersForTests } from '../../ai-vault/transcripts/session-transcript-consumers' +import 'node:crypto' +import SyncDatabase from '../../sqlite/sync-database' + +let root: string | undefined +let store: SessionSearchWorkerStore | undefined +let readers: SessionSearchReaders | undefined + +afterEach(async () => { + resetTranscriptConsumersForTests() + store?.close() + await Promise.all([store?.retired(), readers?.close()]) + if (root) { + await rm(root, { recursive: true, force: true }) + } +}) + +// Real workers import the parser graph; allow cold module loading plus SQLite publication. + +it('commits the original-message digest when a drained conversation ends with only tool rows', async () => { + root = await mkdtemp(join(tmpdir(), 'ss-worker-hash-tail-')) + const path = join(root, 'index.sqlite') + store = new SessionSearchWorkerStore(path, (error) => { + throw error + }) + await store.prepare() + const write = store.beginWrite(syntheticCandidate(), 'replace', 0, undefined, true)! + write.add({ role: 'user', text: 'prompt', timestamp: null }) + await write.drain!() + await store.flush() + write.add({ role: 'tool', text: 'tooltail', timestamp: null }) + const { syntheticSession } = await import('../storage/session-search-index-test-fixture') + expect(write.commit({ session: syntheticSession(), byteOffset: 4096, incomplete: false })).toBe( + true + ) + await store.flush() + const db = new SyncDatabase(path, { readonly: true }) + try { + expect(db.prepare('SELECT content_hash, content_hash_count FROM sessions').get()).toEqual({ + content_hash: '20d617e013f1dbefe8ce6afe43ad44ec558ae2e087d44804ce2f789cc04538a8', + content_hash_count: 2 + }) + expect(db.prepare('SELECT count(*) AS n FROM messages').get()).toEqual({ n: 1 }) + } finally { + db.close() + } +}) + +it('opens a cold reader and searches committed rows while a writer batch remains uncommitted', async () => { + root = await mkdtemp(join(tmpdir(), 'ss-reader-independent-')) + const path = join(root, 'index.sqlite') + const { SessionSearchStore } = await import('../storage/session-search-store') + const { addSyntheticSession } = await import('../query/session-search-engine-test-fixture') + const writer = new SessionSearchStore(path) + try { + addSyntheticSession(writer.connection, { id: 1, text: 'independentneedle' }) + writer.connection.exec('BEGIN IMMEDIATE') + writer.connection.prepare("UPDATE sessions SET title = 'uncommitted' WHERE id = 1").run() + readers = new SessionSearchReaders(path, null) + expect((await readers.query({ query: 'independentneedle' })).result).toMatchObject({ + kind: 'results', + hits: [{ sessionId: '1', title: 'fixture' }] + }) + } finally { + if (writer.connection.isTransaction) { + writer.connection.exec('ROLLBACK') + } + writer.close() + } +}) diff --git a/src/main/ai-vault/scan-service/session-scanner-service-client-state.ts b/src/main/ai-vault/scan-service/session-scanner-service-client-state.ts index d9a9b09f961..fc7d7a18403 100644 --- a/src/main/ai-vault/scan-service/session-scanner-service-client-state.ts +++ b/src/main/ai-vault/scan-service/session-scanner-service-client-state.ts @@ -1,5 +1,5 @@ import { recordRelayedSpan } from '../../observability/tracer' -import type { SessionSearchScanRoots } from '../../ai-vault-search/session-search-scan-roots' +import type { SessionSearchScanRoots } from '../../ai-vault-search/discovery/session-search-scan-roots' import type { ChildProcess } from 'node:child_process' import { createAiVaultScanCancelledError } from '../ai-vault-scan-cancellation' import type { AiVaultServiceScanListener } from './session-scanner-service-request-deadline' diff --git a/src/main/ai-vault/scan-service/session-scanner-service-protocol.ts b/src/main/ai-vault/scan-service/session-scanner-service-protocol.ts index b69788d7ec6..ec7d5c7bdb5 100644 --- a/src/main/ai-vault/scan-service/session-scanner-service-protocol.ts +++ b/src/main/ai-vault/scan-service/session-scanner-service-protocol.ts @@ -14,7 +14,7 @@ import type { } from '../../../shared/ai-vault/search/ai-vault-search-types' import type { AiVaultSearchSettings } from '../../../shared/ai-vault/search/ai-vault-search-settings' import type { SessionSearchHostScope } from '../../ai-vault-search/session-search-service' -import type { SessionSearchScanRoots } from '../../ai-vault-search/session-search-scan-roots' +import type { SessionSearchScanRoots } from '../../ai-vault-search/discovery/session-search-scan-roots' import type { ReadAiVaultFirstUserPromptArgs } from '../session-first-user-prompt-read' import type { SessionParseCachePersistenceOptions } from '../parse-cache/session-parse-cache-persistence' import type { AiVaultScanOptions } from '../session-scanner-types' diff --git a/src/main/ai-vault/scan-service/session-scanner-service-root-request.ts b/src/main/ai-vault/scan-service/session-scanner-service-root-request.ts index bba7592ba13..db64aef6cea 100644 --- a/src/main/ai-vault/scan-service/session-scanner-service-root-request.ts +++ b/src/main/ai-vault/scan-service/session-scanner-service-root-request.ts @@ -1,4 +1,4 @@ -import type { SessionSearchScanRoots } from '../../ai-vault-search/session-search-scan-roots' +import type { SessionSearchScanRoots } from '../../ai-vault-search/discovery/session-search-scan-roots' import type { AiVaultServiceParentMessage } from './session-scanner-service-protocol' let nextId = 1 diff --git a/src/main/ai-vault/scan-service/session-scanner-service-search-lifecycle.test.ts b/src/main/ai-vault/scan-service/session-scanner-service-search-lifecycle.test.ts deleted file mode 100644 index e4f1b667fa4..00000000000 --- a/src/main/ai-vault/scan-service/session-scanner-service-search-lifecycle.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import '../../ai-vault-search/session-search-worker.test-fixture' -import { afterEach, expect, it, vi } from 'vitest' -import { SessionSearchIndexer } from '../../ai-vault-search/session-search-indexer' -import { SessionSearchReaders } from '../../ai-vault-search/session-search-readers' -import { openSessionSearchIndexerHarness } from '../../ai-vault-search/session-search-indexer-test-fixture' -import { SessionScannerServiceSearch } from './session-scanner-service-search' - -afterEach(() => { - vi.useRealTimers() - vi.restoreAllMocks() -}) - -it.each(['initialization', 'retirement'] as const)( - 'answers search/status and settles cancelled or timed-out maintenance during slow %s', - async (phase) => { - const harness = await openSessionSearchIndexerHarness('ss-transition-deadline') - let release!: () => void - const blocked = new Promise((resolve) => { - release = resolve - }) - const initialize = vi.spyOn(SessionSearchIndexer.prototype, 'initialize').mockResolvedValue() - vi.spyOn(SessionSearchIndexer.prototype, 'start').mockResolvedValue() - const subject = new SessionScannerServiceSearch() - const init = { - databasePath: harness.databasePath, - roots: harness.roots, - settings: { enabled: true, historyDays: null } - } - if (phase === 'retirement') { - await subject.apply(init) - vi.spyOn(SessionSearchReaders.prototype, 'close').mockImplementationOnce(() => blocked) - } else { - initialize.mockImplementationOnce(() => blocked) - } - const applying = subject.apply(init) - try { - vi.useFakeTimers() - expect( - await subject.execute({ - type: 'request', - id: 1, - operation: 'searchSessions', - request: { query: 'needle' } - }) - ).toMatchObject({ value: { kind: 'unavailable', reason: 'not-ready' } }) - expect( - await subject.execute({ type: 'request', id: 2, operation: 'searchStatus' }) - ).toMatchObject({ value: { enabled: true } }) - for (const operation of ['searchReconcile', 'searchClear'] as const) { - const controller = new AbortController() - const pending = subject.execute({ type: 'request', id: 3, operation }, controller.signal) - controller.abort() - await expect(pending).rejects.toMatchObject({ name: 'AbortError' }) - } - const clear = expect( - subject.execute({ type: 'request', id: 4, operation: 'searchClear' }) - ).rejects.toThrow('Could not complete') - await vi.advanceTimersByTimeAsync(10_000) - await clear - } finally { - release() - vi.useRealTimers() - await applying - await subject.close() - await harness.cleanup() - } - } -) diff --git a/src/main/ai-vault/scan-service/session-scanner-service-search-roots.test.ts b/src/main/ai-vault/scan-service/session-scanner-service-search-roots.test.ts deleted file mode 100644 index a893f67fffc..00000000000 --- a/src/main/ai-vault/scan-service/session-scanner-service-search-roots.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { - openSessionSearchIndexerHarness, - writeMessageGraphTranscript, - type SessionSearchIndexerHarness -} from '../../ai-vault-search/session-search-indexer-test-fixture' -import { SessionSearchIndexer } from '../../ai-vault-search/session-search-indexer' -import type { SessionSearchScanRoots } from '../../ai-vault-search/session-search-scan-roots' -import { resetSessionParseCacheForTests } from '../parse-cache/session-parse-cache-store' -import type { AiVaultSessionSearchInit } from './session-scanner-service-protocol' -import { SessionScannerServiceSearch } from './session-scanner-service-search' -import { resetTranscriptConsumersForTests } from '../transcripts/session-transcript-consumers' - -let harness: SessionSearchIndexerHarness -let subject: SessionScannerServiceSearch -let spawnRoot: string -let lateRoot: string -let currentRoots: SessionSearchScanRoots -let spawnRoots: SessionSearchScanRoots - -beforeEach(async () => { - resetSessionParseCacheForTests() - resetTranscriptConsumersForTests() - harness = await openSessionSearchIndexerHarness('ss-service-roots') - subject = new SessionScannerServiceSearch(async () => currentRoots) - const { openclawLegacyStateDir, ...rest } = harness.roots - spawnRoot = harness.roots.openclawStateDir ?? '' - lateRoot = openclawLegacyStateDir ?? '' - spawnRoots = rest - currentRoots = rest -}) - -afterEach(async () => { - await subject.close() - vi.restoreAllMocks() - resetTranscriptConsumersForTests() - resetSessionParseCacheForTests() - await harness.cleanup() -}) - -function init(roots: SessionSearchScanRoots): AiVaultSessionSearchInit { - return { - databasePath: harness.databasePath, - settings: { enabled: true, historyDays: null }, - roots - } -} - -function openclawTranscript(stateDir: string, name: string): string { - return join(stateDir, 'agents', 'main', 'sessions', `${name}.jsonl`) -} - -async function sessionsMatching(term: string): Promise { - const reply = await subject.execute({ - type: 'request', - id: 1, - operation: 'searchSessions', - request: { query: term } - }) - if (reply.operation !== 'searchSessions' || reply.value.kind !== 'results') { - throw new Error(`expected results, got ${JSON.stringify(reply)}`) - } - return reply.value.hits.map((hit) => hit.sessionId).sort() -} - -async function indexedSessions(term: string, expected: string[]): Promise { - await vi.waitFor( - async () => { - await subject.execute({ type: 'request', id: 2, operation: 'searchReconcile' }) - expect(await sessionsMatching(term)).toEqual(expected) - }, - { timeout: 20_000 } - ) -} - -it('refreshes a late root without rebuilding the index', async () => { - await writeMessageGraphTranscript(openclawTranscript(spawnRoot, 'early-session'), [ - 'a conversation in a root the spawn already knew' - ]) - await writeMessageGraphTranscript(openclawTranscript(lateRoot, 'late-session'), [ - 'a conversation in a distro that started later' - ]) - - subject.apply(init(spawnRoots)) - await indexedSessions('conversation', ['early-session']) - - const close = vi.spyOn(SessionSearchIndexer.prototype, 'close') - currentRoots = harness.roots - await indexedSessions('conversation', ['early-session', 'late-session']) - expect(close).not.toHaveBeenCalled() -}) diff --git a/src/main/ai-vault/scan-service/session-scanner-service-search.test.ts b/src/main/ai-vault/scan-service/session-scanner-service-search.test.ts index a9b83f01c98..935ab45c29b 100644 --- a/src/main/ai-vault/scan-service/session-scanner-service-search.test.ts +++ b/src/main/ai-vault/scan-service/session-scanner-service-search.test.ts @@ -9,7 +9,7 @@ import { openSessionSearchIndexerHarness, writeClaudeTranscript, type SessionSearchIndexerHarness -} from '../../ai-vault-search/session-search-indexer-test-fixture' +} from '../../ai-vault-search/indexing/session-search-indexer-test-fixture' import { AI_VAULT_SERVICE_PROTOCOL_VERSION, type AiVaultServiceChildMessage, diff --git a/src/main/ai-vault/scan-service/session-scanner-service-search.ts b/src/main/ai-vault/scan-service/session-scanner-service-search.ts index 39cf574abeb..e068fd4f8b2 100644 --- a/src/main/ai-vault/scan-service/session-scanner-service-search.ts +++ b/src/main/ai-vault/scan-service/session-scanner-service-search.ts @@ -1,13 +1,13 @@ import { withinSessionSearchDeadline } from '../../ai-vault-search/session-search-request-deadline' -import type { SessionSearchIndexerOptions } from '../../ai-vault-search/session-search-indexer-options' +import type { SessionSearchIndexerOptions } from '../../ai-vault-search/indexing/session-search-indexer-options' import { unavailableSessionSearchStatus } from '../../../shared/ai-vault/search/ai-vault-search-client' import { AiVaultSearchRequestSchema } from '../../../shared/ai-vault/search/ai-vault-search-contract' import { SessionSearchInstance } from '../../ai-vault-search/session-search-instance' import { sameSessionSearchRoots, type SessionSearchScanRoots -} from '../../ai-vault-search/session-search-scan-roots' -import { sessionSearchSqliteAvailable } from '../../ai-vault-search/session-search-sqlite-support' +} from '../../ai-vault-search/discovery/session-search-scan-roots' +import { isSqliteAvailable } from '../../sqlite/sync-database' import type { AiVaultServiceRequest, AiVaultServiceResultValue, @@ -43,7 +43,7 @@ export class SessionScannerServiceSearch { } private async applySettings(init: AiVaultSessionSearchInit): Promise { - if (!sessionSearchSqliteAvailable()) { + if (!isSqliteAvailable()) { return } if (this.instance && this.databasePath !== init.databasePath) { diff --git a/src/main/ai-vault/scanners/codex/codex-session-root-dedup.ts b/src/main/ai-vault/scanners/codex/codex-session-root-dedup.ts index 4cfe85d9b78..1003eacbe0b 100644 --- a/src/main/ai-vault/scanners/codex/codex-session-root-dedup.ts +++ b/src/main/ai-vault/scanners/codex/codex-session-root-dedup.ts @@ -8,13 +8,24 @@ import { sessionSortTime } from '../../session-scanner-accumulator' // Bridging and backfill expose one rollout through multiple roots; list only its canonical alias (#7521). // Rollout names narrow candidates; inode or parsed session ID must still prove identity. -const CODEX_ROLLOUT_FILE_NAME_PATTERN = /^rollout-.+\.jsonl$/ +const CODEX_ROLLOUT_FILE_NAME_PATTERN = /^rollout-.+\.jsonl(?:\.zst)?$/ // Hosts can scan foreign-platform paths, so handle both separators independently of node:path. function lastPathSegment(filePath: string): string { return filePath.split(/[\\/]/).at(-1) ?? '' } +// Codex archives idle rollouts as .jsonl.zst and restores the .jsonl on resume, so both names alias one rollout. +function codexRolloutAliasName(fileName: string): string { + return fileName.endsWith('.zst') ? fileName.slice(0, -'.zst'.length) : fileName +} + +/** Returns null when both or neither alias is archived; otherwise whether `filePath` is the live one. */ +function codexLiveAliasBeats(filePath: string, bestPath: string): boolean | null { + const archived = filePath.endsWith('.zst') + return archived === bestPath.endsWith('.zst') ? null : !archived +} + export function codexRolloutHardlinkIdentity(file: { dev?: number ino?: number @@ -133,7 +144,7 @@ export async function dedupeCodexRolloutCopyAliases( if (!CODEX_ROLLOUT_FILE_NAME_PATTERN.test(fileName)) { continue } - const key = `${sessionFileExecutionNamespace(filePath)}\0${fileName}` + const key = `${sessionFileExecutionNamespace(filePath)}\0${codexRolloutAliasName(fileName)}` const group = groups.get(key) if (group) { group.push(candidate) @@ -173,7 +184,12 @@ export async function dedupeCodexRolloutCopyAliases( const filePath = accessors.getFilePath(candidate) const rank = codexSessionRootRank(accessors.getCodexHome(candidate)) const best = bestById.get(id) - if (!best || rank < best.rank || (rank === best.rank && filePath < best.filePath)) { + if ( + !best || + rank < best.rank || + (rank === best.rank && + (codexLiveAliasBeats(filePath, best.filePath) ?? filePath < best.filePath)) + ) { bestById.set(id, { candidate, rank, filePath }) } } @@ -195,7 +211,7 @@ export function codexSessionAliasKey(session: AiVaultSession): string | null { if (!CODEX_ROLLOUT_FILE_NAME_PATTERN.test(fileName)) { return null } - return `${session.executionHostId}\0${sessionFileExecutionNamespace(session.filePath)}\0${session.sessionId}\0${fileName}` + return `${session.executionHostId}\0${sessionFileExecutionNamespace(session.filePath)}\0${session.sessionId}\0${codexRolloutAliasName(fileName)}` } export function codexSessionAliasBeats(candidate: AiVaultSession, best: AiVaultSession): boolean { @@ -204,6 +220,10 @@ export function codexSessionAliasBeats(candidate: AiVaultSession, best: AiVaultS if (candidateRank !== bestRank) { return candidateRank < bestRank } + const live = codexLiveAliasBeats(candidate.filePath, best.filePath) + if (live !== null) { + return live + } const candidateTime = sessionSortTime(candidate) const bestTime = sessionSortTime(best) if (candidateTime !== bestTime) { diff --git a/src/main/ai-vault/scanners/codex/session-scanner-codex-fast-path.test.ts b/src/main/ai-vault/scanners/codex/session-scanner-codex-fast-path.test.ts index b2e44506531..ba065c3b55f 100644 --- a/src/main/ai-vault/scanners/codex/session-scanner-codex-fast-path.test.ts +++ b/src/main/ai-vault/scanners/codex/session-scanner-codex-fast-path.test.ts @@ -1,6 +1,7 @@ -import { mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' +import { zstdCompressSync } from 'node:zlib' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { parseCodexSessionFile } from './session-scanner-codex-parser' import { @@ -145,4 +146,45 @@ describe('Codex resumable parser fast path', () => { expect(session).toBeNull() expect(stats.bytesRead).toBeLessThan((file.sizeBytes ?? 0) / 2) }) + + it('indexes a Codex rollout archived as .jsonl.zst (#40312)', async () => { + const lines = [ + record( + 'session_meta', + { id: 'archived-session', cwd: '/repo/archived' }, + '2026-08-01T10:00:00.000Z' + ), + record( + 'response_item', + { type: 'message', role: 'user', content: 'archived question' }, + '2026-08-01T10:00:05.000Z' + ), + record( + 'response_item', + { type: 'message', role: 'assistant', content: 'archived answer' }, + '2026-08-01T10:00:10.000Z' + ) + ] + const plain = await writeTranscript(lines, 'rollout-2026-08-01T10-00-00-archived.jsonl') + const file: FileWithMtime = { + ...plain, + path: `${plain.path}.zst`, + sizeBytes: undefined + } + await writeFile(file.path, zstdCompressSync(await readFile(plain.path))) + const fileStat = await stat(file.path) + file.mtimeMs = fileStat.mtimeMs + file.sizeBytes = fileStat.size + + const session = await parseAgentSessionFileCached( + { agent: 'codex', file, codexHome: null }, + process.platform + ) + + expect(session).toMatchObject({ + sessionId: 'archived-session', + messageCount: 2, + updatedAt: '2026-08-01T10:00:10.000Z' + }) + }) }) diff --git a/src/main/ai-vault/scanners/codex/session-scanner-codex-parser.ts b/src/main/ai-vault/scanners/codex/session-scanner-codex-parser.ts index 246b642f591..43778625ff7 100644 --- a/src/main/ai-vault/scanners/codex/session-scanner-codex-parser.ts +++ b/src/main/ai-vault/scanners/codex/session-scanner-codex-parser.ts @@ -1,5 +1,9 @@ import { waitForAiVaultScan } from '../../ai-vault-scan-cancellation' import { openTranscriptReadStream } from '../../../native-chat/wsl-transcript-fs-access' +import { + isZstdTranscriptPath, + zstdTranscriptStream +} from '../../../native-chat/transcript-zstd-decompression' import { createInterface } from 'node:readline' import type { AiVaultSession, @@ -53,19 +57,25 @@ export async function parseCodexSessionFile( executionHostId?: ExecutionHostId, messages?: TranscriptMessageSink ): Promise { - const lines = createInterface({ - input: openTranscriptReadStream(file.path, { encoding: 'utf-8' }, 'scan'), - crlfDelay: Infinity - }) - return parseCodexSessionLines({ - file, - lines, - platform, - codexHome, - executionHostId, - messages, - titleReader: (sessionId) => readCodexSessionIndexTitle(file.path, codexHome, sessionId) - }) + // readline decodes UTF-8 across chunk boundaries, so both streams stay binary. + const raw = openTranscriptReadStream(file.path, {}, 'scan') + const input = isZstdTranscriptPath(file.path) ? zstdTranscriptStream(raw) : raw + const lines = createInterface({ input, crlfDelay: Infinity }) + try { + return await parseCodexSessionLines({ + file, + lines, + platform, + codexHome, + executionHostId, + messages, + titleReader: (sessionId) => readCodexSessionIndexTitle(file.path, codexHome, sessionId) + }) + } finally { + // readline.close() leaves its input open; an abandoned zstd decoder would keep inflating. + lines.close() + input.destroy() + } } type CodexSessionParseState = { accumulator: SessionAccumulator diff --git a/src/main/ai-vault/scanners/copilot/session-scanner-copilot-cache-upgrade.test.ts b/src/main/ai-vault/scanners/copilot/session-scanner-copilot-cache-upgrade.test.ts deleted file mode 100644 index 3a1cf241187..00000000000 --- a/src/main/ai-vault/scanners/copilot/session-scanner-copilot-cache-upgrade.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it } from 'vitest' -import { buildAiVaultResumeCommand } from '../../../../shared/ai-vault/resume/ai-vault-resume-command' -import SyncDatabase from '../../../sqlite/sync-database' -import { registerSessionSearchIndexConsumer } from '../../../ai-vault-search/session-search-index-consumer' -import { replayTranscriptRead } from '../../../ai-vault-search/session-search-index-test-fixture' -import { SessionSearchStore } from '../../../ai-vault-search/session-search-store' -import { sessionCandidate } from '../../../ai-vault-search/session-search-transcript-fixtures' -import { SessionParseCacheDatabase } from '../../parse-cache/session-parse-cache-database' -import { - initSessionParseCachePersistence, - resetSessionParseCachePersistenceForTests -} from '../../parse-cache/session-parse-cache-persistence' -import { - createSessionParseStats, - parseAgentSessionFileCached -} from '../../parse-cache/session-scanner-parse-cache' -import { - resetSessionParseCacheForTests, - type PersistedSessionParseCacheEntry -} from '../../parse-cache/session-parse-cache-store' -import { parseCopilotSessionFile } from './session-scanner-copilot-parser' -import { resetTranscriptConsumersForTests } from '../../transcripts/session-transcript-consumers' - -let root: string | undefined -let store: SessionSearchStore | undefined - -afterEach(async () => { - resetTranscriptConsumersForTests() - store?.close() - resetSessionParseCacheForTests() - resetSessionParseCachePersistenceForTests() - if (root) { - await rm(root, { recursive: true, force: true }) - } -}) - -function markPreviousVersion(path: string, version: number): void { - const db = new SyncDatabase(path) - try { - db.prepare("UPDATE meta SET value = ? WHERE key = 'schema_version'").run(String(version)) - } finally { - db.close() - } -} - -it('repairs unchanged Copilot metadata and search messages cached before the parser fix', async () => { - root = await mkdtemp(join(tmpdir(), 'orca-copilot-cache-upgrade-')) - const path = join(root, 'events.jsonl') - const prompt = 'fix the login bug' - const transformed = '2026-10-19 injected context' - await writeFile( - path, - `${[ - { type: 'session.start', data: { sessionId: 'copilot-session', context: { cwd: '/repo' } } }, - { type: 'user.message', data: { content: prompt, transformedContent: transformed } } - ] - .map((record) => JSON.stringify(record)) - .join('\n')}\n` - ) - const candidate = await sessionCandidate('copilot', path) - const sizeBytes = candidate.file.sizeBytes - if (sizeBytes === undefined) { - throw new Error('Missing Copilot fixture size') - } - const parsed = await parseCopilotSessionFile(candidate.file, 'linux') - if (!parsed) { - throw new Error('Missing Copilot fixture session') - } - const stale = { - ...parsed, - cwd: null, - title: transformed, - resumeCommand: buildAiVaultResumeCommand({ - agent: 'copilot', - sessionId: parsed.sessionId, - cwd: null, - platform: 'linux' - }) - } - const parsePath = join(root, 'session-parse-cache.sqlite') - const parseCache = new SessionParseCacheDatabase(parsePath) - const entry: PersistedSessionParseCacheEntry = { - mtimeMs: candidate.file.mtimeMs, - sizeBytes, - platform: 'linux', - session: stale - } - parseCache.write([[path, entry]], Date.now()) - parseCache.close() - markPreviousVersion(parsePath, 5) - - const searchPath = join(root, 'search.sqlite') - store = new SessionSearchStore(searchPath) - const unregister = registerSessionSearchIndexConsumer(store) - replayTranscriptRead({ - candidate, - messages: [{ role: 'user', text: transformed, timestamp: null }], - outcome: { session: stale, byteOffset: sizeBytes } - }) - unregister() - store.close() - markPreviousVersion(searchPath, 7) - - initSessionParseCachePersistence({ - filePath: join(root, 'session-parse-cache.json'), - appVersion: 'fixed' - }) - store = new SessionSearchStore(searchPath) - registerSessionSearchIndexConsumer(store) - const stats = createSessionParseStats() - const session = await parseAgentSessionFileCached(candidate, 'linux', stats) - - expect.soft(stats.fullParses).toBe(1) - expect.soft(session?.cwd).toBe('/repo') - expect.soft(session?.title).toBe(prompt) - expect.soft(session?.resumeCommand).toContain("cd '/repo'") - expect.soft(store.connection.prepare('SELECT cwd, title FROM sessions').get()).toEqual({ - cwd: '/repo', - title: prompt - }) - expect(store.connection.prepare('SELECT user_text FROM messages_fts').all()).toEqual([ - { user_text: prompt } - ]) -}) diff --git a/src/main/ai-vault/session-file-discovery.test.ts b/src/main/ai-vault/session-file-discovery.test.ts new file mode 100644 index 00000000000..c2f842f78c0 --- /dev/null +++ b/src/main/ai-vault/session-file-discovery.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import { AI_VAULT_AGENT_SOURCES } from './session-scanner-agent-sources' +import { isDiscoverableSessionFile } from './session-file-discovery' + +const codex = AI_VAULT_AGENT_SOURCES.codex +if (!codex) { + throw new Error('codex agent source missing') +} +const rootDir = '/home/u/.codex/sessions' + +describe('Codex session file discovery', () => { + it('admits rollout-named compressed archives and plain rollouts', () => { + expect( + isDiscoverableSessionFile(codex, rootDir, `${rootDir}/2026/08/20/rollout-2026-a.jsonl.zst`) + ).toBe(true) + expect( + isDiscoverableSessionFile(codex, rootDir, `${rootDir}/2026/08/20/rollout-2026-a.jsonl`) + ).toBe(true) + }) + + it('rejects compressed files that are not rollout archives', () => { + expect(isDiscoverableSessionFile(codex, rootDir, `${rootDir}/2026/08/20/notes.zst`)).toBe(false) + expect(isDiscoverableSessionFile(codex, rootDir, `${rootDir}/2026/08/20/backup.tar.zst`)).toBe( + false + ) + }) +}) diff --git a/src/main/ai-vault/session-scanner-agent-sources.ts b/src/main/ai-vault/session-scanner-agent-sources.ts index 3395c430251..4db2ab7c288 100644 --- a/src/main/ai-vault/session-scanner-agent-sources.ts +++ b/src/main/ai-vault/session-scanner-agent-sources.ts @@ -124,7 +124,11 @@ export const AI_VAULT_AGENT_SOURCES: AiVaultAgentSourceTable = { ...wslHomeSessionDirs('codex', wslHomeDirs), ...(options.additionalCodexSessionsDirs ?? []) ]), - extensions: ['.jsonl'] + // Codex archives rollouts idle 7+ days as .jsonl.zst (#40312); only rollout-named archives. + extensions: ['.jsonl', '.zst'], + filePredicate: (filePath) => + !filePath.toLowerCase().endsWith('.zst') || + /^rollout-.+\.jsonl\.zst$/.test(basename(filePath)) }, gemini: { rootDirs: (options, wslHomeDirs) => diff --git a/src/main/ai-vault/session-scanner-jsonl-reader.ts b/src/main/ai-vault/session-scanner-jsonl-reader.ts index 6af54b2fce4..cedcbe72037 100644 --- a/src/main/ai-vault/session-scanner-jsonl-reader.ts +++ b/src/main/ai-vault/session-scanner-jsonl-reader.ts @@ -1,6 +1,10 @@ import { throwIfAiVaultScanCancelled, waitForAiVaultScan } from './ai-vault-scan-cancellation' import type { Hash } from 'node:crypto' import { openTranscriptReadStream } from '../native-chat/wsl-transcript-fs-access' +import { + isZstdTranscriptPath, + zstdTranscriptStream +} from '../native-chat/transcript-zstd-decompression' import { MAX_SESSION_TRANSCRIPT_RECORD_BYTES, type SkippedTranscriptRecord @@ -60,7 +64,18 @@ export async function consumeCompleteJsonlLines(args: { let discarding = false const skippedRecords: SkippedTranscriptRecord[] = [] - const stream = openTranscriptReadStream(args.path, { start: args.start }, 'scan', args.signal) + // Compressed transcripts are immutable archives; every read starts from zero and decodes. + const compressed = isZstdTranscriptPath(args.path) + if (compressed && args.start !== 0) { + throw new Error(`compressed transcript cannot resume at byte ${args.start}: ${args.path}`) + } + const rawStream = openTranscriptReadStream( + args.path, + { start: compressed ? 0 : args.start }, + 'scan', + args.signal + ) + const stream = compressed ? zstdTranscriptStream(rawStream) : rawStream let chunkStart = args.start try { for await (const chunk of stream as AsyncIterable) { diff --git a/src/main/ai-vault/session-scanner-scope-walk.test.ts b/src/main/ai-vault/session-scanner-scope-walk.test.ts index 2b695cdf609..09e0403e631 100644 --- a/src/main/ai-vault/session-scanner-scope-walk.test.ts +++ b/src/main/ai-vault/session-scanner-scope-walk.test.ts @@ -1,6 +1,7 @@ -import { link, mkdtemp, mkdir, rm, stat, utimes, writeFile } from 'node:fs/promises' +import { link, mkdtemp, mkdir, readFile, rm, stat, utimes, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { zstdCompressSync } from 'node:zlib' import { afterEach, describe, expect, it, vi } from 'vitest' import { truncateAiVaultListResult } from '../../shared/ai-vault/scanning/ai-vault-session-depth' import type { AiVaultListResult } from '../../shared/ai-vault/contracts/ai-vault-types' @@ -139,6 +140,55 @@ async function writeRollout(sessionsDir: string, id: string, cwd: string, day: s } describe('scanAiVaultSessions — scope before the recency cap', () => { + it.each([undefined, ['/repo']])( + 'lists a rollout once, as its plain file, beside its .zst archive (scope %j)', + async (scopePaths) => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-zst-twin-')) + tempRoots.push(root) + const roots = isolatedScanRoots(root) + const plain = await writeRollout(roots.codexSessionsDir, 'twin', '/repo', '11') + await writeFile(`${plain}.zst`, zstdCompressSync(await readFile(plain))) + const archived = await writeRollout(roots.codexSessionsDir, 'archived-only', '/repo', '13') + await writeFile(`${archived}.zst`, zstdCompressSync(await readFile(archived))) + await rm(archived) + + const result = await scanAiVaultSessions({ ...roots, platform: 'darwin', scopePaths }) + + expect( + result.sessions + .filter((session) => session.agent === 'codex') + .map((session) => [session.sessionId, session.filePath]) + ).toEqual( + expect.arrayContaining([ + ['twin', plain], + ['archived-only', `${archived}.zst`] + ]) + ) + expect(result.sessions.filter((session) => session.agent === 'codex')).toHaveLength(2) + } + ) + + it('lists the live rollout when another account home holds only its archive', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-zst-homes-')) + tempRoots.push(root) + const homeA = join(root, 'codex-accounts', 'a', 'home', 'sessions') + const homeB = join(root, 'codex-accounts', 'b', 'home', 'sessions') + const archived = await writeRollout(homeA, 'moved', '/repo', '11') + await writeFile(`${archived}.zst`, zstdCompressSync(await readFile(archived))) + await rm(archived) + const live = await writeRollout(homeB, 'moved', '/repo', '11') + + const result = await scanAiVaultSessions({ + ...isolatedScanRoots(root), + additionalCodexSessionsDirs: [homeA, homeB], + platform: 'darwin' + }) + + expect( + result.sessions.filter((session) => session.agent === 'codex').map((s) => s.filePath) + ).toEqual([live]) + }) + it('lists an older in-scope Codex session once across hardlinked homes', async () => { const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-scope-walk-')) tempRoots.push(root) diff --git a/src/main/ai-vault/session-scope-cwd.ts b/src/main/ai-vault/session-scope-cwd.ts index 92c4fbc33b3..612362d380e 100644 --- a/src/main/ai-vault/session-scope-cwd.ts +++ b/src/main/ai-vault/session-scope-cwd.ts @@ -1,5 +1,14 @@ import type { AiVaultAgent } from '../../shared/ai-vault/contracts/ai-vault-types' -import { readTranscriptSlice, wslGatedReadFile } from '../native-chat/wsl-transcript-fs-access' +import { + openTranscriptReadStream, + readTranscriptSlice, + wslGatedReadFile +} from '../native-chat/wsl-transcript-fs-access' +import { + isZstdTranscriptPath, + readZstdTranscriptSlice, + zstdTranscriptStream +} from '../native-chat/transcript-zstd-decompression' import { CLAUDE_CWD_BUCKET_LAYOUT, CODEBUDDY_CWD_BUCKET_LAYOUT, @@ -182,7 +191,12 @@ export async function readTranscriptHeadCwd( : [first]) { let head: Buffer try { - head = await readTranscriptSlice(file.path, 0, length, 'scan', signal) + head = isZstdTranscriptPath(file.path) + ? await readZstdTranscriptSlice( + zstdTranscriptStream(openTranscriptReadStream(file.path, {}, 'scan', signal)), + length + ) + : await readTranscriptSlice(file.path, 0, length, 'scan', signal) } catch (error) { if (signal?.aborted) { throw error diff --git a/src/main/ai-vault/transcripts/session-document-consumer-replacement.test.ts b/src/main/ai-vault/transcripts/session-document-consumer-replacement.test.ts index 6639e798191..3feeabb2b43 100644 --- a/src/main/ai-vault/transcripts/session-document-consumer-replacement.test.ts +++ b/src/main/ai-vault/transcripts/session-document-consumer-replacement.test.ts @@ -1,78 +1,11 @@ -import { mkdtemp, rm, stat, writeFile } from 'node:fs/promises' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' import { readWholeTranscript } from './session-transcript-reader' import { registerTranscriptConsumer } from './session-transcript-consumers' -import { SessionSearchIndexWriter } from '../../ai-vault-search/session-search-index-writer' -import { openSessionSearchIndexFile } from '../../ai-vault-search/session-search-index-test-fixture' - -it.each(['hermes', 'gemini', 'devin', 'cline'] as const)( - 'indexes only the final %s message array, preserving JSON last-field semantics', - async (agent) => { - const root = await mkdtemp(join(tmpdir(), 'orca-document-replacement-')) - const index = await openSessionSearchIndexFile('ss-document-replacement') - const writer = new SessionSearchIndexWriter(index.db, 1) - const unregister = registerTranscriptConsumer({ - beginRead: (start) => { - const write = writer.beginWrite(start.candidate, start.mode, start.previousByteOffset) - if (!write) { - throw new Error('Expected write') - } - return { - message: (message) => write.add(message), - finish: (outcome) => { - if (outcome.incomplete) { - write.discard() - } else { - write.commit(outcome) - } - } - } - } - }) - try { - const path = join(root, 'session.json') - const key = agent === 'devin' ? 'steps' : 'messages' - const message = (text: string) => - JSON.stringify({ - role: 'assistant', - type: 'gemini', - source: 'agent', - content: text, - message: text - }) - const content = `{"${key}":[${message('overwritten')}],"${key}":[${message('retained 😀')}],"session_id":"session"}` - await writeFile(path, agent === 'cline' ? '{"session_id":"session"}' : content) - if (agent === 'cline') { - await writeFile(join(root, 'session.messages.json'), content) - } - const fileStat = await stat(path) - const session = await readWholeTranscript({ - candidate: { - agent, - codexHome: null, - file: { - path, - mtimeMs: 1, - modifiedAt: new Date(1).toISOString(), - sizeBytes: fileStat.size - } - }, - platform: 'linux' - }) - expect(session?.messageCount).toBe(1) - expect(index.db.prepare('SELECT assistant_text FROM messages_fts').all()).toEqual([ - { assistant_text: 'retained 😀' } - ]) - } finally { - unregister() - writer.close() - await index.close() - await rm(root, { recursive: true, force: true }) - } - } -) +import '../../ai-vault-search/storage/session-search-index-writer' +import '../../ai-vault-search/storage/session-search-index-test-fixture' it('discards partially emitted messages from a malformed Cline sidecar', async () => { const root = await mkdtemp(join(tmpdir(), 'orca-cline-incomplete-')) diff --git a/src/main/ai-vault/transcripts/session-transcript-consumers.test.ts b/src/main/ai-vault/transcripts/session-transcript-consumers.test.ts index 693fdfc7f5c..c9b040071cf 100644 --- a/src/main/ai-vault/transcripts/session-transcript-consumers.test.ts +++ b/src/main/ai-vault/transcripts/session-transcript-consumers.test.ts @@ -1,6 +1,7 @@ import { appendFile, mkdir, mkdtemp, rm, stat, truncate, utimes, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { zstdCompressSync } from 'node:zlib' import { afterEach, expect, it, vi } from 'vitest' import { isAiVaultScanCancelledError } from '../../../shared/ai-vault/contracts/ai-vault-types' import { scanAiVaultSessions } from '../session-scanner' @@ -307,3 +308,39 @@ it('reports the transcript size, not the cache key, as a whole-file read offset' const read = consumer.reads.find((entry) => entry.start.candidate.agent === 'cline') expect(read?.outcome?.byteOffset).toBe((await stat(metadataPath)).size) }) + +it('covers an archived Codex rollout through its compressed size, never resuming into it', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-transcript-consumers-zst-')) + tempRoots.push(root) + const path = join(root, 'rollout-2026-05-01T10-00-00-archived.jsonl.zst') + const records = [ + { type: 'session_meta', payload: { id: 'archived', cwd: '/repo' } }, + { + timestamp: '2026-05-01T10:00:01.000Z', + type: 'response_item', + payload: { type: 'message', role: 'user', content: [{ type: 'text', text: 'old ask' }] } + } + ] + await writeFile(path, zstdCompressSync(`${jsonLines(records)}\n`)) + const stats = await stat(path) + const candidate: SessionFileCandidate = { + agent: 'codex', + file: { + path, + mtimeMs: stats.mtimeMs, + modifiedAt: stats.mtime.toISOString(), + sizeBytes: stats.size + }, + codexHome: null + } + const consumer = recordingConsumer() + + await parseAgentSessionFileCached(candidate, 'darwin', undefined, 'any') + await parseAgentSessionFileCached(candidate, 'darwin', undefined, 'any') + + expect(consumer.reads.map((read) => [read.start.mode, read.outcome?.byteOffset])).toEqual([ + ['replace', stats.size], + ['replace', stats.size] + ]) + expect(textsFor(consumer.reads, 'codex')).toEqual(['user:old ask', 'user:old ask']) +}) diff --git a/src/main/ai-vault/transcripts/session-transcript-message-content.test.ts b/src/main/ai-vault/transcripts/session-transcript-message-content.test.ts index 92f7272f0a4..a88f45ad394 100644 --- a/src/main/ai-vault/transcripts/session-transcript-message-content.test.ts +++ b/src/main/ai-vault/transcripts/session-transcript-message-content.test.ts @@ -4,34 +4,6 @@ import { transcriptMessagesFromDecodedMessage } from './session-transcript-messa import { decodeSessionMessage } from './session-decoded-message' const AT = '2026-05-01T10:00:00.000Z' -const MESSAGE_LIMIT = 256 * 1024 - -it('reads tool-result parts lazily and can project the same decoded result again', () => { - const decoded = decodeSessionMessage( - 'user', - [ - { - type: 'tool_result', - content: [ - { type: 'text', text: 'x'.repeat(MESSAGE_LIMIT) }, - { type: 'text', text: 'omitted text' }, - { - type: 'text', - get text() { - throw new Error('Read beyond the tool-result safety limit') - } - } - ] - } - ], - AT - ) - for (let read = 0; read < 2; read++) { - expect(transcriptMessagesFromDecodedMessage(decoded)).toEqual([ - { role: 'tool', text: 'x'.repeat(MESSAGE_LIMIT), timestamp: AT, textTruncated: true } - ]) - } -}) it('keeps captured server calls and structured results in full Session History', () => { const messages = advisorCapture.flatMap((frame) => diff --git a/src/main/ai-vault/transcripts/session-transcript-reader.ts b/src/main/ai-vault/transcripts/session-transcript-reader.ts index c61449a5104..6f3b8e77936 100644 --- a/src/main/ai-vault/transcripts/session-transcript-reader.ts +++ b/src/main/ai-vault/transcripts/session-transcript-reader.ts @@ -4,6 +4,7 @@ import { readTranscriptSlice } from '../../native-chat/wsl-transcript-fs-access' import type { AiVaultSession } from '../../../shared/ai-vault/contracts/ai-vault-types' import { parseAgentSessionFile } from '../session-scanner-agent-parser' import { consumeCompleteJsonlLines } from '../session-scanner-jsonl-reader' +import { isZstdTranscriptPath } from '../../native-chat/transcript-zstd-decompression' import type { ResumableSessionParseState, SessionFileCandidate } from '../session-scanner-types' import { invalidateSessionParseCacheEntry, @@ -55,7 +56,10 @@ export async function readResumableTranscript( ): Promise { const { file } = args.candidate const resume = args.resume + // Codex .jsonl.zst archives never grow; decoded offsets cannot address their compressed bytes. + const archived = isZstdTranscriptPath(file.path) const canResume = + !archived && resume !== null && typeof file.sizeBytes === 'number' && file.sizeBytes >= resume.byteOffset && @@ -83,7 +87,7 @@ export async function readResumableTranscript( // Hash only for consumers: they compare prefixes after a restart drops this resume point. const prefixHash = canResume ? (resume.prefixHash?.copy() ?? null) - : hasTranscriptConsumers() + : !archived && hasTranscriptConsumers() ? createHash('sha256') : null const prefixOffsets = @@ -98,6 +102,8 @@ export async function readResumableTranscript( prefixOffsets }) try { + // Archives are covered through their compressed size, which search cursors compare to stat size. + const coveredThrough = archived ? (file.sizeBytes ?? 0) : null const readResult = await consumeCompleteJsonlLines({ path: file.path, start: startOffset, @@ -135,7 +141,7 @@ export async function readResumableTranscript( throwIfAiVaultScanCancelled(args.signal) channel.finishRead({ session: consumerSession, - byteOffset: readResult.consumedThrough, + byteOffset: coveredThrough ?? readResult.consumedThrough, incomplete: false, prefixHash: readResult.prefixHash?.copy().digest('hex') }) @@ -143,7 +149,7 @@ export async function readResumableTranscript( session, resume: { state, - byteOffset: readResult.consumedThrough, + byteOffset: coveredThrough ?? readResult.consumedThrough, mtimeMs: file.mtimeMs, sizeBytes: file.sizeBytes, channel, diff --git a/src/main/artifacts/artifact-cloud-request.ts b/src/main/artifacts/artifact-cloud-request.ts index 8c040049687..a39233f1c7f 100644 --- a/src/main/artifacts/artifact-cloud-request.ts +++ b/src/main/artifacts/artifact-cloud-request.ts @@ -1,5 +1,5 @@ import type { ArtifactWriteRequest } from '../../shared/artifacts/artifacts' -import { OrcaCloudRequestError } from '../orca-profiles/profile-cloud-client' +import { OrcaCloudRequestError } from '../orca-profiles/cloud-auth/profile-cloud-client' export type ArtifactWriteBody = { content: string diff --git a/src/main/artifacts/artifact-cloud-service.test.ts b/src/main/artifacts/artifact-cloud-service.test.ts index 69bd24b2ade..664d4067d77 100644 --- a/src/main/artifacts/artifact-cloud-service.test.ts +++ b/src/main/artifacts/artifact-cloud-service.test.ts @@ -13,8 +13,8 @@ import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' import { linkOrcaProfileToCloud, unlinkOrcaProfileFromCloud -} from '../orca-profiles/profile-cloud-index' -import { signOutCloudSession } from '../orca-profiles/profile-cloud-session-owner' +} from '../orca-profiles/cloud-auth/profile-cloud-index' +import { signOutCloudSession } from '../orca-profiles/cloud-session/profile-cloud-session-owner' import { ArtifactCloudService } from './artifact-cloud-service' diff --git a/src/main/artifacts/artifact-cloud-service.ts b/src/main/artifacts/artifact-cloud-service.ts index 9cff076d1b0..7bbddc0ef54 100644 --- a/src/main/artifacts/artifact-cloud-service.ts +++ b/src/main/artifacts/artifact-cloud-service.ts @@ -11,9 +11,9 @@ import type { } from '../../shared/artifacts/artifacts' import { assertArtifactSharingAllowed } from '../../shared/artifacts/artifact-sharing-gate' import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' -import { getOrcaCloudAuthConfig } from '../orca-profiles/profile-cloud-auth-config' -import { prepareArtifactCloudUse } from '../orca-profiles/profile-artifact-cloud-cleanup' -import { runWithFreshOrcaCloudSession } from '../orca-profiles/profile-cloud-session-refresh' +import { getOrcaCloudAuthConfig } from '../orca-profiles/cloud-auth/profile-cloud-auth-config' +import { prepareArtifactCloudUse } from '../orca-profiles/cloud-auth/profile-artifact-cloud-cleanup' +import { runWithFreshOrcaCloudSession } from '../orca-profiles/cloud-session/profile-cloud-session-refresh' import { allowsArtifactCloudAuthOverride, resolveArtifactCloudApiUrl @@ -29,7 +29,7 @@ import { import type { ActiveOrcaProfileState } from '../orca-profiles/profile-index-store' import { artifactRequest, artifactWriteBody } from './artifact-cloud-request' import { ArtifactPublisher } from './artifact-publisher' -import { OrcaCloudRequestError } from '../orca-profiles/profile-cloud-client' +import { OrcaCloudRequestError } from '../orca-profiles/cloud-auth/profile-cloud-client' type ArtifactAuthContext = { profileId: string diff --git a/src/main/artifacts/artifact-publisher.ts b/src/main/artifacts/artifact-publisher.ts index ad86a866cfb..dfe30c7ba89 100644 --- a/src/main/artifacts/artifact-publisher.ts +++ b/src/main/artifacts/artifact-publisher.ts @@ -3,7 +3,7 @@ import type { ArtifactPublishResult, ArtifactWriteRequest } from '../../shared/artifacts/artifacts' -import { OrcaCloudRequestError } from '../orca-profiles/profile-cloud-client' +import { OrcaCloudRequestError } from '../orca-profiles/cloud-auth/profile-cloud-client' import { artifactRequest, type ArtifactWriteBody, diff --git a/src/main/automations/external-automation-owner-guard.test.ts b/src/main/automations/external-automation-owner-guard.test.ts deleted file mode 100644 index f83a7cf1dc0..00000000000 --- a/src/main/automations/external-automation-owner-guard.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { resolveExternalAutomationScope } from './external-automation-owner-guard' -import { AutomationOwnerConflictError } from '../../shared/automations/ownership/automation-owner-conflict' -import type { AutomationOwnerRef } from '../../shared/automations/ownership/automation-owner-ref' - -import type { SshTarget } from '../../shared/ssh-types' - -function sshTarget(overrides: Partial = {}): SshTarget { - return { - id: 'target-a', - label: 'Build box', - host: 'build.example', - port: 22, - username: 'orca', - generation: 3, - ...overrides - } -} - -function registry(targets: SshTarget[]): { getSshTargets: () => SshTarget[] } { - return { getSshTargets: () => targets } -} - -function desktopSsh(targetId: string, targetGeneration: number): AutomationOwnerRef { - return { authority: { kind: 'desktop' }, selector: { kind: 'ssh', targetId, targetGeneration } } -} - -describe('resolveExternalAutomationScope', () => { - it('fails closed with the host-changed conflict on a stale generation', () => { - try { - resolveExternalAutomationScope( - { owner: desktopSsh('target-a', 2), provider: 'openclaw' }, - registry([sshTarget({ generation: 3 })]) - ) - expect.unreachable('stale generation must not resolve') - } catch (error) { - expect(error).toBeInstanceOf(AutomationOwnerConflictError) - expect((error as AutomationOwnerConflictError).code).toBe('automation_owner_changed') - } - }) - - it('fails closed when the registration carries no usable generation', () => { - try { - resolveExternalAutomationScope( - { owner: desktopSsh('target-a', 1), provider: 'openclaw' }, - registry([sshTarget({ generation: undefined })]) - ) - expect.unreachable('unstamped registration must not resolve') - } catch (error) { - expect((error as AutomationOwnerConflictError).code).toBe('automation_owner_changed') - } - }) - - it('reports a removed SSH host as a target-removed conflict', () => { - try { - resolveExternalAutomationScope( - { owner: desktopSsh('gone', 1), provider: 'openclaw' }, - registry([sshTarget()]) - ) - expect.unreachable('missing target must not resolve') - } catch (error) { - expect((error as AutomationOwnerConflictError).code).toBe('automation_target_removed') - } - }) -}) diff --git a/src/main/automations/external-manager.test.ts b/src/main/automations/external-manager.test.ts deleted file mode 100644 index 27367d5f003..00000000000 --- a/src/main/automations/external-manager.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { runExternalAutomationAction } from './external-manager' - -import type { - ExternalAutomationAction, - ExternalAutomationProvider -} from '../../shared/automations/external/external-automation' -import type * as Fs from 'node:fs' - -const runProcessMock = vi.hoisted(() => vi.fn()) -const existsSyncMock = vi.hoisted(() => vi.fn(() => false)) - -vi.mock('@orca/process-host', () => ({ runProcess: runProcessMock })) -vi.mock('fs', async () => { - const actual = await vi.importActual('fs') - return { - ...actual, - existsSync: existsSyncMock - } -}) - -beforeEach(() => { - runProcessMock.mockReset() - runProcessMock.mockResolvedValue({ - code: 0, - signal: null, - stdout: '', - stderr: '', - timedOut: false - }) - existsSyncMock.mockReturnValue(false) -}) - -afterEach(() => { - vi.useRealTimers() -}) - -describe('runExternalAutomationAction', () => { - it('rejects job IDs that could be parsed as CLI options', async () => { - await expect( - runExternalAutomationAction({ - managerId: 'openclaw:local', - provider: 'openclaw', - target: { type: 'local' }, - jobId: '-help', - action: 'run' - }) - ).rejects.toThrow('Invalid external automation job ID.') - - expect(runProcessMock).not.toHaveBeenCalled() - }) - - it('rejects an action inherited from the prototype chain', async () => { - await expect( - runExternalAutomationAction({ - managerId: 'openclaw:local', - provider: 'openclaw', - target: { type: 'local' }, - jobId: 'job-1', - action: 'toString' as unknown as ExternalAutomationAction - }) - ).rejects.toThrow('Unsupported external automation action.') - - expect(runProcessMock).not.toHaveBeenCalled() - }) - - it('rejects a provider that has no action table', async () => { - await expect( - runExternalAutomationAction({ - managerId: 'openclaw:local', - provider: 'shellcat' as ExternalAutomationProvider, - target: { type: 'local' }, - jobId: 'job-1', - action: 'run' - }) - ).rejects.toThrow('Unsupported external automation action.') - - expect(runProcessMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/automations/runtime-terminal-run-observer.test.ts b/src/main/automations/runtime-terminal-run-observer.test.ts deleted file mode 100644 index e078380af0b..00000000000 --- a/src/main/automations/runtime-terminal-run-observer.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - createTranscriptPane, - TRANSCRIPT_PANE_PTY_ID -} from '../runtime/orca-runtime-tests/agent-transcript-pane-test-harness' -import { createRuntimeAutomationRunTerminalObserver } from './runtime-terminal-run-observer' - -describe('createRuntimeAutomationRunTerminalObserver', () => { - beforeEach(() => { - vi.useFakeTimers() - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('propagates recorded end from the real runtime initial probe without a startup wait', async () => { - vi.useRealTimers() - const { runtime, handle } = await createTranscriptPane({ - paneTitle: 'shell', - foregroundProcess: 'bash', - data: '' - }) - runtime.onPtyExit(TRANSCRIPT_PANE_PTY_ID, 137, 'inc-1', { providerExitObserved: true }) - vi.useFakeTimers() - const observer = createRuntimeAutomationRunTerminalObserver(runtime) - await expect( - observer.observeCompletion(handle, { signal: new AbortController().signal }) - ).rejects.toThrow('terminal_exited') - expect(runtime['terminalWaiters'].forPty(TRANSCRIPT_PANE_PTY_ID)).toHaveLength(0) - }) - - it('keeps watching a run terminal across a window reload', async () => { - const waitForTerminal = vi - .fn() - // The start probe sees the agent busy. - .mockResolvedValueOnce({ satisfied: false }) - .mockRejectedValueOnce(new Error('runtime_unavailable')) - .mockResolvedValueOnce({ satisfied: true }) - const observer = createRuntimeAutomationRunTerminalObserver({ - getTerminalHandleForPaneKey: () => 'handle-1', - waitForTerminal, - readTerminal: async () => ({ tail: ['done'] }), - canOpenRunTerminals: () => true - }) - - const observed = observer.observeCompletion('handle-1', { - signal: new AbortController().signal - }) - await vi.advanceTimersByTimeAsync(5_000) - - await expect(observed).resolves.toMatchObject({ status: 'completed' }) - }) -}) diff --git a/src/main/azure-devops/repository-ref.test.ts b/src/main/azure-devops/repository-ref.test.ts new file mode 100644 index 00000000000..faab6a1661e --- /dev/null +++ b/src/main/azure-devops/repository-ref.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest' +import { parseAzureDevOpsRepoRef } from './repository-ref' + +describe('parseAzureDevOpsRepoRef', () => { + it('reads the SSH remote older visualstudio.com organizations use', () => { + const expected = { + host: 'myorg.visualstudio.com', + organization: 'myorg', + project: 'Proj', + repository: 'Repo', + apiBaseUrl: 'https://myorg.visualstudio.com/Proj', + webBaseUrl: 'https://myorg.visualstudio.com/Proj/_git/Repo' + } + expect(parseAzureDevOpsRepoRef('myorg@vs-ssh.visualstudio.com:v3/myorg/Proj/Repo')).toEqual( + expected + ) + expect( + parseAzureDevOpsRepoRef('ssh://myorg@vs-ssh.visualstudio.com:22/v3/myorg/Proj/Repo') + ).toEqual(expected) + expect(parseAzureDevOpsRepoRef('https://myorg.visualstudio.com/Proj/_git/Repo')).toEqual( + expected + ) + }) + + it('rejects a vs-ssh organization that would redirect the API host', () => { + expect(parseAzureDevOpsRepoRef('git@vs-ssh.visualstudio.com:v3/evil.example%23/P/R')).toBeNull() + expect( + parseAzureDevOpsRepoRef('ssh://git@vs-ssh.visualstudio.com/v3/evil.example%2F/P/R') + ).toBeNull() + }) + + it('keeps reading dev.azure.com SSH remotes as before', () => { + expect(parseAzureDevOpsRepoRef('git@ssh.dev.azure.com:v3/acme/Proj/Repo')).toMatchObject({ + host: 'dev.azure.com', + organization: 'acme', + webBaseUrl: 'https://dev.azure.com/acme/Proj/_git/Repo' + }) + }) +}) diff --git a/src/main/azure-devops/repository-ref.ts b/src/main/azure-devops/repository-ref.ts index 086ceaca7b6..0c984587391 100644 --- a/src/main/azure-devops/repository-ref.ts +++ b/src/main/azure-devops/repository-ref.ts @@ -1,4 +1,5 @@ import { createRemoteRefProbeCache } from '../git/remotes/remote-ref-probe-cache' +import { isAzureDevOpsOrganizationName } from '../../shared/git/remotes/azure-devops-organization-name' export type AzureDevOpsRepoRef = { host: string @@ -136,7 +137,8 @@ function parseVisualStudioUrl(url: URL): AzureDevOpsRepoRef | null { } function parseCloudSshPath(host: string, rawPath: string): AzureDevOpsRepoRef | null { - if (host.toLowerCase() !== 'ssh.dev.azure.com') { + const sshHost = host.toLowerCase() + if (!isCloudSshHost(sshHost)) { return null } const parts = splitPath(rawPath) @@ -147,7 +149,27 @@ function parseCloudSshPath(host: string, rawPath: string): AzureDevOpsRepoRef | if (!organization || !project || !repository) { return null } - return makeCloudRef('dev.azure.com', organization, project, repository) + if (sshHost === 'ssh.dev.azure.com') { + return makeCloudRef('dev.azure.com', organization, project, repository) + } + // Older orgs' SSH host; match what their https://.visualstudio.com remotes resolve to. + if (!isAzureDevOpsOrganizationName(organization)) { + return null + } + const webHost = `${organization.toLowerCase()}.visualstudio.com` + const origin = `https://${webHost}` + return { + host: webHost, + organization, + project, + repository, + apiBaseUrl: joinUrl(origin, [project]), + webBaseUrl: joinUrl(origin, [project, '_git', repository]) + } +} + +function isCloudSshHost(host: string): boolean { + return host === 'ssh.dev.azure.com' || host === 'vs-ssh.visualstudio.com' } function parseScpLike(remoteUrl: string): AzureDevOpsRepoRef | null { @@ -167,7 +189,7 @@ export function parseAzureDevOpsRepoRef(remoteUrl: string): AzureDevOpsRepoRef | try { const url = new URL(trimmed) const host = url.hostname.toLowerCase() - if (host === 'ssh.dev.azure.com') { + if (isCloudSshHost(host)) { return parseCloudSshPath(host, url.pathname) } if (!['http:', 'https:', 'ssh:', 'git+ssh:'].includes(url.protocol.toLowerCase())) { diff --git a/src/main/bitbucket/credential-connection.test.ts b/src/main/bitbucket/credential-connection.test.ts index 6f212bf419b..2bf06a5587a 100644 --- a/src/main/bitbucket/credential-connection.test.ts +++ b/src/main/bitbucket/credential-connection.test.ts @@ -94,6 +94,30 @@ describe('Bitbucket credential connection', () => { expect(conn.getBitbucketConnectionStatus().source).toBe('none') }) + it('saves an access token Bitbucket accepts without account access (STA-14576)', async () => { + const conn = await loadModule() + globalThis.fetch = vi.fn( + async () => new Response('Forbidden', { status: 403 }) + ) + const proxied = await conn.connectBitbucket({ authMode: 'token', accessToken: 'repo-token' }) + expect(proxied.ok).toBe(false) + expect(conn.getBitbucketConnectionStatus().source).toBe('none') + + // Bitbucket's /user answer for every repository, project or workspace access token. + globalThis.fetch = vi.fn(async () => + Response.json( + { + type: 'error', + error: { message: 'Token is invalid or not supported for this endpoint.' } + }, + { status: 403 } + ) + ) + const result = await conn.connectBitbucket({ authMode: 'token', accessToken: 'repo-token' }) + expect(result).toEqual({ ok: true, account: null }) + expect(conn.getBitbucketConnectionStatus().source).toBe('stored') + }) + it('rejects an incomplete basic-auth credential before making a request', async () => { const conn = await loadModule() const fetchSpy = vi.fn() diff --git a/src/main/bitbucket/user-request.ts b/src/main/bitbucket/user-request.ts index de82358a145..e990f7fb6b3 100644 --- a/src/main/bitbucket/user-request.ts +++ b/src/main/bitbucket/user-request.ts @@ -11,7 +11,7 @@ export type RawBitbucketUser = { /** Network, server and decode failures do not prove the credentials are invalid. */ export type BitbucketUserResult = - | { ok: true; user: RawBitbucketUser } + | { ok: true; user: RawBitbucketUser | null } | { ok: false; reason: 'rejected' | 'unreachable' } export function accountNameFromUser(user: RawBitbucketUser | null): string | null { @@ -35,10 +35,16 @@ export async function fetchBitbucketUserResult( } catch { return { ok: false, reason: 'unreachable' } } + // Bitbucket answers 401 to bad credentials; its 403 means it accepted them without account access + // (every access token, and API tokens without read:user:bitbucket). + if (response.status === 403) { + return (await isBitbucketErrorBody(response)) + ? { ok: true, user: null } + : { ok: false, reason: 'unreachable' } + } if (!response.ok) { await cancelUnreadResponseBody(response) - const rejected = response.status === 401 || response.status === 403 - return { ok: false, reason: rejected ? 'rejected' : 'unreachable' } + return { ok: false, reason: response.status === 401 ? 'rejected' : 'unreachable' } } try { return { ok: true, user: (await response.json()) as RawBitbucketUser } @@ -46,3 +52,13 @@ export async function fetchBitbucketUserResult( return { ok: false, reason: 'unreachable' } } } + +// A proxy or non-Bitbucket base URL can answer 403 without checking the credential. +async function isBitbucketErrorBody(response: Response): Promise { + try { + const body: unknown = await response.json() + return typeof body === 'object' && body !== null && 'type' in body && body.type === 'error' + } catch { + return false + } +} diff --git a/src/main/browser/cookies/browser-cookie-import-write.test.ts b/src/main/browser/cookies/browser-cookie-import-write.test.ts deleted file mode 100644 index e7f9a6cc2b8..00000000000 --- a/src/main/browser/cookies/browser-cookie-import-write.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { CookieClearIdentity } from './storage/cookie-store-contracts' -import type { SourcePartitionRead } from './sources/browser-cookie-source-partition' -import { writeImportedCookies, type SourceCookieToWrite } from './browser-cookie-import-write' - -function sourceCookie( - overrides: Partial & { name: string; partition: SourcePartitionRead } -): SourceCookieToWrite { - return { - url: 'https://app.example/', - value: 'v', - domain: '.app.example', - path: '/', - secure: true, - httpOnly: false, - sameSite: 'no_restriction', - expirationDate: undefined, - ...overrides - } -} - -function recordingStore() { - const writeCookieIdentity = vi.fn<(identity: CookieClearIdentity) => Promise>( - async () => undefined - ) - return { writeCookieIdentity } -} - -const silentOptions = { log: () => undefined } - -describe('writeImportedCookies', () => { - it('never dispatches an expired cookie, which would delete the existing coordinate', async () => { - const store = recordingStore() - const result = await writeImportedCookies( - store, - [ - sourceCookie({ - name: 'sid', - expirationDate: 1, - partition: { status: 'unpartitioned' } - }) - ], - silentOptions - ) - expect(result).toMatchObject({ importedCount: 0, expired: 1, writeRejected: 0 }) - expect(store.writeCookieIdentity).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/browser/cookies/sources/browser-cookie-decryption.test.ts b/src/main/browser/cookies/sources/browser-cookie-decryption.test.ts index 50955cb3be3..ef893be62df 100644 --- a/src/main/browser/cookies/sources/browser-cookie-decryption.test.ts +++ b/src/main/browser/cookies/sources/browser-cookie-decryption.test.ts @@ -5,9 +5,8 @@ import type { EncryptionKeyResult } from './chromium-encryption-key-contract' const HOST_KEY = '.example.com' const cbcKey = randomBytes(16) -const gcmKey = randomBytes(32) + const cbcKeyResult: EncryptionKeyResult = { mode: 'aes-128-cbc', keysByVersion: { v10: cbcKey } } -const gcmKeyResult: EncryptionKeyResult = { mode: 'aes-256-gcm', key: gcmKey } function hostKeyHash(hostKey: string): Buffer { return createHash('sha256').update(hostKey).digest() @@ -18,21 +17,9 @@ function encryptCbc(plaintext: Buffer): Buffer { return Buffer.concat([Buffer.from('v10'), cipher.update(plaintext), cipher.final()]) } -function encryptGcm(plaintext: Buffer): Buffer { - const nonce = randomBytes(12) - const cipher = createCipheriv('aes-256-gcm', gcmKey, nonce) - const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]) - return Buffer.concat([Buffer.from('v10'), nonce, ciphertext, cipher.getAuthTag()]) -} - describe('decryptCookieValueRaw host-key hash prefix', () => { it('decrypts an empty value whose plaintext is only the hash', () => { const encrypted = encryptCbc(hostKeyHash(HOST_KEY)) expect(decryptCookieValueRaw(encrypted, cbcKeyResult, HOST_KEY)).toEqual(Buffer.alloc(0)) }) - - it('decrypts an empty value on the Windows AES-GCM path', () => { - const encrypted = encryptGcm(hostKeyHash(HOST_KEY)) - expect(decryptCookieValueRaw(encrypted, gcmKeyResult, HOST_KEY)).toEqual(Buffer.alloc(0)) - }) }) diff --git a/src/main/browser/document-preview/doc-preview-guest-policy.ts b/src/main/browser/document-preview/doc-preview-guest-policy.ts index fb6ff0a71f0..2795b9562dd 100644 --- a/src/main/browser/document-preview/doc-preview-guest-policy.ts +++ b/src/main/browser/document-preview/doc-preview-guest-policy.ts @@ -66,6 +66,12 @@ export function readDocPreviewGuestBoundGrantId(guest: Electron.WebContents): st return previewGuests.get(guest)?.readBoundGrantId() ?? null } +/** Browser page of the guest's live grant; null before the grant binds or once it is revoked. */ +export function readDocPreviewGuestBoundPageId(guest: Electron.WebContents): string | null { + const grantId = readDocPreviewGuestBoundGrantId(guest) + return (grantId && getDocPreviewGrant(grantId)?.browserPageId) || null +} + /** URL of the guest's committed document; unlike getURL(), pushState cannot rewrite it. */ export function readDocPreviewGuestDocumentUrl(guest: Electron.WebContents): string { return previewGuests.get(guest)?.readDocumentUrl() ?? '' diff --git a/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-policy.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-policy.ts index 1c527c71636..2385d90a432 100644 --- a/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-policy.ts +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-policy.ts @@ -5,10 +5,11 @@ import { BrowserManagerGuestCleanup } from './browser-manager-guest-cleanup' import { allowPageUnload } from '../../navigation/browser-guest-unload-policy' import { installDocPreviewGuestPolicy, - readDocPreviewGuestBoundGrantId + readDocPreviewGuestBoundPageId } from '../../../document-preview/doc-preview-guest-policy' -import { getDocPreviewGrant } from '../../../document-preview/doc-preview-grant-registry' import { setupGuestEscapeForwarding } from '../../input/shortcuts/browser-guest-escape-forwarding' +import { setupGuestShortcutForwarding } from '../../input/shortcuts/browser-guest-shortcut-forwarding' +import { forwardGuestMousePress } from '../../input/browser-guest-mouse-press' import { installGuestDevToolsCloseShortcut } from '../../devtools/browser-guest-devtools-close-shortcut' export abstract class BrowserManagerGuestPolicy extends BrowserManagerGuestCleanup { @@ -92,15 +93,37 @@ export abstract class BrowserManagerGuestPolicy extends BrowserManagerGuestClean host: Electron.WebContents ): void { const disposeDocPolicy = installDocPreviewGuestPolicy(guest, host) + const resolveHost = (): Electron.WebContents | null => (host.isDestroyed() ? null : host) const disposeEscapeForwarding = setupGuestEscapeForwarding({ guest, resolveTarget: () => { - const grantId = readDocPreviewGuestBoundGrantId(guest) - const browserPageId = grantId ? getDocPreviewGrant(grantId)?.browserPageId : undefined + const browserPageId = readDocPreviewGuestBoundPageId(guest) return browserPageId ? { browserPageId, renderer: host } : null }, hasActiveGrabOp: (browserPageId) => this.hasActiveGrabOp(browserPageId) }) + // Why: a focused preview swallows keys, so Orca's window shortcuts (Ctrl+Tab, close tab) are + // forwarded to its own host as for plugin frames; browser-page chords stay with the document. + const disposeShortcutForwarding = setupGuestShortcutForwarding({ + browserTabId: `workspace-doc:${guest.id}`, + guest, + resolveRenderer: resolveHost, + getKeybindings: () => this.settingsResolver?.().keybindings, + browserPage: false + }) + // Why: a press in the preview never reaches the host DOM, so its split stays inactive and + // forwarded shortcuts like Close would act on another split (#22144). Presses only: previews + // have no history listener for the side buttons a release would send. + const reportPress = (_event: Electron.Event, mouse: Electron.MouseInputEvent): void => { + if (mouse.type !== 'mouseDown') { + return + } + const browserPageId = readDocPreviewGuestBoundPageId(guest) + if (browserPageId) { + forwardGuestMousePress(guest, browserPageId, resolveHost, mouse) + } + } + guest.on('before-mouse-event', reportPress) const handleDestroyed = (): void => { this.cleanupGuestPolicyAttachment(guest.id) } @@ -109,9 +132,11 @@ export abstract class BrowserManagerGuestPolicy extends BrowserManagerGuestClean this.policyCleanupByGuestId.set(guest.id, () => { disposeDocPolicy() disposeEscapeForwarding() + disposeShortcutForwarding() try { guest.off('destroyed', handleDestroyed) guest.off('will-prevent-unload', allowPageUnload) + guest.off('before-mouse-event', reportPress) } catch { // guest may already be destroyed } diff --git a/src/main/browser/guest-lifecycle/manager/registration/browser-manager-workspace-doc-shortcuts.test.ts b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-workspace-doc-shortcuts.test.ts new file mode 100644 index 00000000000..bab2aa74f57 --- /dev/null +++ b/src/main/browser/guest-lifecycle/manager/registration/browser-manager-workspace-doc-shortcuts.test.ts @@ -0,0 +1,90 @@ +import { afterEach, describe, expect, it, vi, type Mock } from 'vitest' + +vi.mock('electron', () => ({ + app: { getPath: () => '/downloads' }, + BrowserWindow: { fromWebContents: () => null }, + clipboard: { writeText: vi.fn() }, + shell: { openExternal: vi.fn() }, + Menu: { buildFromTemplate: vi.fn() }, + screen: { getCursorScreenPoint: () => ({ x: 0, y: 0 }) }, + webContents: { fromId: () => null } +})) +vi.mock('../../popups/presentation/popup-origin-bar-window', () => ({ + openPopupWithOriginBar: vi.fn() +})) + +import { buildDocPreviewUrl } from '../../../../../shared/document-preview/doc-preview-scheme' +import { + mintDocPreviewGrant, + revokeAllDocPreviewGrants +} from '../../../document-preview/doc-preview-grant-registry' +import { + DestroyedGuestTestContents, + DestroyedGuestTestManager +} from './browser-manager-destroyed-guest-test-fixture' + +describe('workspace document guest input', () => { + const guests: DestroyedGuestTestContents[] = [] + + function attachDocumentGuest(): { + guest: DestroyedGuestTestContents + send: Mock + } { + const grant = mintDocPreviewGrant({ + owner: { + kind: 'runtime', + environmentId: 'env-1', + worktreeSelector: 'id:worktree-1', + worktreeRoot: '/repo' + }, + root: '/repo', + entryRelativePath: 'page.html', + browserPageId: 'doc-page-1' + }) + const url = buildDocPreviewUrl(grant.id, grant.entryRelativePath) + const guest = Object.assign(new DestroyedGuestTestContents(7), { getURL: () => url }) + const send = vi.fn() + const host = Object.assign(new DestroyedGuestTestContents(5001), { send }) + new DestroyedGuestTestManager().attachGuestPolicies(guest.asWebContents(), null, { + profile: 'workspace-doc', + host: host.asWebContents() + }) + guests.push(guest) + return { guest, send } + } + + afterEach(() => { + for (const guest of guests.splice(0)) { + guest.destroy() + } + revokeAllDocPreviewGrants() + }) + + it('forwards Ctrl+Tab from a focused document preview to its host window', () => { + const { guest, send } = attachDocumentGuest() + guest.emit( + 'before-input-event', + { preventDefault: vi.fn() }, + { + type: 'keyDown', + key: 'Tab', + code: 'Tab', + control: true, + shift: false, + alt: false, + meta: false + } + ) + + expect(send.mock.calls).toEqual([['ui:ctrlTabKeyDown', { shiftKey: false }]]) + }) + + it('reports a press in the preview so its split becomes active', () => { + const { guest, send } = attachDocumentGuest() + guest.emit('before-mouse-event', { preventDefault: vi.fn() }, { type: 'mouseDown', x: 1, y: 1 }) + + expect(send.mock.calls).toEqual([ + ['ui:browserPagePointerDown', { browserPageId: 'doc-page-1' }] + ]) + }) +}) diff --git a/src/main/browser/routing/local-host-partitions/local-ssh-browser-route-target.test.ts b/src/main/browser/routing/local-host-partitions/local-ssh-browser-route-target.test.ts deleted file mode 100644 index 8ddaec3b3eb..00000000000 --- a/src/main/browser/routing/local-host-partitions/local-ssh-browser-route-target.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { requireLocalSshBrowserRouteTarget } from './local-ssh-browser-route' - -const target = { generation: 4 } - -describe('local SSH browser target registration', () => { - it('preserves direct SSH callers that do not supply a deployment fence', () => { - expect(() => requireLocalSshBrowserRouteTarget(target)).not.toThrow() - }) - - it.each([3, 5, '4', null])( - 'refuses a stale or invalid deployment registration: %j', - (generation) => { - expect(() => requireLocalSshBrowserRouteTarget(target, generation)).toThrow( - 'browser_local_route_target_stale' - ) - } - ) - - it('refuses a removed target instead of borrowing another route', () => { - expect(() => requireLocalSshBrowserRouteTarget(undefined, 4)).toThrow( - 'browser_local_route_target_invalid' - ) - }) -}) diff --git a/src/main/claude-usage/claude-usage-automation-attribution.ts b/src/main/claude-usage/claude-usage-automation-attribution.ts index ed083d0eb5b..316f6b53d5f 100644 --- a/src/main/claude-usage/claude-usage-automation-attribution.ts +++ b/src/main/claude-usage/claude-usage-automation-attribution.ts @@ -2,7 +2,7 @@ import type { AutomationRunUsage } from '../../shared/automations/history/automa import type { ClaudeUsagePersistedState } from './types' import { estimateCostUsd } from './claude-model-pricing' import { addBillableTokens, NO_TOKENS, type ClaudeBillableTokens } from './claude-billable-tokens' -import { shouldForceAutomationUsageScan } from '../usage/automation-usage-scan-forcing' +import { shouldForceAutomationUsageScan } from '../usage/provider-lifecycle/automation-usage-scan-forcing' const AUTOMATION_ATTRIBUTION_WINDOW_MS = 5 * 60_000 diff --git a/src/main/claude-usage/claude-usage-report-aggregation.ts b/src/main/claude-usage/claude-usage-report-aggregation.ts index 8d5c5411ff9..f771e0940e7 100644 --- a/src/main/claude-usage/claude-usage-report-aggregation.ts +++ b/src/main/claude-usage/claude-usage-report-aggregation.ts @@ -1,4 +1,4 @@ -import { highestUsageKey } from '../usage/highest-usage-key' +import { highestUsageKey } from '../usage/rollups/highest-usage-key' import type { ClaudeUsageBreakdownKind, ClaudeUsageBreakdownRow, diff --git a/src/main/claude-usage/claude-usage-scope-filters.ts b/src/main/claude-usage/claude-usage-scope-filters.ts index e7ae8bfb1ff..792fdd45c1c 100644 --- a/src/main/claude-usage/claude-usage-scope-filters.ts +++ b/src/main/claude-usage/claude-usage-scope-filters.ts @@ -1,6 +1,9 @@ import type { ClaudeUsageRange, ClaudeUsageScope } from '../../shared/claude-usage-types' import type { ClaudeUsagePersistedState } from './types' -import { getLocalUsageDay, getUsageRangeCutoff } from '../usage/usage-calendar-range' +import { + getLocalUsageDay, + getUsageRangeCutoff +} from '../usage/reporting/range-query/usage-calendar-range' export function getFilteredDaily( state: ClaudeUsagePersistedState, diff --git a/src/main/claude-usage/persisted-source-authority.test.ts b/src/main/claude-usage/persisted-source-authority.test.ts index 394ca9693be..a0ff40dc8c8 100644 --- a/src/main/claude-usage/persisted-source-authority.test.ts +++ b/src/main/claude-usage/persisted-source-authority.test.ts @@ -1,4 +1,4 @@ -import { appendFile, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' @@ -6,17 +6,8 @@ import type { ClaudeUsagePersistedFile, ClaudeUsagePersistedState } from './type import { scanClaudeUsageFiles } from './scanner' import { readClaudeUsageScanFile } from './transcript-record-parser' import { projectClaudeUsageScanFile } from './transcript-usage-projection' -import { parseClaudeUsageReport, serializeClaudeUsageReport } from './persisted-usage-report' -import { - readClaudeUsageSourceCache, - splitClaudeUsageCacheFile, - writeClaudeUsageSourceCache -} from './persisted-source-cache' -import { - compressClaudeUsageSourceText, - decodeClaudeUsageSourceText -} from './source-cache-compression' -import { readUsageSourceCache } from '../usage/usage-source-cache-file' +import { parseClaudeUsageReport } from './persisted-usage-report' +import { splitClaudeUsageCacheFile } from './persisted-source-cache' const { discovered } = vi.hoisted(() => { const discovered: { paths: string[] } = { paths: [] } @@ -28,7 +19,6 @@ vi.mock('./transcript-file-discovery', () => ({ let directory: string let transcript: string -let sourcePath: string function row(input: number): string { return `${JSON.stringify({ @@ -40,10 +30,6 @@ function row(input: number): string { })}\n` } -function ref() { - return { path: sourcePath, schemaVersion: 7, worktreeFingerprint: '[]', reuse: true } -} - function state(file: ClaudeUsagePersistedFile, schemaVersion = 7): ClaudeUsagePersistedState { return { schemaVersion, @@ -70,103 +56,12 @@ async function fixture(large = true): Promise { beforeEach(async () => { directory = await mkdtemp(join(tmpdir(), 'orca-claude-source-authority-')) transcript = join(directory, 'session.jsonl') - sourcePath = join(directory, 'usage-sources.json') discovered.paths = [transcript] }) afterEach(async () => { await rm(directory, { recursive: true, force: true }) }) -it('uses a verified packed restart for exact append corrections', async () => { - const original = await fixture() - await writeClaudeUsageSourceCache(ref(), [original]) - const cached = await readClaudeUsageSourceCache(ref()) - expect(cached.sources).toEqual([original]) - expect(cached.verifiedSources?.has(cached.sources[0])).toBe(true) - await appendFile(transcript, row(150)) - - const resumed = await scanClaudeUsageFiles( - [], - cached.sources, - undefined, - [], - cached.verifiedSources - ) - const cold = await scanClaudeUsageFiles([], [], undefined, []) - - expect(resumed.sessions).toEqual(cold.sessions) - expect(resumed.dailyAggregates).toEqual(cold.dailyAggregates) - expect(resumed.sessions[0]?.turnCount).toBe(1) - expect(resumed.sessions[0]?.totalInputTokens).toBe(150) -}) - -it('compresses large caches losslessly and resumes the same totals after restart', async () => { - const rows = Array.from({ length: 3000 }, (_, index) => - row(index).replace('"request"', `"request-${index}"`) - ).join('') - await writeFile(transcript, rows) - const cold = await scanClaudeUsageFiles([], [], undefined, []) - const mutableRef = ref() - const pending = writeClaudeUsageSourceCache(mutableRef, cold.processedFiles) - mutableRef.path = join(directory, 'different-cache.json') - mutableRef.worktreeFingerprint = '["different-workspace"]' - await pending - await expect(readFile(mutableRef.path)).rejects.toMatchObject({ code: 'ENOENT' }) - const text = await readFile(sourcePath) - expect([...text.subarray(0, 2)]).toEqual([0x1f, 0x8b]) - const decoded = await decodeClaudeUsageSourceText(text) - expect(Buffer.byteLength(text)).toBeLessThan(Buffer.byteLength(decoded)) - const cached = await readClaudeUsageSourceCache(ref()) - expect(cached.sources).toEqual(cold.processedFiles) - expect(cached.verifiedSources?.has(cached.sources[0])).toBe(true) - - await appendFile(transcript, row(4000).replace('"request"', '"request-7"')) - const resumed = await scanClaudeUsageFiles( - [], - cached.sources, - undefined, - [], - cached.verifiedSources - ) - expect(resumed).toEqual(await scanClaudeUsageFiles([], [], undefined, [])) - // Older readers discard the optional resume cache; the separately stored report stays readable. - expect(await readUsageSourceCache(ref())).toEqual([]) -}) - -it('keeps old plain caches readable and rejects compressed content with invalid integrity', async () => { - await writeFile( - transcript, - Array.from({ length: 3000 }, (_, index) => - row(index).replace('"request"', `"request-${index}"`) - ).join('') - ) - const cold = await scanClaudeUsageFiles([], [], undefined, []) - await writeClaudeUsageSourceCache(ref(), cold.processedFiles) - const decoded = await decodeClaudeUsageSourceText(await readFile(sourcePath)) - await writeFile(sourcePath, decoded) - expect((await readClaudeUsageSourceCache(ref())).sources).toEqual(cold.processedFiles) - const report = serializeClaudeUsageReport(state(cold.processedFiles[0])) - const damaged = JSON.parse(decoded) - damaged.sources[0].sessions[0].totalInputTokens++ - await writeFile(sourcePath, await compressClaudeUsageSourceText(JSON.stringify(damaged))) - expect(await readClaudeUsageSourceCache(ref())).toEqual({ sources: [] }) - expect(await parseClaudeUsageReport(report, JSON.parse(report))).toEqual(JSON.parse(report)) -}) - -it('protects tiny source rollups despite their absent resume checkpoint', async () => { - const original = await fixture(false) - expect(original.parseResumeState).toBeNull() - await writeClaudeUsageSourceCache(ref(), [original]) - const saved = JSON.parse(await readFile(sourcePath, 'utf8')) - saved.sources[0].sessions[0].totalInputTokens++ - await writeFile(sourcePath, JSON.stringify(saved)) - - const rejected = await readClaudeUsageSourceCache(ref()) - expect(rejected.sources).toEqual([]) - const rebuilt = await scanClaudeUsageFiles([], rejected.sources, undefined, []) - expect(rebuilt.sessions).toEqual(original.sessions) -}) - it('rejects same-stat direct scanner corruption without a raw-envelope proof', async () => { const original = await fixture() const checkpoint = original.parseResumeState diff --git a/src/main/claude-usage/persisted-source-cache.ts b/src/main/claude-usage/persisted-source-cache.ts index e1c60cec361..1dbe3f126ef 100644 --- a/src/main/claude-usage/persisted-source-cache.ts +++ b/src/main/claude-usage/persisted-source-cache.ts @@ -11,14 +11,14 @@ import { type ClaudeUsageVerifiedSources } from './persisted-projection-validation' import { parseClaudeUsageReport, serializeClaudeUsageReport } from './persisted-usage-report' -import { sealUsageCacheJson, verifyUsageCacheJson } from '../usage/usage-cache-json-integrity' +import { sealUsageCacheJson, verifyUsageCacheJson } from '../usage/cache/usage-cache-json-integrity' import { usageSourceCachePath, writeUsageSourceCacheData, type UsageCacheSplitRequest, type UsageCacheSplitResult, type UsageSourceCacheRef -} from '../usage/usage-source-cache-file' +} from '../usage/cache/usage-source-cache-file' const SOURCE_DOMAIN = 'claude-usage-sources-v1' diff --git a/src/main/claude-usage/persisted-token-columns-store.test.ts b/src/main/claude-usage/persisted-token-columns-store.test.ts deleted file mode 100644 index f97d765aee8..00000000000 --- a/src/main/claude-usage/persisted-token-columns-store.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { readFile, writeFile } from 'node:fs/promises' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { - createPersistedUsageTestFixture, - type PersistedUsageTestFixture -} from './persisted-usage-test-fixture' - -const { getPath } = vi.hoisted(() => ({ getPath: vi.fn<() => string>() })) -vi.mock('electron', () => ({ app: { getPath } })) -vi.mock('../usage/usage-scan-worker-spawn', () => ({ - scanClaudeUsageFilesViaWorker: vi.fn(), - splitUsageCacheFileViaWorker: vi.fn() -})) -vi.mock('./transcript-file-discovery', () => ({ - listClaudeTranscriptFiles: vi.fn(), - claudeProfileTranscriptDirs: vi.fn(() => []) -})) - -let fixture: PersistedUsageTestFixture - -beforeEach(async () => { - fixture = await createPersistedUsageTestFixture(getPath) -}) - -afterEach(async () => { - await fixture.cleanup() -}) - -it.each([ - { name: 'empty', checkpoint: {} }, - { name: 'offset-only', checkpoint: { parsedBytes: 20_000 } }, - { - name: 'unsigned tuples', - checkpoint: { - parsedBytes: 20_000, - lineCount: 1, - boundaryDigest: 'boundary', - headDigest: 'head', - physicalFileId: '1:2', - ownedTokenMaxima: [[100, 10, 0, 20, 5, null]], - projections: [], - encounterOrder: [] - } - } -])( - 'preserves $name legacy checkpoints when enabling and flushing without a scan', - async ({ checkpoint }) => { - const file = { - path: join(fixture.directory, 'legacy.jsonl'), - mtimeMs: 1, - ctimeMs: 2, - physicalFileId: '1:2', - size: 20_000, - lineCount: 1, - sessions: [], - dailyAggregates: [], - ownedDedupeKeys: ['legacy-key'], - hasDeferredClaims: false, - parseResumeState: checkpoint - } - const state = { - schemaVersion: 6, - worktreeFingerprint: '[]', - processedFiles: [file], - sessions: [], - dailyAggregates: [], - scanState: { - enabled: false, - lastScanStartedAt: 1, - lastScanCompletedAt: 2, - lastScanError: null - } - } - await writeFile(fixture.reportPath, JSON.stringify(state)) - const store = fixture.createStore() - await store.setEnabled(true) - await store.flush() - - const report = JSON.parse(await readFile(fixture.reportPath, 'utf8')) - const sidecar = JSON.parse(await readFile(fixture.sourceRef.path, 'utf8')) - expect(report).not.toHaveProperty('processedFiles') - expect(report).not.toHaveProperty('usageIntegrity') - expect(report.schemaVersion).toBe(6) - expect(report.scanState).toEqual({ ...state.scanState, enabled: true }) - expect(sidecar.schemaVersion).toBe(6) - expect(sidecar).not.toHaveProperty('usageIntegrity') - expect(sidecar.sources).toEqual([file]) - expect(sidecar.sources[0]?.parseResumeState).not.toHaveProperty('tokenCodecVersion') - expect(sidecar.sources[0]?.parseResumeState).not.toHaveProperty('ownedTokenColumns') - expect(sidecar.sources[0]?.parseResumeState).not.toHaveProperty('projectionIntegrity') - expect(fixture.scanWorker).not.toHaveBeenCalled() - } -) diff --git a/src/main/claude-usage/persisted-usage-report.ts b/src/main/claude-usage/persisted-usage-report.ts index a5015bf90b4..29e661494bd 100644 --- a/src/main/claude-usage/persisted-usage-report.ts +++ b/src/main/claude-usage/persisted-usage-report.ts @@ -3,7 +3,7 @@ import { hasClaudeUsageProtectedCheckpoint, initializePersistedClaudeUsageProjections } from './persisted-projection-validation' -import { sealUsageCacheJson, verifyUsageCacheJson } from '../usage/usage-cache-json-integrity' +import { sealUsageCacheJson, verifyUsageCacheJson } from '../usage/cache/usage-cache-json-integrity' const REPORT_DOMAIN = 'claude-usage-report-v1' diff --git a/src/main/claude-usage/persisted-usage-test-fixture.ts b/src/main/claude-usage/persisted-usage-test-fixture.ts index 46735e02c99..32b1f4ca370 100644 --- a/src/main/claude-usage/persisted-usage-test-fixture.ts +++ b/src/main/claude-usage/persisted-usage-test-fixture.ts @@ -12,14 +12,14 @@ import { persistClaudeUsageSourceCache } from './persisted-source-cache' import { normalizeClaudeUsageSourceFiles } from './persisted-projection-validation' -import { usageSourceCachePath } from '../usage/usage-source-cache-file' +import { usageSourceCachePath } from '../usage/cache/usage-source-cache-file' import { ClaudeUsageStore, initClaudeUsagePath } from './store' import { listClaudeTranscriptFiles } from './transcript-file-discovery' import { scanClaudeUsageFilesViaWorker, splitUsageCacheFileViaWorker -} from '../usage/usage-scan-worker-spawn' +} from '../usage/scan-worker/usage-scan-worker-spawn' export async function createPersistedUsageTestFixture(getPath: Mock<() => string>) { const directory = await mkdtemp(join(tmpdir(), 'orca-claude-persisted-usage-')) diff --git a/src/main/claude-usage/scanner-long-context.test.ts b/src/main/claude-usage/scanner-long-context.test.ts index f7953e12ea5..e3eb8168a7d 100644 --- a/src/main/claude-usage/scanner-long-context.test.ts +++ b/src/main/claude-usage/scanner-long-context.test.ts @@ -1,11 +1,10 @@ -import { appendFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import type * as NodeOs from 'node:os' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { scanClaudeUsageFiles } from './scanner' import type { ClaudeUsagePersistedFile } from './types' -import { MIN_RESUMABLE_PREFIX_BYTES } from '../usage/jsonl-file-checkpoint' const { homedirMock } = vi.hoisted(() => ({ homedirMock: vi.fn<() => string>() })) @@ -52,9 +51,6 @@ function assistantRow(key: string, model: string, cacheReadTokens: number): stri } // Resume checkpoints require at least MIN_RESUMABLE_PREFIX_BYTES. -function padding(): string { - return `${JSON.stringify({ type: 'user', content: 'x'.repeat(4 * MIN_RESUMABLE_PREFIX_BYTES) })}\n` -} async function scan(previous: ClaudeUsagePersistedFile[] = []): Promise { const { scanClaudeUsageFiles } = await import('./scanner') @@ -86,38 +82,4 @@ describe('Claude usage long-context subsets', () => { expect(byModel.get('claude-sonnet-4-6')?.longContext).toBeUndefined() expect(result.sessions[0]?.locationBreakdown[0]?.longContext?.cacheReadTokens).toBe(100_000) }) - - it('moves a resumed turn into the long-context subset when its usage grows past the threshold', async () => { - await writeFile(transcriptPath, padding() + assistantRow('turn', 'claude-haiku-5-5', 90_000)) - const first = await scan() - expect(first.dailyAggregates[0]?.longContext).toBeUndefined() - const persisted: ClaudeUsagePersistedFile[] = JSON.parse(JSON.stringify(first.processedFiles)) - expect(persisted[0]?.parseResumeState).toBeTruthy() - await appendFile(transcriptPath, assistantRow('turn', 'claude-haiku-5-5', 120_000)) - - const resumed = await scan(persisted) - const cold = await scan() - - expect(resumed.dailyAggregates[0]?.longContext?.cacheReadTokens).toBe(120_000) - expect(resumed.dailyAggregates).toEqual(cold.dailyAggregates) - expect(resumed.sessions).toEqual(cold.sessions) - }) - - it('reparses a file saved by an older projection version', async () => { - await writeFile(transcriptPath, assistantRow('turn', 'claude-haiku-5-5', 120_000)) - const first = await scan() - const legacy = first.processedFiles.map( - ({ projectionVersion: _projectionVersion, ...file }) => ({ - ...file, - dailyAggregates: file.dailyAggregates.map(({ longContext: _longContext, ...row }) => row) - }) - ) - - const rebuilt = await scan(legacy) - - expect(rebuilt.dailyAggregates[0]?.longContext?.cacheReadTokens).toBe(120_000) - expect(rebuilt.processedFiles[0]?.projectionVersion).toBe( - first.processedFiles[0]?.projectionVersion - ) - }) }) diff --git a/src/main/claude-usage/store-checkpoint-persistence.test.ts b/src/main/claude-usage/store-checkpoint-persistence.test.ts deleted file mode 100644 index 160b22315ca..00000000000 --- a/src/main/claude-usage/store-checkpoint-persistence.test.ts +++ /dev/null @@ -1,187 +0,0 @@ -import { appendFile, readFile, rm, writeFile } from 'node:fs/promises' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { projectClaudeUsageScanFile } from './transcript-usage-projection' -import { readClaudeUsageScanFile } from './transcript-record-parser' -import { - createPersistedUsageTestFixture, - type PersistedUsageTestFixture -} from './persisted-usage-test-fixture' - -const { getPath } = vi.hoisted(() => ({ getPath: vi.fn<() => string>() })) -vi.mock('electron', () => ({ app: { getPath } })) -vi.mock('../usage/usage-scan-worker-spawn', () => ({ - scanClaudeUsageFilesViaWorker: vi.fn(), - splitUsageCacheFileViaWorker: vi.fn() -})) -vi.mock('./transcript-file-discovery', () => ({ - listClaudeTranscriptFiles: vi.fn(), - claudeProfileTranscriptDirs: vi.fn(() => []) -})) - -let fixture: PersistedUsageTestFixture -const KEY_COUNT = 1024 - -beforeEach(async () => { - fixture = await createPersistedUsageTestFixture(getPath) -}) - -afterEach(async () => { - await fixture.cleanup() -}) - -it('persists every distinct maximum within the sidecar byte budget and resumes an older indented cache', async () => { - await writeFile( - fixture.transcript, - Array.from({ length: KEY_COUNT }, (_, index) => fixture.row(index)).join('') - ) - const initial = await fixture.project() - const store = fixture.createStore() - await store.setEnabled(true) - await store.refresh(true) - await store.flush() - - const report = JSON.parse(await readFile(fixture.reportPath, 'utf8')) - const sourceText = await readFile(fixture.sourceRef.path, 'utf8') - const sidecar = JSON.parse(sourceText) - expect(report.schemaVersion).toBe(7) - expect(report).not.toHaveProperty('processedFiles') - expect(report.sessions).toEqual(initial.sessions) - expect(Buffer.byteLength(sourceText)).toBeLessThan(100_000) - expect(sidecar.schemaVersion).toBe(7) - expect(sidecar.sources[0]?.parseResumeState).not.toHaveProperty('ownedTokenMaxima') - expect(sidecar.sources[0]?.parseResumeState.tokenCodecVersion).toBe(1) - expect(await fixture.decodedSources()).toEqual([initial]) - expect(initial.ownedDedupeKeys).toHaveLength(KEY_COUNT) - expect(initial.parseResumeState?.ownedTokenMaxima).toHaveLength(KEY_COUNT) - - await rm(fixture.sourceRef.path) - await writeFile(fixture.reportPath, JSON.stringify(fixture.state([initial]), null, 2)) - await appendFile(fixture.transcript, fixture.row(0, true)) - const restarted = fixture.createStore() - await restarted.whenLoaded() - const migrated = JSON.parse(await readFile(fixture.sourceRef.path, 'utf8')) - expect(migrated.schemaVersion).toBe(7) - expect(migrated.sources[0]?.parseResumeState.tokenCodecVersion).toBe(1) - expect(await fixture.decodedSources()).toEqual([initial]) - await restarted.refresh(true) - await restarted.flush() - - const afterRestart = JSON.parse(await readFile(fixture.reportPath, 'utf8')) - const cold = await fixture.project() - expect(afterRestart.schemaVersion).toBe(7) - expect(afterRestart).not.toHaveProperty('processedFiles') - expect(afterRestart.sessions).toEqual(cold.sessions) - expect(afterRestart.dailyAggregates).toEqual(cold.dailyAggregates) - expect(await fixture.decodedSources()).toEqual([cold]) - expect(cold.ownedDedupeKeys).toHaveLength(KEY_COUNT) - expect(cold.sessions[0]?.sessionId).toBe('original-session') - expect(cold.sessions[0]?.turnCount).toBe(KEY_COUNT) - expect(cold.parseResumeState?.ownedTokenMaxima[0]).toEqual([2000, 55, 5, 15, 3, 0]) -}) - -it('hides invalid saved totals until a refresh rebuilds the owner and its deferred fork', async () => { - const initial = await fixture.writeResumable() - const forkPath = join(fixture.directory, 'fork.jsonl') - await writeFile(forkPath, await readFile(fixture.transcript, 'utf8')) - fixture.transcripts.push(forkPath) - const fork = await projectClaudeUsageScanFile( - await readClaudeUsageScanFile(forkPath), - new Map(), - () => false - ) - expect(fork.hasDeferredClaims).toBe(true) - const state = fixture.state([initial, fork]) - const maxima = initial.parseResumeState?.ownedTokenMaxima[0] - if (!maxima) { - throw new Error('Expected a resumable owner fixture.') - } - maxima[0]-- - await writeFile(fixture.reportPath, JSON.stringify(state)) - - const store = fixture.createStore() - await store.whenLoaded() - expect(await fixture.decodedSources()).toEqual([]) - expect(store.getSnapshot('all', 'all')).toMatchObject({ - summary: { sessions: 0, turns: 0, inputTokens: 0 }, - daily: [], - recentSessions: [], - scanState: { - enabled: true, - hasAnyClaudeData: false, - lastScanCompletedAt: null, - lastScanError: 'Saved usage totals could not be validated. Refresh to rebuild them.' - } - }) - await store.refresh(false) - await store.flush() - expect(store.getSnapshot('all', 'all')).toMatchObject({ - summary: { sessions: 1, turns: 1, inputTokens: 1000 }, - scanState: { enabled: true, hasAnyClaudeData: true, lastScanError: null } - }) - const rebuilt = await fixture.decodedSources() - expect(rebuilt).toHaveLength(2) - expect(rebuilt.flatMap((file) => file.ownedDedupeKeys)).toHaveLength(1) - expect(rebuilt.some((file) => file.hasDeferredClaims)).toBe(true) -}) - -it('reconstructs duplicated global totals from validated file projections on load', async () => { - const initial = await fixture.writeResumable() - const state = fixture.state([initial]) - const session = state.sessions[0] - const daily = state.dailyAggregates[0] - if (!session || !daily) { - throw new Error('Expected saved global totals.') - } - session.totalInputTokens++ - daily.inputTokens++ - await writeFile(fixture.reportPath, JSON.stringify(state)) - - const store = fixture.createStore() - await store.whenLoaded() - expect(store.getSnapshot('all', 'all')).toMatchObject({ - summary: { sessions: 1, turns: 1, inputTokens: 1000 }, - daily: [{ inputTokens: 1000 }], - scanState: { enabled: true, lastScanCompletedAt: state.scanState.lastScanCompletedAt } - }) - await store.refresh(false) - expect(fixture.scanWorker).not.toHaveBeenCalled() -}) - -it.each(['nonArray', 'nullEntry', 'unsignedRollup'] as const)( - 'preserves tracking when malformed %s cache records cannot be validated', - async (malformation) => { - const initial = await fixture.writeResumable() - const state = fixture.state([initial]) - const malformedFiles = - malformation === 'nonArray' - ? null - : malformation === 'nullEntry' - ? [initial, null] - : [ - initial, - { - ...initial, - parseResumeState: null, - sessions: [{ ...initial.sessions[0], locationBreakdown: null }] - } - ] - await writeFile( - fixture.reportPath, - JSON.stringify({ ...state, processedFiles: malformedFiles }) - ) - - const store = fixture.createStore() - await store.whenLoaded() - expect(store.getSnapshot('all', 'all')).toMatchObject({ - summary: { sessions: 0, turns: 0 }, - daily: [], - scanState: { - enabled: true, - hasAnyClaudeData: false, - lastScanCompletedAt: null, - lastScanError: 'Saved usage totals could not be validated. Refresh to rebuild them.' - } - }) - } -) diff --git a/src/main/claude-usage/store-source-authority.test.ts b/src/main/claude-usage/store-source-authority.test.ts deleted file mode 100644 index 241ab4f1a01..00000000000 --- a/src/main/claude-usage/store-source-authority.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { appendFile, readFile, writeFile } from 'node:fs/promises' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { UsageCacheSnapshotWriter } from '../usage/usage-cache-snapshot-writer' -import { readClaudeUsageSourceCache, writeClaudeUsageSourceCache } from './persisted-source-cache' -import { serializeClaudeUsageReport } from './persisted-usage-report' -import { - createPersistedUsageTestFixture, - type PersistedUsageTestFixture -} from './persisted-usage-test-fixture' - -const { getPath } = vi.hoisted(() => ({ getPath: vi.fn<() => string>() })) -vi.mock('electron', () => ({ app: { getPath } })) -vi.mock('../usage/usage-scan-worker-spawn', () => ({ - scanClaudeUsageFilesViaWorker: vi.fn(), - splitUsageCacheFileViaWorker: vi.fn() -})) -vi.mock('./transcript-file-discovery', () => ({ - listClaudeTranscriptFiles: vi.fn(), - claudeProfileTranscriptDirs: vi.fn(() => []) -})) - -let fixture: PersistedUsageTestFixture - -beforeEach(async () => { - fixture = await createPersistedUsageTestFixture(getPath) -}) - -afterEach(async () => { - await fixture.cleanup() -}) - -it('keeps a newer source generation when an earlier report migration could not be written', async () => { - const original = await fixture.writeResumable() - const inline = fixture.state([original]) - await writeFile(fixture.reportPath, JSON.stringify(inline)) - vi.spyOn(UsageCacheSnapshotWriter.prototype, 'write').mockRejectedValueOnce( - new Error('report migration write failed') - ) - const first = fixture.createStore() - await first.whenLoaded() - expect(JSON.parse(await readFile(fixture.reportPath, 'utf8'))).toEqual(inline) - expect(await fixture.decodedSources()).toEqual([original]) - - await appendFile(fixture.transcript, fixture.row(0, true)) - const updated = await fixture.project() - await writeClaudeUsageSourceCache(fixture.sourceRef, [updated]) - const warmSourceText = await readFile(fixture.sourceRef.path, 'utf8') - const restarted = fixture.createStore() - await restarted.whenLoaded() - expect(await readFile(fixture.sourceRef.path, 'utf8')).toBe(warmSourceText) - expect(await fixture.decodedSources()).toEqual([updated]) - expect(restarted.getSnapshot('all', 'all').summary.inputTokens).toBe(1000) - await restarted.refresh(true) - await restarted.flush() - expect(await fixture.decodedSources()).toEqual([updated]) - expect(restarted.getSnapshot('all', 'all').summary).toMatchObject({ turns: 1, inputTokens: 2000 }) -}) - -it('preserves a disabled inline cache through worker failure and preference writes', async () => { - const original = await fixture.writeResumable() - const inline = fixture.state([original]) - inline.scanState.enabled = false - await writeFile(fixture.reportPath, JSON.stringify(inline)) - fixture.splitWorker.mockRejectedValue(new Error('worker unavailable')) - vi.spyOn(console, 'warn').mockImplementation(() => {}) - - const store = fixture.createStore() - await store.whenLoaded() - expect(store.getSnapshot('all', 'all')).toMatchObject({ - summary: { inputTokens: 1000 }, - scanState: { enabled: false } - }) - await store.setEnabled(true) - await store.flush() - expect(JSON.parse(await readFile(fixture.reportPath, 'utf8'))).toEqual({ - ...inline, - scanState: { ...inline.scanState, enabled: true } - }) - expect(fixture.scanWorker).not.toHaveBeenCalled() - expect((await readClaudeUsageSourceCache(fixture.sourceRef)).sources).toEqual([]) - - await store.refresh(true) - await store.flush() - const report = JSON.parse(await readFile(fixture.reportPath, 'utf8')) - expect(report.schemaVersion).toBe(7) - expect(report).not.toHaveProperty('processedFiles') - expect(report.scanState.enabled).toBe(true) - expect(await fixture.decodedSources()).toEqual([original]) -}) - -it('rejects an unsigned schema7 tiny-file source without hiding its valid report', async () => { - await writeFile(fixture.transcript, fixture.row(0)) - const original = await fixture.project() - expect(original.parseResumeState).toBeNull() - await writeClaudeUsageSourceCache(fixture.sourceRef, [original]) - await writeFile(fixture.reportPath, serializeClaudeUsageReport(fixture.state([original], 7))) - const unsigned = JSON.parse(await readFile(fixture.sourceRef.path, 'utf8')) - delete unsigned.usageIntegrity - unsigned.sources[0].sessions[0].totalInputTokens = 9999 - unsigned.sources[0].dailyAggregates[0].inputTokens = 9999 - await writeFile(fixture.sourceRef.path, JSON.stringify(unsigned)) - expect((await readClaudeUsageSourceCache(fixture.sourceRef)).sources).toEqual([]) - - const store = fixture.createStore() - await store.whenLoaded() - expect(store.getSnapshot('all', 'all').summary.inputTokens).toBe(1000) - await store.refresh(true) - await store.flush() - expect(await fixture.decodedSources()).toEqual([original]) - expect(store.getSnapshot('all', 'all').summary).toMatchObject({ turns: 1, inputTokens: 1000 }) -}) - -it('rejects a source cache attributed to a different worktree fingerprint', async () => { - const original = await fixture.writeResumable() - await writeClaudeUsageSourceCache( - { ...fixture.sourceRef, worktreeFingerprint: '["other-worktree"]' }, - [original] - ) - await writeFile(fixture.reportPath, serializeClaudeUsageReport(fixture.state([original], 7))) - expect((await readClaudeUsageSourceCache(fixture.sourceRef)).sources).toEqual([]) - const store = fixture.createStore() - await store.whenLoaded() - await store.refresh(true) - await store.flush() - expect(await fixture.decodedSources()).toEqual([original]) - expect(store.getSnapshot('all', 'all').summary.inputTokens).toBe(1000) -}) diff --git a/src/main/claude-usage/store.test.ts b/src/main/claude-usage/store.test.ts deleted file mode 100644 index 7f3cf203f68..00000000000 --- a/src/main/claude-usage/store.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { ClaudeUsagePersistedState } from './types' - -const { getPathMock } = vi.hoisted(() => ({ - getPathMock: vi.fn(() => '/tmp/orca-test-userdata') -})) - -vi.mock('electron', () => ({ - app: { - getPath: getPathMock - } -})) - -vi.mock('../usage/usage-scan-worker-spawn', () => ({ - scanClaudeUsageFilesViaWorker: vi.fn(), - splitUsageCacheFileViaWorker: vi.fn() -})) - -import { ClaudeUsageStore, initClaudeUsagePath } from './store' -import { scanClaudeUsageFilesViaWorker } from '../usage/usage-scan-worker-spawn' - -function createBackingStore(): ConstructorParameters[0] { - return { - getRepos: () => [], - getAllWorktreeMeta: () => ({}) - } -} - -function createStoreWithState(state: Partial): ClaudeUsageStore { - const store = new ClaudeUsageStore(createBackingStore()) - - ;(store as unknown as { state: ClaudeUsagePersistedState }).state = { - schemaVersion: 1, - worktreeFingerprint: null, - processedFiles: [], - sessions: [], - dailyAggregates: [], - scanState: { - enabled: false, - lastScanStartedAt: null, - lastScanCompletedAt: null, - lastScanError: null - }, - ...state - } - - return store -} - -function createWorktreeUsageSession(worktreeId: string) { - const tokens = { - turnCount: 1, - inputTokens: 1000, - outputTokens: 500, - cacheReadTokens: 200, - cacheWriteTokens: 100, - cacheWrite1hTokens: 0 - } - return { - sessionId: 'session-1', - firstTimestamp: '2026-04-09T15:00:00.000Z', - lastTimestamp: '2026-04-09T15:05:00.000Z', - model: 'claude-sonnet-4-6', - lastCwd: '/workspace/repo-a', - lastGitBranch: 'feature/a', - primaryWorktreeId: worktreeId, - primaryRepoId: 'repo-1', - totalInputTokens: 1000, - totalOutputTokens: 500, - totalCacheReadTokens: 200, - totalCacheWriteTokens: 100, - totalCacheWrite1hTokens: 0, - ...tokens, - locationBreakdown: [ - { - locationKey: `worktree:${worktreeId}`, - projectLabel: 'Repo A', - repoId: 'repo-1', - worktreeId, - ...tokens - } - ] - } -} - -describe('ClaudeUsageStore', () => { - let tempUserData: string - - beforeEach(() => { - tempUserData = mkdtempSync(join(tmpdir(), 'orca-claude-usage-store-')) - getPathMock.mockReturnValue(tempUserData) - initClaudeUsagePath() - vi.mocked(scanClaudeUsageFilesViaWorker).mockReset() - vi.mocked(scanClaudeUsageFilesViaWorker).mockResolvedValue({ - sessions: [], - dailyAggregates: [] - }) - vi.useFakeTimers() - vi.setSystemTime(new Date('2026-04-09T12:00:00.000-04:00')) - }) - - afterEach(() => { - vi.useRealTimers() - rmSync(tempUserData, { recursive: true, force: true }) - }) - - it('joins a scan that is already in flight when the run finished before it started', async () => { - const worktreeId = 'repo-1::/workspace/repo-a' - const store = createStoreWithState({ - scanState: { - enabled: true, - lastScanStartedAt: null, - lastScanCompletedAt: null, - lastScanError: null - } - }) - // Prime the worktree fingerprint so an unforced refresh can return early. - vi.mocked(scanClaudeUsageFilesViaWorker).mockResolvedValue({ - sessions: [], - dailyAggregates: [] - }) - await store.refresh(true) - - const completedAt = Date.now() + 10_000 - vi.setSystemTime(new Date(completedAt + 1_000)) - - let startScan = () => {} - let finishScan = () => {} - const scanStarted = new Promise((resolve) => { - startScan = resolve - }) - const scanFinished = new Promise((resolve) => { - finishScan = resolve - }) - vi.mocked(scanClaudeUsageFilesViaWorker).mockImplementationOnce(async () => { - startScan() - await scanFinished - return { - sessions: [createWorktreeUsageSession(worktreeId)], - dailyAggregates: [] - } - }) - - const inFlight = store.refresh(true) - await scanStarted - - const usage = store.getAutomationRunUsage({ - worktreeId, - terminalSessionId: 'session-1', - startedAt: completedAt - 60_000, - completedAt - }) - finishScan() - await inFlight - - expect((await usage).status).toBe('known') - expect((await usage).providerSessionId).toBe('session-1') - }) -}) diff --git a/src/main/claude-usage/store.ts b/src/main/claude-usage/store.ts index f2dc5d850f2..5272a268e19 100644 --- a/src/main/claude-usage/store.ts +++ b/src/main/claude-usage/store.ts @@ -1,4 +1,4 @@ -import { claudeTokenSessions } from '../usage/agent-token-usage' +import { claudeTokenSessions } from '../usage/reporting/token-usage/agent-token-usage' import { app } from 'electron' import { join } from 'node:path' import type { @@ -17,8 +17,8 @@ import type { ClaudeUsagePersistedState } from './types' import { scanClaudeUsageFilesViaWorker, splitUsageCacheFileViaWorker -} from '../usage/usage-scan-worker-spawn' -import { UsageProviderStoreLifecycle } from '../usage/usage-provider-store-lifecycle' +} from '../usage/scan-worker/usage-scan-worker-spawn' +import { UsageProviderStoreLifecycle } from '../usage/provider-lifecycle/usage-provider-store-lifecycle' import { buildBreakdown, buildDaily, buildSummary } from './claude-usage-report-aggregation' import { buildRecentSessions } from './claude-usage-session-rows' import type { AutomationUsageLookupInput } from './claude-usage-automation-attribution' diff --git a/src/main/claude-usage/transcript-record-parser.ts b/src/main/claude-usage/transcript-record-parser.ts index 187e34dbae6..0094e5bbecd 100644 --- a/src/main/claude-usage/transcript-record-parser.ts +++ b/src/main/claude-usage/transcript-record-parser.ts @@ -1,5 +1,5 @@ import { basename } from 'node:path' -import { readJsonlFileSnapshot } from '../usage/jsonl-file-snapshot' +import { readJsonlFileSnapshot } from '../usage/source-input/jsonl/jsonl-file-snapshot' import { createReadStream } from 'node:fs' import { createInterface } from 'node:readline' import type { @@ -7,7 +7,7 @@ import type { ClaudeUsageParsedTurn, ClaudeUsageProcessedFile } from './types' -import { readJsonlLinesFromOffset } from '../usage/jsonl-line-offsets' +import { readJsonlLinesFromOffset } from '../usage/source-input/jsonl/jsonl-line-offsets' import { buildJsonlFileCheckpoint, jsonlPhysicalFileId, @@ -15,7 +15,7 @@ import { resolveJsonlFileCheckpoint, validateJsonlFileReader, type JsonlFileCheckpoint -} from '../usage/jsonl-file-checkpoint' +} from '../usage/source-input/jsonl/jsonl-file-checkpoint' type ClaudeUsageSourceRecord = { type?: string diff --git a/src/main/claude-usage/types.ts b/src/main/claude-usage/types.ts index ea6884bbc83..fbdbb3b1ce2 100644 --- a/src/main/claude-usage/types.ts +++ b/src/main/claude-usage/types.ts @@ -106,7 +106,7 @@ export type ClaudeUsageAttributedTurn = ClaudeUsageParsedTurn & { repoId: string | null worktreeId: string | null } -import type { JsonlFileCheckpoint } from '../usage/jsonl-file-checkpoint' +import type { JsonlFileCheckpoint } from '../usage/source-input/jsonl/jsonl-file-checkpoint' export type ClaudeUsageTokenTotals = Pick< ClaudeUsageParsedTurn, diff --git a/src/main/claude/claude-agent-sdk-exit-proof-identity.test.ts b/src/main/claude/claude-agent-sdk-exit-proof-identity.test.ts index 1aa589666b1..893e32b960f 100644 --- a/src/main/claude/claude-agent-sdk-exit-proof-identity.test.ts +++ b/src/main/claude/claude-agent-sdk-exit-proof-identity.test.ts @@ -1,29 +1,9 @@ import { describe, expect, it, vi } from 'vitest' -import type { DescendantSnapshot } from '../pty/process-retirement/pty-descendant-termination' + import { collectDescendantRows } from '../pty/process-retirement/pty-descendant-termination' import { createClaudeChildTreeReaper } from './claude-agent-sdk-exit-proof' -import { mergeClaudeDescendantSnapshots } from './claude-child-tree-snapshot' - -function posixSnapshot(capturedAtMs: number): DescendantSnapshot { - return { - root: { pid: 100, startedAt: 'Mon Jan 1 00:00:00 2026' }, - rootPgid: 100, - descendants: [{ pid: 200, ppid: 100, pgid: 100, startedAt: 'Mon Jan 1 00:00:01 2026' }], - capturedAtMs - } -} describe('Claude child root identity', () => { - it('keeps a retained row boundary when a refresh observes no new descendants', () => { - const previous = posixSnapshot(1_700_000_000_900) - const next = posixSnapshot(1_700_000_002_100) - - expect(mergeClaudeDescendantSnapshots(previous, next)).toEqual({ - ...next, - capturedAtMsByPid: { '200': previous.capturedAtMs } - }) - }) - it('rejects mixed old and recycled root rows instead of making the tree killable', async () => { const child = { pid: 100, kill: vi.fn(() => true) } const terminateDescendants = vi.fn(async () => 'exited' as const) diff --git a/src/main/claude/claude-stream-json-exit-error.test.ts b/src/main/claude/claude-stream-json-exit-error.test.ts deleted file mode 100644 index 935f93f3d6b..00000000000 --- a/src/main/claude/claude-stream-json-exit-error.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { readFileSync } from 'node:fs' -import { expect, it } from 'vitest' -import { - claudeStartupResultError, - claudeStreamJsonExitError -} from './claude-stream-json-exit-error' -import { providerStartupFailureFact } from '../native-chat/agent-session-wire/startup/structured-agent-session-failure-text' -import { claudeStartFailure } from './claude-startup-failure' - -const retryableStructuredAgentSessionStart = (error: unknown): boolean => - claudeStartFailure(error).retry === 'safe' - -const frame = JSON.parse( - readFileSync(new URL('./__fixtures__/claude-missing-conversation.jsonl', import.meta.url), 'utf8') -) - -it('treats the recorded missing-conversation exit as an explained final refusal', () => { - const error = claudeStreamJsonExitError(frame.errors[0], { - code: 1, - signal: null, - processless: false - }) - expect(providerStartupFailureFact(error)).toMatchObject({ - kind: 'savedConversationMissing', - detail: { text: expect.stringContaining(frame.errors[0]), audience: 'log' } - }) - expect(retryableStructuredAgentSessionStart(error)).toBe(false) -}) - -it('reads the same refusal from the recorded result, and makes other startup results final', () => { - const refusal = claudeStartupResultError(frame) - expect(providerStartupFailureFact(refusal)).toEqual({ - kind: 'savedConversationMissing', - detail: { text: frame.errors[0], audience: 'log' } - }) - expect(retryableStructuredAgentSessionStart(refusal)).toBe(false) - const generic = claudeStartupResultError({ ...frame, errors: ['managed settings failed'] }) - expect(providerStartupFailureFact(generic)).toMatchObject({ - kind: 'startFailed', - detail: { text: 'managed settings failed', audience: 'log' } - }) - expect(retryableStructuredAgentSessionStart(generic)).toBe(false) -}) diff --git a/src/main/claude/claude-transcript-catch-up.test.ts b/src/main/claude/claude-transcript-catch-up.test.ts index 4566844d847..e27ba39f354 100644 --- a/src/main/claude/claude-transcript-catch-up.test.ts +++ b/src/main/claude/claude-transcript-catch-up.test.ts @@ -1,34 +1,11 @@ import './claude-conversation-worker.test-fixture' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session/journal/agent-session-journal-types' + import { describe, expect, it, vi } from 'vitest' import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' -import { - isStructuredRewindTarget, - structuredRewindCut -} from '../native-chat/agent-session-wire/rewind/structured-rewind-cut' -import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import { readAgentSessionHistory } from '../native-chat/agent-session-wire/publication/history/agent-session-history-page' -import { projectJournalBatch } from '../native-chat/agent-session-wire/publication/history/agent-session-journal-batch' -import { - replacePage, - mergeItems -} from '../../shared/agent-session/view/structured-agent-session-history-state' -import { AgentJournalRenderItemSchema } from '../../shared/agent-session/journal/agent-session-journal-schemas' -import { agentSessionSendBodyFingerprint } from '../../shared/agent-session/requests/structured-agent-session-send-mutation' -import { dispatchClaudeTurn } from './structured/claude-structured-dispatch' -import { claudePromptUuidForSubmission } from './structured/claude-structured-session-id' -import { - childExited, - sessionFor, - userMessage -} from './structured/claude-structured-dispatch-test-support' + import { SESSION, SID, - prompt, - reply, - attachment, - bookkeeping, chatTurn, outsideTurn, chat @@ -37,272 +14,6 @@ import { import * as transcriptTail from './claude-transcript-tail' describe('Claude chat catch-up', () => { - it.each([false, true])( - 'recognizes an unacknowledged local prompt; equal external input: %s', - async (outside) => { - const c = await chat() - await c.live() - const body = userMessage([{ type: 'text', text: 'same prompt' }]) - const clientMessageId = 'unacknowledged' - await c.journal.appendSubmission({ - clientMessageId, - body, - fence: 1, - payloadFingerprint: agentSessionSendBodyFingerprint(SESSION, body) - }) - const send = vi.fn().mockResolvedValue(undefined) - const session = sessionFor(send) - session.providerSessionId = SID - await dispatchClaudeTurn(session, { sessionId: SESSION, clientMessageId, body }) - const uuid = String(send.mock.calls[0]![0].uuid) - childExited(session) - await c.journal.resolveDispatch({ - clientMessageId, - fence: 1, - state: 'unknown', - reason: 'provider_closed_before_acknowledgement' - }) - const before = c.journal.snapshot() - await c.journal.close() - const reopened = await c.replay() - c.deferred.bind({ journal: reopened, fence: 1, publish: () => {} }) - const queued = { - ...attachment('queued', 'a1'), - attachment: { - type: 'queued_command', - source_uuid: uuid, - commandMode: 'prompt', - origin: { kind: 'human' }, - humanTurn: true, - prompt: 'same prompt' - } - } - await c.write([ - ...chatTurn, - outside ? queued : prompt(uuid, 'a1', 'same prompt', 3), - reply( - 'recovered', - outside ? 'queued' : uuid, - 'msg_recovered', - { type: 'text', text: 'reply' }, - 4 - ), - ...(outside ? [prompt('external', 'recovered', 'same prompt', 5)] : []) - ]) - expect(await c.open('a1')).toBe(true) - const after = reopened.snapshot() - expect( - after.items - .filter((item) => item.body.kind !== 'turn') - .map((item) => (item.body.kind === 'message' ? item.body.role : item.body.kind)) - ).toEqual(['user', 'assistant', 'user', 'status', 'assistant', ...(outside ? ['user'] : [])]) - expect(after.submissions).toEqual(before.submissions) - expect(reopened.receiptFor(clientMessageId)).toBeNull() - const key = agentJournalItemKey({ provider: 'claude', sessionId: SID, uuid }) - expect(reopened.canonicalItemId(key)).toBe(key) - expect( - structuredRewindCut(reopened, { - itemId: agentJournalItemKey({ provider: 'orca', clientMessageId }), - provider: 'claude', - nativeId: SID - }) - ).toBeNull() - expect(await c.open('a1')).toBe(true) - expect(reopened.snapshot()).toEqual(after) - expect((await c.replay()).snapshot()).toEqual(after) - expect(c.warn).not.toHaveBeenCalled() - } - ) - - it.each(['a1', 'missing-parent'])( - 'keeps an unresolved queued prompt visible without inventing a turn after %s', - async (parent) => { - const c = await chat() - await c.live() - await c.journal.appendSubmission({ - clientMessageId: 'new-native-send', - body: { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'new native request' }] - }, - payloadFingerprint: 'new-native-send', - handoverRecorded: true, - fence: 1 - }) - await c.journal.resolveDispatch({ - clientMessageId: 'new-native-send', - state: 'pending', - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const submissions = c.journal.snapshot().submissions - const cursor = c.journal.cursor() - await c.write([ - ...chatTurn, - { - ...attachment('queued-row', parent), - attachment: { - type: 'queued_command', - source_uuid: 'cmd-1', - commandMode: 'prompt', - origin: { kind: 'human' }, - humanTurn: true, - prompt: 'follow up' - } - } - ]) - const key = agentJournalItemKey({ provider: 'claude', sessionId: SID, uuid: 'cmd-1' }) - expect(await c.open('a1')).toBe(true) - const held = c.journal.snapshot().items - expect(c.rows().filter((row) => row === 'user:follow up')).toHaveLength(1) - expect(c.journal.item(key)?.turnScope).toEqual({ kind: 'unknown' }) - expect(isStructuredRewindTarget(c.journal, key)).toBe(false) - expect(held.filter((row) => row.body.kind === 'turn')).toHaveLength(1) - expect(await c.open('a1')).toBe(true) - expect(c.journal.snapshot().items).toEqual(held) - const beforeReplay = c.journal.item(key) - const reopened = await c.replay() - expect(reopened.item(key)).toEqual(beforeReplay) - expect(isStructuredRewindTarget(reopened, key)).toBe(false) - const page = readAgentSessionHistory(reopened, { sessionId: SESSION, direction: 'tail' }) - const delta = reopened.readSince(cursor) - if (!page.ok || !delta.ok) { - throw new Error('history unavailable') - } - const batch = projectJournalBatch({ - rows: delta.rows, - snapshot: reopened.snapshot(), - afterSequence: cursor.sequence - }) - if (!batch.ok) { - throw new Error('batch unavailable') - } - const snapshotClient = replacePage(page.page, 1) - const liveClient = mergeItems([], batch.batch.items, []) - expect(snapshotClient.items.find((item) => item.itemId === key)).toEqual(c.journal.item(key)) - expect(liveClient.find((item) => item.itemId === key)).toEqual(c.journal.item(key)) - // The open wire schema used by older readers preserves the new scope and message content. - expect( - AgentJournalRenderItemSchema.parse(JSON.parse(JSON.stringify(c.journal.item(key)))) - ).toMatchObject({ turnScope: { kind: 'unknown' }, body: { role: 'user' } }) - - await c.write([ - reply('a2', 'queued-row', 'msg_b', { type: 'text', text: 'follow up answer' }, 4), - prompt('p3', 'a2', 'next request', 5), - reply('a3', 'p3', 'msg_c', { type: 'text', text: 'next answer' }, 6) - ]) - expect(await c.open('a1')).toBe(true) - const items = c.journal.snapshot().items - expect(c.journal.item(key)).toEqual(held.find((row) => row.itemId === key)) - const resumed = items.find((row) => row.body.kind === 'turn' && row.body.turnId === 'a2') - expect(resumed?.body).toMatchObject({ userItemId: resumed?.itemId }) - const opener = agentJournalItemKey({ provider: 'claude', sessionId: SID, uuid: 'p3' }) - expect(isStructuredRewindTarget(c.journal, opener)).toBe(true) - expect(c.journal.snapshot().submissions).toEqual(submissions) - expect(c.rows().filter((row) => row === 'user:follow up')).toHaveLength(1) - expect(c.warn).not.toHaveBeenCalled() - const cut = structuredRewindCut(c.journal, { - itemId: opener, - provider: 'claude', - nativeId: SID - }) - if (!cut) { - throw new Error('ordinary rewind unavailable') - } - await c.journal.replaceEpochItems('handle_forked', 1, cut.kept) - expect(c.journal.item(key)?.turnScope).toEqual({ kind: 'unknown' }) - expect((await c.replay()).item(key)?.turnScope).toEqual({ kind: 'unknown' }) - } - ) - - it.each([ - ['-work', '/work'], - ['-work-caf-', '/work/cafe\u0301'], - ['-old-work', '/moved-work'] - ] as const)( - 'uses the selected-home bucket, retaining moved-project fallback: %s', - async (project, cwd) => { - const c = await chat(project, cwd) - await c.write([...chatTurn, ...outsideTurn]) - expect(await c.open('a1')).toBe(true) - expect(c.rows()).toContain('assistant:answer 2') - } - ) - - it('never leaves a turn it imports running when its reply was already saved', async () => { - // An update killed the chat after Claude saved its reply but before the prompt's echo. - const c = await chat() - await c.live({ interrupted: true }) - const saved = new Set(c.journal.snapshot().items.map((item) => item.itemId)) - await c.write([ - prompt('leaf', null, 'earlier request', 0), - prompt('unechoed', 'leaf', 'ask 1', 1), - reply('a1', 'unechoed', 'msg_a', { type: 'text', text: 'answer 1' }, 2) - ]) - expect(await c.open('leaf')).toBe(true) - const imported = c.journal - .snapshot() - .items.filter((item) => item.body.kind === 'turn' && !saved.has(item.itemId)) - expect(imported).toHaveLength(1) - // It ends where it opened: in the thread, not inside the saved turn its reply matched. - expect(imported[0]).toMatchObject({ - body: { state: 'completed' }, - turnScope: { kind: 'thread' } - }) - }) - - it('completes interrupted text and a result-only tool once at their original positions', async () => { - const c = await chat() - await c.live({ - interrupted: true, - tool: true, - text: 'unfinished, differently normalized', - thinking: 'retained thought' - }) - const before = c.journal.snapshot().items - const tool = before.find((item) => item.body.kind === 'tool-call')! - const text = before.find( - (item) => item.body.kind === 'message' && item.body.role === 'assistant' - )! - const turn = before.find((item) => item.body.kind === 'turn')! - const thinking = before.find( - (item) => item.body.kind === 'message' && item.body.role === 'reasoning' - )! - await c.write([ - prompt('boundary', null, 'saved before crash', 1), - reply('a1', 'boundary', 'msg_a', { type: 'text', text: 'final answer, normalized' }, 2), - reply('thinking-final', 'a1', 'msg_thought', { type: 'thinking', thinking: '' }, 3), - { ...outsideTurn[4], parentUuid: 'thinking-final' } - ]) - expect(await c.open('boundary')).toBe(true) - const afterText = c.journal.item(text.itemId)! - const afterTool = c.journal.item(tool.itemId)! - expect(afterText).toMatchObject({ - sequence: text.sequence, - observedAt: text.observedAt, - turnScope: text.turnScope, - body: { blocks: [{ type: 'text', text: 'final answer, normalized' }] } - }) - expect(afterTool).toMatchObject({ - sequence: tool.sequence, - observedAt: tool.observedAt, - turnScope: tool.turnScope, - body: { - name: 'Read', - input: { path: 'original' }, - state: 'completed', - output: { head: 'hello' } - } - }) - expect(c.journal.item(turn.itemId)).toEqual(turn) - expect(c.journal.item(thinking.itemId)).toEqual(thinking) - expect(c.rows().some((row) => row.startsWith('(continued-outside'))).toBe(false) - const completed = c.journal.snapshot().items - expect(await c.open('boundary')).toBe(true) - expect(c.journal.snapshot().items).toEqual(completed) - }) - it('does not place historical lifecycle after live work that arrives during its read', async () => { const c = await chat() await c.live() @@ -330,385 +41,4 @@ describe('Claude chat catch-up', () => { expect(running?.body).toMatchObject({ state: 'running' }) live.dispose() }) - - it('shows the turns made outside the chat once, in order, under one divider', async () => { - const c = await chat() - await c.live() - await c.write(chatTurn) - const shown = c.rows() - expect(shown).toEqual(['user:ask 1', 'assistant:answer 1']) - - await c.open('a1') - expect(c.rows()).toEqual(shown) - - await c.write(outsideTurn) - await c.open('a1') - const caughtUp = [ - ...shown, - '(continued-outside)', - 'user:ask 2', - 'tool:Read:completed', - 'assistant:answer 2' - ] - expect(c.rows()).toEqual(caughtUp) - expect(c.journal.snapshot().submissions).toHaveLength(1) - - // Opening again, or from a leaf left before the chat's own streamed turn by a crash, adds nothing. - await c.open('a1') - await c.open('p1') - expect(c.rows()).toEqual(caughtUp) - expect(c.warn).not.toHaveBeenCalled() - }) - - // P saved aliases plus P unacknowledged queued prompts: two J-item indexes, not P×J scans. - it.each([10, 100].flatMap((prompts) => [1_000, 10_000].map((items) => ({ prompts, items }))))( - 'bounds retained-leaf work for $prompts aliases and local misses over $items journal items', - async ({ prompts, items }) => { - const c = await chat() - await c.live() - const expected = [...c.rows(), '(continued-outside)'] - const rows: Record[] = [ - reply('saved-leaf', 'earlier-prompt', 'msg_saved', { type: 'text', text: 'earlier' }, 0), - prompt('p1', 'saved-leaf', 'ask 1', 1), - ...chatTurn.slice(1) - ] - for (let n = 1; n < prompts; n++) { - rows.push( - prompt(`outside-p${n}`, n === 1 ? 'a1' : `outside-a${n - 1}`, `ask ${n}`, n * 2 + 1), - reply( - `outside-a${n}`, - `outside-p${n}`, - `msg_outside${n}`, - { type: 'text', text: `answer ${n}` }, - n * 2 + 2 - ) - ) - expected.push(`user:ask ${n}`, `assistant:answer ${n}`) - } - const alias = agentJournalItemKey({ provider: 'claude', sessionId: SID, uuid: 'p1' }) - const canonical = c.journal.canonicalItemId(alias) - expect(canonical).not.toBe(alias) - const submissions = c.journal.snapshot().submissions - await c.write(rows) - expect(await c.open('saved-leaf')).toBe(true) - expect(c.rows()).toEqual(expected) - expect(c.journal.snapshot().submissions).toEqual(submissions) - await c.journal.appendLifecycleBatch({ - settlementId: 'perf-padding', - fence: 1, - mutations: Array.from({ length: items - c.journal.snapshot().items.length }, (_, n) => ({ - kind: 'item' as const, - identity: { provider: 'orca' as const, clientMessageId: `padding${n}` }, - body: { kind: 'message' as const, role: 'user' as const, blocks: [] }, - turnScope: { kind: 'thread' as const } - })) - }) - for (let n = 0; n < prompts; n++) { - const key = agentJournalItemKey({ provider: 'orca', clientMessageId: `padding${n}` }) - await c.write([ - { - ...attachment(`queued${n}`, n ? `queued${n - 1}` : `outside-a${prompts - 1}`), - attachment: { - type: 'queued_command', - source_uuid: claudePromptUuidForSubmission(SESSION, key), - commandMode: 'prompt', - prompt: 'local' - } - } - ]) - } - const before = c.journal.snapshot() - const itemCount = before.items.length - expect(itemCount).toBe(items) - let associationVisits = 0 - let viewVisits = 0 - const visitItems = c.journal.visitItems.bind(c.journal) - const visitLinked = c.journal.visitItemsWithLinkage.bind(c.journal) - vi.spyOn(c.journal, 'visitItems').mockImplementation((visit) => - visitItems((...args) => { - associationVisits++ - visit(...args) - }) - ) - vi.spyOn(c.journal, 'visitItemsWithLinkage').mockImplementation((visit) => - visitLinked((...args) => { - viewVisits++ - visit(...args) - }) - ) - c.journal.visitItems(() => {}) - c.journal.visitItemsWithLinkage(() => {}) - // visitItems delegates to the linked visitor, so this calibration exercises it twice. - expect([associationVisits, viewVisits]).toEqual([itemCount, 2 * itemCount]) - associationVisits = viewVisits = 0 - const committed = vi.fn() - c.journal.observeCommits(committed) - const tail = vi.spyOn(transcriptTail, 'readClaudeTranscriptTail') - expect(await c.open('saved-leaf')).toBe(true) - expect(tail).toHaveBeenCalledOnce() - expect( - (await tail.mock.results[0].value)?.rows.filter((row) => row.type === 'user') - ).toHaveLength(prompts) - expect(c.journal.snapshot()).toEqual(before) - expect(c.journal.canonicalItemId(alias)).toBe(canonical) - expect(committed).not.toHaveBeenCalled() - expect(c.warn).not.toHaveBeenCalled() - expect(associationVisits).toBeLessThanOrEqual(2 * itemCount) - // The linked visitor also counts the association passes; bound the extra view work. - expect(viewVisits - associationVisits).toBeLessThanOrEqual(2 * itemCount) - console.info('retained-leaf operation counts', { - prompts, - itemCount, - associationVisits, - viewVisits - }) - } - ) - - it('clears closed scope and restores only a saved queued prompt without settling delivery', async () => { - const c = await chat() - await c.live() - await c.journal.appendSubmission({ - clientMessageId: 'queued-send', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'follow up' }] }, - payloadFingerprint: 'queued-send', - handoverRecorded: true, - fence: 1 - }) - const scope = c.journal - .snapshot() - .items.find( - (item) => item.body.kind === 'message' && item.body.role === 'assistant' - )?.turnScope - if (!scope || scope.kind !== 'turn') { - throw new Error('missing native turn') - } - await c.journal.resolveDispatch({ - clientMessageId: 'queued-send', - state: 'pending', - turnScope: scope, - fence: 1 - }) - await c.journal.resolveDispatch({ - clientMessageId: 'queued-send', - state: 'accepted', - providerIdentity: { provider: 'claude', sessionId: SID, uuid: 'cmd-1' }, - fence: 1 - }) - const before = c.journal.snapshot() - const end = (uuid: string, parentUuid: string) => ({ - type: 'system', - subtype: 'turn_duration', - sessionId: SID, - uuid, - parentUuid, - timestamp: 'malformed' - }) - await c.write([ - ...chatTurn, - end('saved-end', 'a1'), - { - ...attachment('unknown-row', 'saved-end'), - attachment: { - type: 'queued_command', - source_uuid: 'unknown-input', - commandMode: 'prompt', - origin: { kind: 'human' }, - humanTurn: true, - prompt: 'unproved input' - } - }, - { - ...attachment('queued-row', 'unknown-row'), - attachment: { - type: 'queued_command', - source_uuid: 'cmd-1', - delivery_id: 'delivery-1', - commandMode: 'prompt', - origin: { kind: 'human' }, - humanTurn: true, - prompt: 'follow up' - } - }, - reply('a2', 'queued-row', 'msg_b', { type: 'text', text: 'follow up answer' }, 3), - end('continued-end', 'a2'), - reply('wake', 'continued-end', 'msg_wake', { type: 'text', text: 'background' }, 4), - prompt('next', 'wake', 'next request', 5), - reply('next-answer', 'next', 'msg_next', { type: 'text', text: 'next answer' }, 6) - ]) - expect(await c.open('p1')).toBe(true) - expect(c.rows()).toEqual([ - 'user:ask 1', - 'assistant:answer 1', - 'user:follow up', - '(continued-outside)', - 'user:unproved input', - 'assistant:follow up answer', - 'assistant:background', - 'user:next request', - 'assistant:next answer' - ]) - const imported = c.journal.snapshot().items - expect(await c.open('p1')).toBe(true) - expect(c.journal.snapshot().items).toEqual(imported) - expect(c.journal.snapshot().submissions).toEqual(before.submissions) - for (const item of before.items) { - expect(c.journal.item(item.itemId)).toEqual(item) - } - const unknown = agentJournalItemKey({ - provider: 'claude', - sessionId: SID, - uuid: 'unknown-input' - }) - expect(c.journal.item(unknown)?.turnScope).toEqual({ kind: 'unknown' }) - expect(isStructuredRewindTarget(c.journal, unknown)).toBe(false) - const answer = c.journal - .snapshot() - .items.find( - (item) => - item.body.kind === 'message' && - item.body.role === 'assistant' && - item.itemId !== - agentJournalItemKey({ provider: 'claude', sessionId: SID, uuid: 'block:msg_a:0' }) - ) - expect(answer?.turnScope).toEqual(scope) - const turns = imported.filter((item) => item.body.kind === 'turn') - expect(turns).toHaveLength(3) - const wake = turns.find((item) => item.body.kind === 'turn' && item.body.turnId === 'wake')! - expect(wake.body).toMatchObject({ userItemId: wake.itemId }) - expect(turns.some((item) => item.body.kind === 'turn' && item.body.turnId === 'next')).toBe( - true - ) - expect(c.warn).not.toHaveBeenCalled() - }) - - it('reads an outside reply that spans many read chunks whole', async () => { - const c = await chat() - await c.live() - const answer = `${'outside answer paragraph\n'.repeat(12_000)}END` - await c.write([ - ...chatTurn, - prompt('p5', 'a1', 'ask long', 9), - reply('a5', 'p5', 'msg_e', { type: 'text', text: answer }, 10), - ...bookkeeping - ]) - await c.open('a1') - expect(c.rows().slice(2)).toEqual([ - '(continued-outside)', - 'user:ask long', - `assistant:${answer}` - ]) - }) - - it('opens normally when the saved leaf is not in the transcript', async () => { - const c = await chat() - await c.live() - await c.write([...chatTurn, ...outsideTurn]) - await c.open('missing') - expect(c.rows()).toEqual(['user:ask 1', 'assistant:answer 1']) - expect(c.warn).toHaveBeenCalledWith( - 'Claude chat did not catch up on turns made outside it', - expect.objectContaining({ reason: 'leaf-not-in-tail' }) - ) - }) -}) - -it.each(['removed-leaf', ''])( - 'recovers the active main chain for copied leaf %j, ignoring covered and metadata rows', - async (leafUuid) => { - const c = await chat() - await c.journal.replaceEpochItems( - 'session_created', - 1, - [ - { - identity: { provider: 'legacy', agent: 'claude', sessionId: 'source', recordId: 'rich' }, - ownerFence: 0, - observedAt: 1, - body: { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: 'rich copied answer' }] - } - } - ], - undefined, - undefined, - { - version: 1, - kind: 'native_copy', - agent: 'claude', - unit: 'claude-entry', - providerHandle: { kind: 'claude', sessionId: SID, leafUuid: leafUuid || null }, - ids: ['p1', 't1', 'a1'] - } - ) - await c.write([ - ...chatTurn, - prompt('abandoned', 'a1', 'abandoned branch', 3), - ...outsideTurn, - { type: 'custom-title', uuid: 'metadata', customTitle: 'title', sessionId: SID }, - ...(leafUuid === '' - ? [ - { - ...reply( - 'helper-output', - 'a1', - 'msg_helper', - { type: 'text', text: 'x'.repeat(16 * 1024 * 1024) }, - 7 - ), - isSidechain: true - } - ] - : []) - ]) - expect(await c.open(leafUuid)).toBe(true) - expect(await c.open(leafUuid)).toBe(true) - expect(c.rows().filter((row) => row.startsWith('assistant:'))).toEqual([ - 'assistant:rich copied answer', - 'assistant:answer 2' - ]) - expect(c.rows()).not.toContain('user:abandoned branch') - expect((await c.replay()).snapshot().items.map((item) => item.itemId)).toEqual( - c.journal.snapshot().items.map((item) => item.itemId) - ) - } -) - -it('keeps terminal turns before the recorded compaction bridge during catch-up', async () => { - const c = await chat() - await c.live() - await c.write([ - ...chatTurn, - ...outsideTurn, - { - type: 'system', - subtype: 'compact_boundary', - uuid: 'compact', - parentUuid: null, - logicalParentUuid: 'a3', - isSidechain: false, - sessionId: SID, - timestamp: '2026-10-21T12:00:07.000Z', - content: 'Conversation compacted', - compactMetadata: { trigger: 'manual', preTokens: 1000 } - }, - prompt('summary', 'compact', 'Summary of the conversation', 8), - prompt('p3', 'summary', 'ask after compaction', 9), - reply('a4', 'p3', 'msg_d', { type: 'text', text: 'answer after compaction' }, 10) - ]) - expect(await c.open('a1')).toBe(true) - const messages = c.journal - .snapshot() - .items.flatMap((item) => - item.body.kind === 'message' - ? item.body.blocks.flatMap((block) => (block.type === 'text' ? [block.text] : [])) - : [] - ) - expect(messages).toContain('ask 2') - expect(messages).toContain('answer 2') - expect(messages).toContain('ask after compaction') - expect(messages).toContain('answer after compaction') - expect(c.warn).not.toHaveBeenCalled() }) diff --git a/src/main/claude/structured/journal/claude-structured-prompt-items.test.ts b/src/main/claude/structured/journal/claude-structured-prompt-items.test.ts deleted file mode 100644 index 0be0dd589c7..00000000000 --- a/src/main/claude/structured/journal/claude-structured-prompt-items.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { claudeQuestionItems } from './claude-structured-prompt-items' - -const LAYOUT_A = '┌──────┬────────┐\n│ nav │ main │\n└──────┴────────┘' - -describe('claudeQuestionItems', () => { - it('keeps option previews on single-select questions only', () => { - const [item] = claudeQuestionItems({ - sessionId: 'session-1', - prompt: { - requestId: 'req-1', - promptKey: 'req-1', - toolUseId: 'toolu-1', - toolName: 'AskUserQuestion', - kind: 'question', - input: { - questions: [ - { - question: 'Which layout?', - header: 'Layout', - multiSelect: false, - options: [ - { label: 'Sidebar', description: 'Nav on the left', preview: LAYOUT_A }, - { label: 'Top bar', description: 'Nav on top', preview: ' \n ' } - ] - }, - { - question: 'Which panes?', - header: 'Panes', - multiSelect: true, - options: [ - { label: 'Files', description: 'File tree', preview: 'files' }, - { label: 'Git', description: 'Changes', preview: 'git' } - ] - } - ] - }, - suggestions: [], - questionIds: ['q1', 'q2'], - settle: vi.fn() - } - }) - const questions = item!.body.questions! - expect(questions[0]!.options.map((option) => option.preview)).toEqual([LAYOUT_A, undefined]) - expect(questions[1]!.options.map((option) => option.preview)).toEqual([undefined, undefined]) - }) -}) diff --git a/src/main/codex-usage/codex-automation-run-attribution.ts b/src/main/codex-usage/codex-automation-run-attribution.ts index 9da30261492..ae2b6f50c44 100644 --- a/src/main/codex-usage/codex-automation-run-attribution.ts +++ b/src/main/codex-usage/codex-automation-run-attribution.ts @@ -1,7 +1,7 @@ import type { AutomationRunUsage } from '../../shared/automations/history/automation-run' import type { CodexUsagePersistedState } from './types' import { estimateCostUsd } from './codex-usage-cost-estimate' -import { shouldForceAutomationUsageScan } from '../usage/automation-usage-scan-forcing' +import { shouldForceAutomationUsageScan } from '../usage/provider-lifecycle/automation-usage-scan-forcing' const AUTOMATION_ATTRIBUTION_WINDOW_MS = 5 * 60_000 diff --git a/src/main/codex-usage/codex-rollout-file-parse.ts b/src/main/codex-usage/codex-rollout-file-parse.ts index 30dab4b2b71..f2e105677e1 100644 --- a/src/main/codex-usage/codex-rollout-file-parse.ts +++ b/src/main/codex-usage/codex-rollout-file-parse.ts @@ -1,13 +1,16 @@ import { basename } from 'node:path' -import { readJsonlFileSnapshot, type JsonlFileSnapshot } from '../usage/jsonl-file-snapshot' -import { readJsonlLinesFromOffset } from '../usage/jsonl-line-offsets' +import { + readJsonlFileSnapshot, + type JsonlFileSnapshot +} from '../usage/source-input/jsonl/jsonl-file-snapshot' +import { readJsonlLinesFromOffset } from '../usage/source-input/jsonl/jsonl-line-offsets' import { openJsonlFileReader, validateJsonlFileReader, jsonlPhysicalFileId -} from '../usage/jsonl-file-checkpoint' +} from '../usage/source-input/jsonl/jsonl-file-checkpoint' import { attributeCodexUsageEvent } from './codex-usage-event-attribution' -import type { UsageWorktreeResolver } from '../usage/usage-worktree-resolver' +import type { UsageWorktreeResolver } from '../usage/worktree-attribution/usage-worktree-resolver' import { parseCodexUsageRecord, type CodexUsageParseContext } from './codex-usage-record-parser' import { codexUsageAggregation } from './codex-usage-aggregation' import { diff --git a/src/main/codex-usage/codex-rollout-resume-state.ts b/src/main/codex-usage/codex-rollout-resume-state.ts index e6592a97d60..d1b79b42243 100644 --- a/src/main/codex-usage/codex-rollout-resume-state.ts +++ b/src/main/codex-usage/codex-rollout-resume-state.ts @@ -4,9 +4,12 @@ import { buildJsonlFileCheckpoint, resolveJsonlFileCheckpoint, type JsonlFileReader -} from '../usage/jsonl-file-checkpoint' +} from '../usage/source-input/jsonl/jsonl-file-checkpoint' -export { MIN_RESUMABLE_PREFIX_BYTES, isResumablePrefixLength } from '../usage/jsonl-file-checkpoint' +export { + MIN_RESUMABLE_PREFIX_BYTES, + isResumablePrefixLength +} from '../usage/source-input/jsonl/jsonl-file-checkpoint' export async function buildCodexRolloutResumeState( filePath: string, diff --git a/src/main/codex-usage/codex-session-file-discovery.ts b/src/main/codex-usage/codex-session-file-discovery.ts index b6f372aa00b..62c47e98f3f 100644 --- a/src/main/codex-usage/codex-session-file-discovery.ts +++ b/src/main/codex-usage/codex-session-file-discovery.ts @@ -7,7 +7,7 @@ import { } from '../codex/configuration/homes/codex-home-paths' import { getCodexAccountHomeSessionDirectories } from '../codex/history/rollouts/codex-account-home-discovery' import { getLegacyCopiedCodexSessionBridgeScanPreference } from '../codex/history/bridges/codex-session-bridge' -import { normalizeFsPath } from '../usage/usage-path-comparison' +import { normalizeFsPath } from '../usage/worktree-attribution/usage-path-comparison' import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' const YIELD_EVERY_DISCOVERY_ENTRIES = 100 diff --git a/src/main/codex-usage/codex-usage-aggregation.ts b/src/main/codex-usage/codex-usage-aggregation.ts index 1afdc7736c0..8f5b1b8e22c 100644 --- a/src/main/codex-usage/codex-usage-aggregation.ts +++ b/src/main/codex-usage/codex-usage-aggregation.ts @@ -1,4 +1,4 @@ -import { createUsageEventAggregation } from '../usage/usage-event-aggregation' +import { createUsageEventAggregation } from '../usage/rollups/usage-event-aggregation' import type { CodexLongContextTokens, CodexUsageAttributedEvent } from './types' type CodexUsageMetric = { hasInferredPricing: boolean } & CodexLongContextTokens diff --git a/src/main/codex-usage/codex-usage-event-attribution.ts b/src/main/codex-usage/codex-usage-event-attribution.ts index 8ebf7fbc5e3..de1257d5792 100644 --- a/src/main/codex-usage/codex-usage-event-attribution.ts +++ b/src/main/codex-usage/codex-usage-event-attribution.ts @@ -1,6 +1,6 @@ -import { attributeUsageEvent } from '../usage/usage-event-attribution' -import type { UsageScanWorktreeRef } from '../usage/usage-provider-contract' -import type { UsageWorktreeResolver } from '../usage/usage-worktree-resolver' +import { attributeUsageEvent } from '../usage/worktree-attribution/usage-event-attribution' +import type { UsageScanWorktreeRef } from '../usage/provider-lifecycle/usage-provider-contract' +import type { UsageWorktreeResolver } from '../usage/worktree-attribution/usage-worktree-resolver' import type { CodexUsageAttributedEvent, CodexUsageParsedEvent } from './types' export type CodexUsageWorktreeRef = UsageScanWorktreeRef diff --git a/src/main/codex-usage/codex-usage-long-context-billing.test.ts b/src/main/codex-usage/codex-usage-long-context-billing.test.ts index 9dc698a29eb..d095211610f 100644 --- a/src/main/codex-usage/codex-usage-long-context-billing.test.ts +++ b/src/main/codex-usage/codex-usage-long-context-billing.test.ts @@ -1,26 +1,5 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { createStoreWithState, setupCodexUsageStoreEnv } from './store-test-harness' +import { describe, expect, it } from 'vitest' -const { getPathMock } = vi.hoisted(() => ({ - getPathMock: vi.fn(() => '/tmp/orca-test-userdata') -})) - -vi.mock('electron', () => ({ - app: { - getPath: getPathMock - } -})) - -vi.mock('../usage/usage-scan-worker-spawn', () => ({ - scanCodexUsageFilesViaWorker: vi.fn(), - splitUsageCacheFileViaWorker: vi.fn() -})) - -import { createUsageWorktreeResolver } from '../usage/usage-worktree-resolver' -import { parseCodexUsageFile } from './codex-rollout-file-parse' import { parseCodexUsageRecord, type CodexUsageParseContext } from './codex-usage-record-parser' type Usage = { input: number; cached: number; output: number } @@ -125,73 +104,3 @@ describe('per-request long-context classification', () => { }) }) }) - -describe('long-context cost across rollups', () => { - setupCodexUsageStoreEnv(getPathMock) - let rolloutDir: string | null = null - - afterEach(() => { - if (rolloutDir) { - rmSync(rolloutDir, { recursive: true, force: true }) - rolloutDir = null - } - }) - - it('prices a mixed two-day rollout per request, and the summary matches the breakdown', async () => { - rolloutDir = mkdtempSync(join(tmpdir(), 'orca-codex-long-context-')) - const rolloutPath = join(rolloutDir, 'rollout-session-1.jsonl') - const shortRequest: Usage = { input: 200_000, cached: 100_000, output: 10_000 } - const requests = [ - { - timestamp: '2026-04-08T12:00:00.000Z', - usage: { input: 300_000, cached: 150_000, output: 100_000 } - }, - ...Array.from({ length: 10 }, (_, index) => ({ - timestamp: `2026-04-0${index < 5 ? 8 : 9}T12:${String(10 + index).padStart(2, '0')}:00.000Z`, - usage: shortRequest - })) - ] - const lines = [ - JSON.stringify({ - type: 'session_meta', - payload: { id: 'session-1', cwd: '/workspace/repo' } - }), - JSON.stringify({ - type: 'turn_context', - payload: { cwd: '/workspace/repo', model: 'gpt-6-astra' } - }), - ...requestLines(requests) - ] - writeFileSync(rolloutPath, `${lines.join('\n')}\n`) - - const parsed = await parseCodexUsageFile(rolloutPath, await createUsageWorktreeResolver([])) - const store = createStoreWithState({ - sessions: parsed.sessions, - dailyAggregates: parsed.dailyAggregates - }) - - expect(parsed.dailyAggregates).toHaveLength(2) - expect(parsed.sessions[0]?.locationModelBreakdown[0]).toMatchObject({ - longContextInputTokens: 300_000, - longContextCachedInputTokens: 150_000, - longContextOutputTokens: 100_000 - }) - const summary = await store.getSummary('all', '30d') - const breakdown = await store.getBreakdown('all', '30d', 'model') - // Long request: 0.15M*$20 + 0.15M*$2 + 0.1M*$75 = 10.8. - // Ten short requests: 10 * (0.1M*$10 + 0.1M*$1 + 0.01M*$50) = 16. - expect(summary.estimatedCostUsd).toBeCloseTo(26.8, 9) - expect(breakdown).toHaveLength(1) - expect(breakdown[0]?.estimatedCostUsd).toBeCloseTo(26.8, 9) - - store['state'].scanState.enabled = true - vi.spyOn(store, 'refresh').mockResolvedValue({ ...store.getScanState(), lastScanError: null }) - const runUsage = await store.getAutomationRunUsage({ - worktreeId: 'unrelated-worktree', - terminalSessionId: 'session-1', - startedAt: Date.parse('2026-04-08T11:59:00.000Z'), - completedAt: Date.parse('2026-04-09T12:30:00.000Z') - }) - expect(runUsage.estimatedCostUsd).toBeCloseTo(26.8, 9) - }) -}) diff --git a/src/main/codex-usage/codex-usage-provider.ts b/src/main/codex-usage/codex-usage-provider.ts index ab8d0f4e7bc..8da60e3b175 100644 --- a/src/main/codex-usage/codex-usage-provider.ts +++ b/src/main/codex-usage/codex-usage-provider.ts @@ -1,5 +1,5 @@ -import type { UsageProvider } from '../usage/usage-provider-contract' -import { scanCodexUsageFilesViaWorker } from '../usage/usage-scan-worker-spawn' +import type { UsageProvider } from '../usage/provider-lifecycle/usage-provider-contract' +import { scanCodexUsageFilesViaWorker } from '../usage/scan-worker/usage-scan-worker-spawn' import type { CodexUsageDailyAggregate, CodexUsageSession } from './types' // Rescan older caches: v5 deduplicates forks across sessions; v6 adds per-request long-context counts; diff --git a/src/main/codex-usage/codex-usage-record-parser.ts b/src/main/codex-usage/codex-usage-record-parser.ts index bd0de5b94cd..e09c7fd21f7 100644 --- a/src/main/codex-usage/codex-usage-record-parser.ts +++ b/src/main/codex-usage/codex-usage-record-parser.ts @@ -1,4 +1,4 @@ -import { extractString } from '../usage/usage-record-coercion' +import { extractString } from '../usage/source-input/usage-record-coercion' import { buildCodexUsageEventKey, normalizeRawUsage, diff --git a/src/main/codex-usage/codex-usage-rollup-projections.ts b/src/main/codex-usage/codex-usage-rollup-projections.ts index 614347aa2de..ea31ec29b7c 100644 --- a/src/main/codex-usage/codex-usage-rollup-projections.ts +++ b/src/main/codex-usage/codex-usage-rollup-projections.ts @@ -1,4 +1,4 @@ -import { highestUsageKey } from '../usage/highest-usage-key' +import { highestUsageKey } from '../usage/rollups/highest-usage-key' import type { CodexUsageBreakdownKind, CodexUsageBreakdownRow, diff --git a/src/main/codex-usage/codex-usage-scope-filters.ts b/src/main/codex-usage/codex-usage-scope-filters.ts index de023f50864..ef3891e350e 100644 --- a/src/main/codex-usage/codex-usage-scope-filters.ts +++ b/src/main/codex-usage/codex-usage-scope-filters.ts @@ -1,6 +1,9 @@ import type { CodexUsageRange, CodexUsageScope } from '../../shared/codex-usage-types' import type { CodexUsagePersistedState } from './types' -import { filterUsageDaily, filterUsageSessions } from '../usage/usage-scope-filters' +import { + filterUsageDaily, + filterUsageSessions +} from '../usage/reporting/range-query/usage-scope-filters' export type ScopedCodexUsageModelRow = { modelKey: string diff --git a/src/main/codex-usage/codex-usage-token-delta.ts b/src/main/codex-usage/codex-usage-token-delta.ts index 9d391661bf9..497b7352fc2 100644 --- a/src/main/codex-usage/codex-usage-token-delta.ts +++ b/src/main/codex-usage/codex-usage-token-delta.ts @@ -1,4 +1,4 @@ -import { ensureNumber } from '../usage/usage-record-coercion' +import { ensureNumber } from '../usage/source-input/usage-record-coercion' export type CodexUsageRawUsage = { inputTokens: number diff --git a/src/main/codex-usage/scanner-incremental-append.test.ts b/src/main/codex-usage/scanner-incremental-append.test.ts index adfb0508d4a..06500ff51df 100644 --- a/src/main/codex-usage/scanner-incremental-append.test.ts +++ b/src/main/codex-usage/scanner-incremental-append.test.ts @@ -1,25 +1,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { tmpdir } from 'node:os' import type * as NodeOs from 'node:os' -import type * as NodeFs from 'node:fs' -import type * as NodeFsPromises from 'node:fs/promises' -import type * as JsonlLineOffsets from '../usage/jsonl-line-offsets' + import { join } from 'node:path' -const { getPathMock, homedirMock, streamReads, onStreamOpen, parsingPaths } = vi.hoisted(() => { - const streamReads: { path: string; bytes: number; start: number; digest: boolean }[] = [] - // Inject filesystem mutations between parse reads. - const onStreamOpen: { current: ((path: string, digest: boolean) => void) | null } = { - current: null - } - return { - getPathMock: vi.fn<(name: string) => string>(), - homedirMock: vi.fn<() => string>(), - streamReads, - onStreamOpen, - parsingPaths: new Set() - } -}) +const { getPathMock, homedirMock } = vi.hoisted(() => ({ + getPathMock: vi.fn<(name: string) => string>(), + homedirMock: vi.fn<() => string>() +})) vi.mock('electron', () => ({ app: { @@ -35,113 +23,10 @@ vi.mock('node:os', async () => { } }) -// Count both parsing and checkpoint reads for the scan I/O assertions. -vi.mock('node:fs', async () => { - const actual = await vi.importActual('node:fs') - return { - ...actual, - createReadStream: ( - path: Parameters[0], - options?: Parameters[1] - ) => { - const filePath = String(path) - const range = typeof options === 'object' && options !== null ? options : {} - const start = range.start ?? 0 - const read = { path: filePath, bytes: 0, start, digest: !parsingPaths.has(filePath) } - streamReads.push(read) - onStreamOpen.current?.(filePath, read.digest) - const stream = actual.createReadStream(path, options) - stream.on('data', (chunk: string | Buffer) => { - read.bytes += typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.length - }) - return stream - } - } -}) - -vi.mock('node:fs/promises', async () => { - const actual = await vi.importActual('node:fs/promises') - return { - ...actual, - open: async (...args: Parameters) => { - const handle = await actual.open(...args) - const createStream = handle.createReadStream.bind(handle) - const readWindow = handle.read.bind(handle) - let streamActive = false - vi.spyOn(handle, 'read').mockImplementation(async (...readArgs) => { - if (streamActive) { - return readWindow(...readArgs) - } - const filePath = String(args[0]) - const digest = !parsingPaths.has(filePath) - onStreamOpen.current?.(filePath, digest) - const result = await readWindow(...readArgs) - const position = readArgs.at(-1) - streamReads.push({ - path: filePath, - bytes: result.bytesRead, - start: typeof position === 'number' ? position : 0, - digest - }) - return result - }) - vi.spyOn(handle, 'createReadStream').mockImplementation((options) => { - const filePath = String(args[0]) - const read = { - path: filePath, - bytes: 0, - start: options?.start ?? 0, - digest: !parsingPaths.has(filePath) - } - streamReads.push(read) - onStreamOpen.current?.(filePath, read.digest) - streamActive = true - const stream = createStream(options) - const finish = (): void => { - streamActive = false - } - stream.once('end', finish) - stream.once('close', finish) - stream.on('data', (chunk: string | Buffer) => { - read.bytes += typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.length - }) - return stream - }) - return handle - } - } -}) - -vi.mock('../usage/jsonl-line-offsets', async () => { - const actual = await vi.importActual('../usage/jsonl-line-offsets') - return { - ...actual, - readJsonlLinesFromOffset: async function* ( - ...args: Parameters - ) { - parsingPaths.add(args[0]) - try { - yield* actual.readJsonlLinesFromOffset(...args) - } finally { - parsingPaths.delete(args[0]) - } - } - } -}) - -import { - mkdirSync, - mkdtempSync, - rmSync, - statSync, - utimesSync, - writeFileSync, - appendFileSync -} from 'node:fs' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { scanCodexUsageFiles } from './scanner' /** Mirrors the checkpoint window in jsonl-file-checkpoint.ts. */ -const BOUNDARY_WINDOW_BYTES = 4096 /** Clear the resumable-prefix floor so tests actually exercise incremental parsing. */ const RESUMABLE_RECORDS = 40 @@ -179,26 +64,6 @@ function usageRecord(timestamp: string, inputTokens: number, totalInputTokens: n })}\n` } -function totalOnlyUsageRecord(timestamp: string, totalInputTokens: number): string { - return `${JSON.stringify({ - timestamp, - type: 'event_msg', - payload: { - type: 'token_count', - info: { - model: 'gpt-5-codex', - total_token_usage: { - input_tokens: totalInputTokens, - cached_input_tokens: 0, - output_tokens: 0, - reasoning_output_tokens: 0, - total_tokens: totalInputTokens - } - } - } - })}\n` -} - function sessionMeta(id: string): string { return `${JSON.stringify({ type: 'session_meta', @@ -218,11 +83,6 @@ function usageRecordRange(from: number, to: number): string { } /** The iterator marks parse reads to distinguish them from bounded digest reads. */ -function parseReadOffsets(filePath: string): number[] { - return streamReads - .filter((entry) => entry.path === filePath && !entry.digest) - .map((entry) => entry.start) -} function recordedResumeOffset( files: { path: string; parseResumeState?: { parsedBytes: number } | null }[], @@ -232,9 +92,6 @@ function recordedResumeOffset( } /** Session attribution catches context corruption that token totals alone can miss. */ -function eventCountsBySession(sessions: { sessionId: string; eventCount: number }[]): unknown[] { - return sessions.map((session) => [session.sessionId, session.eventCount]).sort() -} function totalTokens(aggregates: { totalTokens: number }[]): number { return aggregates.reduce((total, aggregate) => total + aggregate.totalTokens, 0) @@ -255,9 +112,6 @@ beforeEach(() => { }) sessionsDir = join(userDataDir, 'codex-runtime-home', 'home', 'sessions') mkdirSync(sessionsDir, { recursive: true }) - streamReads.length = 0 - onStreamOpen.current = null - parsingPaths.clear() }) afterEach(() => { @@ -277,64 +131,6 @@ afterEach(() => { }) describe('scanCodexUsageFiles incremental append', () => { - it('carries cumulative token totals across the resume boundary', async () => { - const rolloutPath = join(sessionsDir, 'rollout-cumulative.jsonl') - writeFileSync( - rolloutPath, - [ - sessionMeta('session-cumulative'), - usageRecordRange(0, RESUMABLE_RECORDS), - totalOnlyUsageRecord('2026-05-26T13:00:00.000Z', RESUMABLE_RECORDS + 100), - totalOnlyUsageRecord('2026-05-26T13:01:00.000Z', RESUMABLE_RECORDS + 250) - ].join(''), - 'utf-8' - ) - - const first = await scanCodexUsageFiles([], []) - expect(totalTokens(first.dailyAggregates)).toBe(RESUMABLE_RECORDS + 250) - const resumeOffset = recordedResumeOffset(first.processedFiles, rolloutPath) - - appendFileSync( - rolloutPath, - totalOnlyUsageRecord('2026-05-26T13:02:00.000Z', RESUMABLE_RECORDS + 400), - 'utf-8' - ) - - streamReads.length = 0 - const second = await scanCodexUsageFiles([], first.processedFiles) - expect(parseReadOffsets(rolloutPath)).toEqual([resumeOffset]) - const fromScratch = await scanCodexUsageFiles([], []) - expect(totalTokens(second.dailyAggregates)).toBe(RESUMABLE_RECORDS + 400) - expect(second.dailyAggregates).toEqual(fromScratch.dailyAggregates) - }) - - it('tracks byte offsets through CRLF line endings', async () => { - const rolloutPath = join(sessionsDir, 'rollout-crlf.jsonl') - const toCrlf = (text: string): string => text.replaceAll('\n', '\r\n') - writeFileSync( - rolloutPath, - toCrlf(`${sessionMeta('session-crlf')}${usageRecordRange(0, RESUMABLE_RECORDS)}`), - 'utf-8' - ) - - const first = await scanCodexUsageFiles([], []) - expect(totalTokens(first.dailyAggregates)).toBe(RESUMABLE_RECORDS) - const resumeOffset = recordedResumeOffset(first.processedFiles, rolloutPath) - - appendFileSync( - rolloutPath, - toCrlf(usageRecordRange(RESUMABLE_RECORDS, RESUMABLE_RECORDS + 3)), - 'utf-8' - ) - - streamReads.length = 0 - const second = await scanCodexUsageFiles([], first.processedFiles) - expect(parseReadOffsets(rolloutPath)).toEqual([resumeOffset]) - const fromScratch = await scanCodexUsageFiles([], []) - expect(totalTokens(second.dailyAggregates)).toBe(RESUMABLE_RECORDS + 3) - expect(second.sessions).toEqual(fromScratch.sessions) - }) - it('falls back to a full reparse when a rollout is truncated', async () => { const rolloutPath = join(sessionsDir, 'rollout-truncated.jsonl') writeFileSync( @@ -354,292 +150,8 @@ describe('scanCodexUsageFiles incremental append', () => { }) // Truncate after checkpoint validation to exercise the parse-time race. - it('reparses from the start when a rollout shrinks during its parse read', async () => { - const rolloutPath = join(sessionsDir, 'rollout-shrinks-mid-read.jsonl') - writeFileSync( - rolloutPath, - `${sessionMeta('session-shrinker')}${usageRecordRange(0, RESUMABLE_RECORDS)}` - ) - - const first = await scanCodexUsageFiles([], []) - expect(totalTokens(first.dailyAggregates)).toBe(RESUMABLE_RECORDS) - const resumeOffset = recordedResumeOffset(first.processedFiles, rolloutPath) - - appendFileSync(rolloutPath, usageRecordRange(RESUMABLE_RECORDS, RESUMABLE_RECORDS + 2), 'utf-8') - const truncated = `${sessionMeta('session-shrinker')}${usageRecordRange(0, 5)}` - onStreamOpen.current = (path, digest) => { - if (path === rolloutPath && !digest) { - onStreamOpen.current = null - writeFileSync(path, truncated, 'utf-8') - } - } - - streamReads.length = 0 - const second = await scanCodexUsageFiles([], first.processedFiles) - expect(onStreamOpen.current).toBeNull() - expect(parseReadOffsets(rolloutPath)).toEqual([resumeOffset, 0]) - expect(totalTokens(second.dailyAggregates)).toBe(5) - expect(second.sessions[0]?.eventCount).toBe(5) - const third = await scanCodexUsageFiles([], second.processedFiles) - expect(totalTokens(third.dailyAggregates)).toBe(5) - }) // Token totals can match despite a stale session context; compare attribution with a cold scan. /** Preserve the boundary window while changing leading records at the same file length. */ - function prefixSwapPair(sessionId: string): { original: string; replacement: string } { - const sharedSuffix = usageRecordRange(20, 40) - expect(sharedSuffix.length).toBeGreaterThan(BOUNDARY_WINDOW_BYTES) - let swappedPrefix = '' - for (let index = 0; index < 20; index++) { - const minute = String(index % 60).padStart(2, '0') - swappedPrefix += usageRecord(`2026-05-26T12:${minute}:00.000Z`, 3, index + 1) - } - const original = `${sessionMeta(sessionId)}${usageRecordRange(0, 20)}${sharedSuffix}` - const replacement = `${sessionMeta(sessionId)}${swappedPrefix}${sharedSuffix}` - expect(replacement.length).toBe(original.length) - return { original, replacement } - } - - it('falls back to a full reparse when the records before the offset changed', async () => { - const rolloutPath = join(sessionsDir, 'rollout-tail-swap.jsonl') - const swappedFrom = RESUMABLE_RECORDS - const swappedTo = RESUMABLE_RECORDS + 10 - const sharedHead = `${sessionMeta('session-tail')}${usageRecordRange(0, swappedFrom)}` - expect(sharedHead.length).toBeGreaterThan(BOUNDARY_WINDOW_BYTES) - let heavierTail = '' - for (let index = swappedFrom; index < swappedTo; index++) { - const minute = String(index % 60).padStart(2, '0') - const hour = String(12 + (Math.floor(index / 60) % 4)).padStart(2, '0') - heavierTail += usageRecord(`2026-05-26T${hour}:${minute}:00.000Z`, 3, index + 1) - } - const original = `${sharedHead}${usageRecordRange(swappedFrom, swappedTo)}` - const replacement = `${sharedHead}${heavierTail}` - expect(replacement.length).toBe(original.length) - // Only the boundary window can detect this rewrite. - expect(original.length - sharedHead.length).toBeLessThan(BOUNDARY_WINDOW_BYTES) - writeFileSync(rolloutPath, original, 'utf-8') - - // Keep the rewrite observable on filesystems whose clock has not ticked yet. - utimesSync(rolloutPath, 1, 1) - const first = await scanCodexUsageFiles([], []) - expect(totalTokens(first.dailyAggregates)).toBe(swappedTo) - expect(recordedResumeOffset(first.processedFiles, rolloutPath)).toBeGreaterThan(0) - - writeFileSync(rolloutPath, replacement, 'utf-8') - - expect(statSync(rolloutPath).mtimeMs).not.toBe(first.processedFiles[0]?.mtimeMs) - const second = await scanCodexUsageFiles([], first.processedFiles) - const fromScratch = await scanCodexUsageFiles([], []) - expect(second.dailyAggregates).toEqual(fromScratch.dailyAggregates) - expect(totalTokens(second.dailyAggregates)).toBe(swappedFrom + 10 * 3) - }) - - // Recreated files can reuse inodes, so rotation must also check content. - - it('falls back to a full reparse when a prefix was rewritten in place', async () => { - const rolloutPath = join(sessionsDir, 'rollout-prefix-swap-in-place.jsonl') - const { original, replacement } = prefixSwapPair('session-prefix-in-place') - writeFileSync(rolloutPath, original, 'utf-8') - - // Keep the rewrite observable on filesystems whose clock has not ticked yet. - utimesSync(rolloutPath, 1, 1) - const first = await scanCodexUsageFiles([], []) - expect(totalTokens(first.dailyAggregates)).toBe(40) - - const inodeBefore = statSync(rolloutPath).ino - writeFileSync(rolloutPath, replacement, 'utf-8') - expect(statSync(rolloutPath).ino).toBe(inodeBefore) - - expect(statSync(rolloutPath).mtimeMs).not.toBe(first.processedFiles[0]?.mtimeMs) - const second = await scanCodexUsageFiles([], first.processedFiles) - const fromScratch = await scanCodexUsageFiles([], []) - expect(second.dailyAggregates).toEqual(fromScratch.dailyAggregates) - expect(totalTokens(second.dailyAggregates)).toBe(80) - }) - - it('does not double-count a record completed after a partial trailing line', async () => { - const rolloutPath = join(sessionsDir, 'rollout-partial.jsonl') - const complete = usageRecordRange(0, RESUMABLE_RECORDS) - const pending = usageRecord('2026-05-26T12:59:00.000Z', 1, RESUMABLE_RECORDS + 1) - writeFileSync( - rolloutPath, - `${sessionMeta('session-partial')}${complete}${pending.slice(0, 40)}`, - 'utf-8' - ) - - const first = await scanCodexUsageFiles([], []) - expect(totalTokens(first.dailyAggregates)).toBe(RESUMABLE_RECORDS) - - writeFileSync( - rolloutPath, - `${sessionMeta('session-partial')}${complete}${pending}${usageRecordRange(RESUMABLE_RECORDS + 1, RESUMABLE_RECORDS + 2)}`, - 'utf-8' - ) - - streamReads.length = 0 - const second = await scanCodexUsageFiles([], first.processedFiles) - expect(parseReadOffsets(rolloutPath)).toEqual([ - recordedResumeOffset(first.processedFiles, rolloutPath) - ]) - expect(totalTokens(second.dailyAggregates)).toBe(RESUMABLE_RECORDS + 2) - expect(second.sessions[0]?.eventCount).toBe(RESUMABLE_RECORDS + 2) - }) - - // Valid JSON without its newline is counted, so incremental reuse would count the tail twice. - it('does not double-count a counted tail whose newline was not yet written', async () => { - const rolloutPath = join(sessionsDir, 'rollout-unflushed-newline.jsonl') - const complete = usageRecordRange(0, RESUMABLE_RECORDS) - const pending = usageRecord('2026-05-26T12:59:00.000Z', 1, RESUMABLE_RECORDS + 1) - writeFileSync( - rolloutPath, - `${sessionMeta('session-unflushed')}${complete}${pending.slice(0, -1)}`, - 'utf-8' - ) - - const first = await scanCodexUsageFiles([], []) - expect(totalTokens(first.dailyAggregates)).toBe(RESUMABLE_RECORDS + 1) - expect(first.sessions[0]?.eventCount).toBe(RESUMABLE_RECORDS + 1) - // A large prefix ensures the missing newline alone suppresses the checkpoint. - expect(first.processedFiles[0]?.parseResumeState).toBeNull() - - appendFileSync( - rolloutPath, - `\n${usageRecordRange(RESUMABLE_RECORDS + 1, RESUMABLE_RECORDS + 2)}`, - 'utf-8' - ) - - streamReads.length = 0 - const second = await scanCodexUsageFiles([], first.processedFiles) - expect(parseReadOffsets(rolloutPath)).toEqual([0]) - const fromScratch = await scanCodexUsageFiles([], []) - expect(totalTokens(second.dailyAggregates)).toBe(RESUMABLE_RECORDS + 2) - expect(second.sessions[0]?.eventCount).toBe(RESUMABLE_RECORDS + 2) - expect(second.dailyAggregates).toEqual(fromScratch.dailyAggregates) - }) - - it('keeps fork ownership when the owning rollout grows incrementally', async () => { - const originalPath = join(sessionsDir, 'aaaa-original.jsonl') - const forkPath = join(sessionsDir, 'zzzz-fork.jsonl') - const copiedPrefix = `${sessionMeta('session-fork')}${usageRecordRange(0, RESUMABLE_RECORDS)}` - writeFileSync(originalPath, copiedPrefix, 'utf-8') - writeFileSync( - forkPath, - `${copiedPrefix}${usageRecordRange(RESUMABLE_RECORDS, RESUMABLE_RECORDS + 2)}`, - 'utf-8' - ) - - const first = await scanCodexUsageFiles([], []) - expect(totalTokens(first.dailyAggregates)).toBe(RESUMABLE_RECORDS + 2) - expect(first.processedFiles.find((file) => file.path === originalPath)?.ownedEventKeys).toEqual( - expect.arrayContaining([expect.any(String)]) - ) - - const resumeOffset = recordedResumeOffset(first.processedFiles, originalPath) - appendFileSync( - originalPath, - usageRecordRange(RESUMABLE_RECORDS + 2, RESUMABLE_RECORDS + 4), - 'utf-8' - ) - - streamReads.length = 0 - const second = await scanCodexUsageFiles([], first.processedFiles) - expect(parseReadOffsets(originalPath)).toEqual([resumeOffset]) - // Shared prefix + two fork-only records + two appended records, each counted once. - expect(totalTokens(second.dailyAggregates)).toBe(RESUMABLE_RECORDS + 4) - const originalAfter = second.processedFiles.find((file) => file.path === originalPath) - const forkAfter = second.processedFiles.find((file) => file.path === forkPath) - expect(originalAfter?.ownedEventKeys).toHaveLength(RESUMABLE_RECORDS + 2) - expect(forkAfter?.ownedEventKeys).toHaveLength(2) - expect(forkAfter?.hasDeferredClaims).toBe(true) - }) - - it('keeps a new fork from re-claiming events a resumed rollout still owns', async () => { - const originalPath = join(sessionsDir, 'aaaa-origin.jsonl') - const forkPath = join(sessionsDir, 'zzzz-late-fork.jsonl') - const copiedPrefix = `${sessionMeta('session-late')}${usageRecordRange(0, RESUMABLE_RECORDS)}` - writeFileSync(originalPath, copiedPrefix, 'utf-8') - - const first = await scanCodexUsageFiles([], []) - expect(totalTokens(first.dailyAggregates)).toBe(RESUMABLE_RECORDS) - const resumeOffset = recordedResumeOffset(first.processedFiles, originalPath) - - appendFileSync( - originalPath, - usageRecordRange(RESUMABLE_RECORDS, RESUMABLE_RECORDS + 2), - 'utf-8' - ) - writeFileSync( - forkPath, - `${copiedPrefix}${usageRecordRange(RESUMABLE_RECORDS + 2, RESUMABLE_RECORDS + 3)}`, - 'utf-8' - ) - - streamReads.length = 0 - const second = await scanCodexUsageFiles([], first.processedFiles) - expect(parseReadOffsets(originalPath)).toEqual([resumeOffset]) - expect(totalTokens(second.dailyAggregates)).toBe(RESUMABLE_RECORDS + 3) - const forkAfter = second.processedFiles.find((file) => file.path === forkPath) - expect(forkAfter?.ownedEventKeys).toHaveLength(1) - expect(forkAfter?.hasDeferredClaims).toBe(true) - }) - - // Released ownership must let a fork count records lost from the rewritten file. - it('lets a fork reclaim records a rewritten rollout can no longer own', async () => { - const originalPath = join(sessionsDir, 'aaaa-rewritten.jsonl') - const forkPath = join(sessionsDir, 'zzzz-inheritor.jsonl') - const sharedPrefix = `${sessionMeta('session-shared')}${usageRecordRange(0, 40)}` - writeFileSync(originalPath, sharedPrefix, 'utf-8') - - const first = await scanCodexUsageFiles([], []) - expect(totalTokens(first.dailyAggregates)).toBe(40) - - writeFileSync( - originalPath, - `${sessionMeta('session-rewritten')}${usageRecordRange(100, 140)}`, - 'utf-8' - ) - writeFileSync(forkPath, `${sharedPrefix}${usageRecordRange(40, 43)}`, 'utf-8') - - const second = await scanCodexUsageFiles([], first.processedFiles) - const fromScratch = await scanCodexUsageFiles([], []) - expect(eventCountsBySession(second.sessions)).toEqual( - eventCountsBySession(fromScratch.sessions) - ) - expect(totalTokens(second.dailyAggregates)).toBe(83) - }) - - it('still reclaims deferred fork claims after an incremental append', async () => { - const originalPath = join(sessionsDir, 'aaaa-owner.jsonl') - const forkPath = join(sessionsDir, 'zzzz-deferred.jsonl') - const copiedPrefix = `${sessionMeta('session-deferred')}${usageRecordRange(0, RESUMABLE_RECORDS)}` - writeFileSync(originalPath, copiedPrefix, 'utf-8') - writeFileSync( - forkPath, - `${copiedPrefix}${usageRecordRange(RESUMABLE_RECORDS, RESUMABLE_RECORDS + 2)}`, - 'utf-8' - ) - - const first = await scanCodexUsageFiles([], []) - const resumeOffset = recordedResumeOffset(first.processedFiles, forkPath) - // Appending must preserve the deferred flag so the fork can later reclaim the prefix. - appendFileSync( - forkPath, - usageRecordRange(RESUMABLE_RECORDS + 2, RESUMABLE_RECORDS + 4), - 'utf-8' - ) - streamReads.length = 0 - const second = await scanCodexUsageFiles([], first.processedFiles) - expect(parseReadOffsets(forkPath)).toEqual([resumeOffset]) - expect(totalTokens(second.dailyAggregates)).toBe(RESUMABLE_RECORDS + 4) - expect(second.processedFiles.find((file) => file.path === forkPath)?.hasDeferredClaims).toBe( - true - ) - - rmSync(originalPath) - const third = await scanCodexUsageFiles([], second.processedFiles) - expect(third.processedFiles).toHaveLength(1) - expect(third.processedFiles[0]?.ownedEventKeys).toHaveLength(RESUMABLE_RECORDS + 4) - expect(totalTokens(third.dailyAggregates)).toBe(RESUMABLE_RECORDS + 4) - }) }) diff --git a/src/main/codex-usage/scanner.ts b/src/main/codex-usage/scanner.ts index 1cc78258216..cdd1acf0d95 100644 --- a/src/main/codex-usage/scanner.ts +++ b/src/main/codex-usage/scanner.ts @@ -1,4 +1,4 @@ -import { createUsageWorktreeResolver } from '../usage/usage-worktree-resolver' +import { createUsageWorktreeResolver } from '../usage/worktree-attribution/usage-worktree-resolver' import { getLegacySourceSkipBytesByPath, listCodexSessionFiles, diff --git a/src/main/codex-usage/store-automation-usage.test.ts b/src/main/codex-usage/store-automation-usage.test.ts deleted file mode 100644 index ca0f8581bc3..00000000000 --- a/src/main/codex-usage/store-automation-usage.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -import { scanCodexUsageFilesViaWorker } from '../usage/usage-scan-worker-spawn' -import { - createStoreWithState, - createWorktreeUsageSession, - setupCodexUsageStoreEnv -} from './store-test-harness' - -const { getPathMock } = vi.hoisted(() => ({ - getPathMock: vi.fn(() => '/tmp/orca-test-userdata') -})) - -vi.mock('electron', () => ({ - app: { - getPath: getPathMock - } -})) - -vi.mock('../usage/usage-scan-worker-spawn', () => ({ - scanCodexUsageFilesViaWorker: vi.fn(), - splitUsageCacheFileViaWorker: vi.fn() -})) - -describe('CodexUsageStore', () => { - setupCodexUsageStoreEnv(getPathMock) - - it('joins a scan that is already in flight when the run finished before it started', async () => { - const worktreeId = 'repo-1::/workspace/repo' - const store = createStoreWithState({ - scanState: { - enabled: true, - lastScanStartedAt: null, - lastScanCompletedAt: null, - lastScanError: null - } - }) - // Prime the fingerprint so an unforced refresh can return early. - await store.refresh(true) - - const completedAt = Date.now() + 10_000 - vi.setSystemTime(new Date(completedAt + 1_000)) - - let startScan = () => {} - let finishScan = () => {} - const scanStarted = new Promise((resolve) => { - startScan = resolve - }) - const scanFinished = new Promise((resolve) => { - finishScan = resolve - }) - vi.mocked(scanCodexUsageFilesViaWorker).mockImplementationOnce(async () => { - startScan() - await scanFinished - return { - processedFiles: [], - sessions: [createWorktreeUsageSession(worktreeId)], - dailyAggregates: [] - } - }) - - const inFlight = store.refresh(true) - await scanStarted - - const usage = store.getAutomationRunUsage({ - worktreeId, - terminalSessionId: 'session-1', - startedAt: completedAt - 60_000, - completedAt - }) - finishScan() - await inFlight - - expect((await usage).status).toBe('known') - expect((await usage).providerSessionId).toBe('session-1') - }) -}) diff --git a/src/main/codex-usage/store-persistence.test.ts b/src/main/codex-usage/store-persistence.test.ts deleted file mode 100644 index 96294174cc3..00000000000 --- a/src/main/codex-usage/store-persistence.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { readFileSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import { setupCodexUsageStoreEnv } from './store-test-harness' - -const { getPathMock } = vi.hoisted(() => ({ - getPathMock: vi.fn(() => '/tmp/orca-test-userdata') -})) - -vi.mock('electron', () => ({ - app: { - getPath: getPathMock - } -})) - -vi.mock('../usage/usage-scan-worker-spawn', () => ({ - scanCodexUsageFilesViaWorker: vi.fn(), - splitUsageCacheFileViaWorker: vi.fn() -})) - -import { CodexUsageStore } from './store' -import { CODEX_USAGE_SCHEMA_VERSION } from './codex-usage-provider' -import { scanCodexUsageFilesViaWorker } from '../usage/usage-scan-worker-spawn' - -describe('CodexUsageStore', () => { - const storeEnv = setupCodexUsageStoreEnv(getPathMock) - - it('rescans from scratch when the cache predates per-request long-context counts', async () => { - const scanMock = vi.mocked(scanCodexUsageFilesViaWorker) - const sourceCachePath = join(storeEnv.tempUserData, 'orca-codex-usage-sources.json') - const cacheFile = join(storeEnv.tempUserData, 'orca-codex-usage.json') - const seeded = new CodexUsageStore({ getRepos: () => [], getAllWorktreeMeta: () => ({}) }) - await seeded.setEnabled(true) - await seeded.refresh(true) - await seeded.flush() - const current = readFileSync(cacheFile, 'utf-8') - - scanMock.mockClear() - await new CodexUsageStore({ getRepos: () => [], getAllWorktreeMeta: () => ({}) }).refresh(true) - expect(scanMock).toHaveBeenLastCalledWith([], { - path: sourceCachePath, - schemaVersion: CODEX_USAGE_SCHEMA_VERSION, - worktreeFingerprint: '[]', - reuse: true - }) - - writeFileSync(cacheFile, JSON.stringify({ ...JSON.parse(current), schemaVersion: 5 })) - scanMock.mockClear() - await new CodexUsageStore({ getRepos: () => [], getAllWorktreeMeta: () => ({}) }).refresh(false) - expect(scanMock).toHaveBeenLastCalledWith([], { - path: sourceCachePath, - schemaVersion: CODEX_USAGE_SCHEMA_VERSION, - worktreeFingerprint: '[]', - reuse: false - }) - }) -}) diff --git a/src/main/codex-usage/store-test-harness.ts b/src/main/codex-usage/store-test-harness.ts index caab6237d71..8267abf6909 100644 --- a/src/main/codex-usage/store-test-harness.ts +++ b/src/main/codex-usage/store-test-harness.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, vi } from 'vitest' import type { Mock } from 'vitest' -import { scanCodexUsageFilesViaWorker } from '../usage/usage-scan-worker-spawn' +import { scanCodexUsageFilesViaWorker } from '../usage/scan-worker/usage-scan-worker-spawn' import { CodexUsageStore, initCodexUsagePath } from './store' import type { CodexUsagePersistedState } from './types' diff --git a/src/main/codex-usage/store.ts b/src/main/codex-usage/store.ts index aa7e6ff436e..7e5f5515c4b 100644 --- a/src/main/codex-usage/store.ts +++ b/src/main/codex-usage/store.ts @@ -1,4 +1,4 @@ -import { codexOpenCodeTokenSessions } from '../usage/agent-token-usage' +import { codexOpenCodeTokenSessions } from '../usage/reporting/token-usage/agent-token-usage' import { app } from 'electron' import { join } from 'node:path' import type { @@ -19,8 +19,8 @@ import { CODEX_USAGE_SCHEMA_VERSION, codexUsageProvider } from './codex-usage-pr import { resolveCodexAutomationRunUsage } from './codex-automation-run-attribution' import { buildRecentSessions } from './codex-usage-session-rows' import { buildBreakdown, buildDaily, buildSummary } from './codex-usage-rollup-projections' -import { UsageProviderStoreLifecycle } from '../usage/usage-provider-store-lifecycle' -import { splitUsageCacheFileViaWorker } from '../usage/usage-scan-worker-spawn' +import { UsageProviderStoreLifecycle } from '../usage/provider-lifecycle/usage-provider-store-lifecycle' +import { splitUsageCacheFileViaWorker } from '../usage/scan-worker/usage-scan-worker-spawn' const SCHEMA_VERSION = CODEX_USAGE_SCHEMA_VERSION diff --git a/src/main/codex/history/rollouts/codex-rollout-session-meta.test.ts b/src/main/codex/history/rollouts/codex-rollout-session-meta.test.ts index 799c5123275..e24e4c72115 100644 --- a/src/main/codex/history/rollouts/codex-rollout-session-meta.test.ts +++ b/src/main/codex/history/rollouts/codex-rollout-session-meta.test.ts @@ -1,6 +1,7 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { zstdCompressSync } from 'node:zlib' import { afterEach, describe, expect, it, vi } from 'vitest' import type * as WslFsAccessModule from '../../../native-chat/wsl-transcript-fs-access' import { readCodexRolloutSessionMetaId } from './codex-rollout-session-meta' @@ -44,6 +45,22 @@ describe('readCodexRolloutSessionMetaId', () => { await expect(readCodexRolloutSessionMetaId(malformed)).resolves.toBeNull() }) + it('reads the session id from a compressed rollout', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-codex-session-meta-')) + tempRoots.push(root) + const rollout = join(root, 'rollout.jsonl.zst') + await writeFile( + rollout, + zstdCompressSync( + Buffer.from( + `${JSON.stringify({ type: 'session_meta', payload: { id: 'archived-id' } })}\nignored\n` + ) + ) + ) + + await expect(readCodexRolloutSessionMetaId(rollout)).resolves.toBe('archived-id') + }) + it('surfaces an aborted read instead of reporting an unprovable rollout', async () => { const root = await mkdtemp(join(tmpdir(), 'orca-codex-session-meta-')) tempRoots.push(root) diff --git a/src/main/codex/history/rollouts/codex-rollout-session-meta.ts b/src/main/codex/history/rollouts/codex-rollout-session-meta.ts index 0cffe593b2a..74317f0f5de 100644 --- a/src/main/codex/history/rollouts/codex-rollout-session-meta.ts +++ b/src/main/codex/history/rollouts/codex-rollout-session-meta.ts @@ -1,4 +1,12 @@ -import { readTranscriptSlice } from '../../../native-chat/wsl-transcript-fs-access' +import { + openTranscriptReadStream, + readTranscriptSlice +} from '../../../native-chat/wsl-transcript-fs-access' +import { + isZstdTranscriptPath, + readZstdTranscriptSlice, + zstdTranscriptStream +} from '../../../native-chat/transcript-zstd-decompression' import type { WslTranscriptFsTaskPriority } from '../../../native-chat/wsl-transcript-fs-gate' const ROLLOUT_READ_LIMIT = 64 * 1024 @@ -12,7 +20,12 @@ export async function readCodexRolloutSessionMetaId( let head: Buffer try { // The transcript gate bounds stalled WSL reads; missing or pruned rollouts cannot abort a scan (#15453). - head = await readTranscriptSlice(filePath, 0, ROLLOUT_READ_LIMIT, priority, signal) + head = isZstdTranscriptPath(filePath) + ? await readZstdTranscriptSlice( + zstdTranscriptStream(openTranscriptReadStream(filePath, {}, priority, signal)), + ROLLOUT_READ_LIMIT + ) + : await readTranscriptSlice(filePath, 0, ROLLOUT_READ_LIMIT, priority, signal) } catch (error) { // Preserve cancellation instead of treating it as an unreadable rollout. if (signal?.aborted) { diff --git a/src/main/codex/structured/threads/codex-structured-thread-catch-up-echo.spec.ts b/src/main/codex/structured/threads/codex-structured-thread-catch-up-echo.spec.ts deleted file mode 100644 index 0508ae44a4d..00000000000 --- a/src/main/codex/structured/threads/codex-structured-thread-catch-up-echo.spec.ts +++ /dev/null @@ -1,425 +0,0 @@ -import { registerCodexHistorySourcesTests } from './codex-structured-thread-catch-up-sources.spec' -import { registerCodexHistoryVariantsTests } from './codex-structured-thread-catch-up-variants.spec' -import { registerCodexHistoryBoundsTests } from './codex-structured-thread-catch-up-bounds.spec' -import { - adapterFor, - fakeCodex, - acquireReadyCodexForTest -} from '../session-lifecycle/codex-structured-session-adapter-fixture' -import { codexProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { journalItemEchoFields } from '../../../native-chat/agent-session-journal/projection/journal-item-echo' -import { expect, it } from 'vitest' -import { codexTurnLifecycleIdentity } from '../journal/codex-structured-journal-translation-turns' -import { - type AgentJournalMessageItem, - AGENT_JOURNAL_THREAD_SCOPE -} from '../../../../shared/agent-session/journal/agent-session-journal-types' -import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type { - chat as catchUpChat, - codexWith as catchUpCodexWith, - turn as catchUpTurn -} from './codex-thread-catch-up-contract-test-fixture' -import { agentSessionSendBodyFingerprint } from '../../../../shared/agent-session/requests/structured-agent-session-send-mutation' -import { agentSessionFailureFact } from '../../../../shared/agent-session/failures/agent-session-failure' -import { agentSessionFailureWords } from '../../../../shared/agent-session/failures/agent-session-failure-words' -import { structuredRewindCut } from '../../../native-chat/agent-session-wire/rewind/structured-rewind-cut' -import { restoreJournal } from '../../../native-chat/agent-session-journal/replay/journal-open' - -export function registerCodexCatchUpEchoTests(input: { - codexWith: typeof catchUpCodexWith - chat: typeof catchUpChat - turn: typeof catchUpTurn - sessionId: string - threadId: string -}): void { - const { chat, turn, codexWith, sessionId: SESSION, threadId: THREAD } = input - registerCodexHistorySourcesTests(input) - registerCodexHistoryVariantsTests(input) - registerCodexHistoryBoundsTests(input) - it('reconciles older completed acquired content and keeps unchanged reacquisition write-free', async () => { - const c = await chat({ now: 1_000 }) - const first = turn(1) - await c.open([], { - returnedTurns: [ - { ...first, items: Array.isArray(first.items) ? first.items.slice(0, 1) : [] } - ], - paginate: false - }) - await c.open([], { returnedTurns: [turn(2)], paginate: false }) - const whole = [turn(1), turn(2)] - await c.open([], { returnedTurns: whole, paginate: false }) - expect(c.texts()).toContain('assistant:answer 1') - const before = c.journal.cursor() - await c.reopen() - await c.open([], { returnedTurns: whole, paginate: false }) - expect(c.journal.cursor()).toEqual(before) - expect(c.texts().filter((text) => text === 'assistant:answer 1')).toHaveLength(1) - }) - - it('uses saved native IDs only for display, preserving sends and drafts through outside echoes and replay', async () => { - const c = await chat({ now: 1_000 }) - const body: AgentJournalMessageItem = { - kind: 'message', - role: 'user', - blocks: [ - { type: 'text', text: 'continue' }, - { type: 'image-ref', path: '/attachment.png' } - ] - } - const fingerprint = agentSessionSendBodyFingerprint(SESSION, body) - await c.journal.queuedMessages.insert({ - messageId: 'draft', - body - }) - const states = ['unknown', 'rejected'] as const - for (const state of states) { - await c.journal.appendSubmission( - { - clientMessageId: state, - body, - payloadFingerprint: fingerprint, - fence: 1, - handoverRecorded: true - }, - state === 'rejected' ? { messageId: 'draft', expect: 'waiting' } : undefined - ) - await c.journal.resolveDispatch({ - clientMessageId: state, - state: 'pending', - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await (state === 'unknown' - ? c.journal.markPendingSubmissionsUnknown(1) - : c.journal.resolveDispatch({ - clientMessageId: state, - state: 'rejected', - ...agentSessionFailureWords(agentSessionFailureFact('cancelled'), { - surface: 'rejection' - }), - fence: 1 - })) - } - await c.reopen() - const before = c.journal.snapshot() - const draft = c.journal.queuedMessages.get('draft') - const receipts = states.map((state) => c.journal.receiptFor(state)) - const native = states.map((state, n) => ({ - ...turn(n + 2), - items: [ - { - type: 'userMessage', - id: `u-${n + 2}`, - clientId: state, - content: [{ type: 'text', text: 'different historical rendering' }] - }, - { type: 'agentMessage', id: `a-${n + 2}`, text: `answer ${n + 2}` } - ] - })) - const outside = { - ...turn(7), - items: [ - { - type: 'userMessage', - id: 'outside', - clientId: 'foreign-request', - content: [ - { type: 'text', text: 'continue' }, - { type: 'localImage', path: '/attachment.png' } - ] - }, - { type: 'agentMessage', id: 'outside-answer', text: 'outside answer' } - ] - } - await c.open([...native, outside]) - expect(c.texts().slice(-4)).toEqual([ - 'assistant:answer 3', - '(continued-outside)', - 'user:continue', - 'assistant:outside answer' - ]) - expect(c.journal.snapshot().items.slice(0, before.items.length)).toEqual(before.items) - expect(states.map((state) => c.journal.receiptFor(state))).toEqual(receipts) - expect(c.texts().filter((text) => text.includes('historical rendering'))).toEqual([]) - expect(c.journal.snapshot().submissions).toEqual(before.submissions) - expect(c.journal.queuedMessages.get('draft')).toEqual(draft) - const outsideKey = agentJournalItemKey({ - provider: 'codex', - threadId: THREAD, - turnId: 'turn-7', - ordinal: 0 - }) - expect(journalItemEchoFields(c.journal.itemProvenance(outsideKey))).toEqual({ echoOf: null }) - const whole = c.journal.snapshot() - await c.reopen() - await c.open([...native, outside]) - expect(c.journal.snapshot()).toEqual(whole) - expect(c.journal.queuedMessages.get('draft')).toEqual(draft) - const restored = restoreJournal(c.db, SESSION) - expect(restored?.state.queue.cards.get('draft')).toEqual(draft) - }) - - it('keeps native display identity after a real retained cut and disk reopen', async () => { - const c = await chat({ now: 1_000 }) - await c.open([turn(1)]) - const clientMessageId = `native-${'u'.repeat(1100)}` - const body: AgentJournalMessageItem = { - kind: 'message', - role: 'user', - blocks: [ - { type: 'text', text: 'original rich prompt' }, - { type: 'image-ref', path: '/kept.png' } - ] - } - await c.journal.appendSubmission({ - clientMessageId, - body, - payloadFingerprint: agentSessionSendBodyFingerprint(SESSION, body), - fence: 1, - handoverRecorded: true - }) - await c.journal.resolveDispatch({ - clientMessageId, - state: 'pending', - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await c.journal.markPendingSubmissionsUnknown(1) - await c.open([turn(1), turn(2), turn(3)]) - const key = agentJournalItemKey({ provider: 'orca', clientMessageId }) - const cut = structuredRewindCut(c.journal, { - itemId: agentJournalItemKey({ - provider: 'codex', - threadId: THREAD, - turnId: 'turn-3', - ordinal: 0 - }), - provider: 'codex', - nativeId: THREAD - }) - if (!cut) { - throw new Error('missing native retention cut') - } - await c.journal.replaceEpochItems('handle_forked', 1, cut.kept) - await c.reopen() - const prompt = c.journal.item(key) - expect(prompt?.body).toEqual(body) - expect(c.journal.submission(clientMessageId)?.dispatchState).toBe('unknown') - const native = { - ...turn(4), - items: [ - { - type: 'userMessage', - id: 'native', - clientId: clientMessageId, - content: [{ type: 'text', text: 'provider rendering' }] - }, - { type: 'agentMessage', id: 'reply', text: 'native answer' } - ] - } - const before = c.journal.snapshot() - const beforeTexts = c.texts() - await c.open([turn(1), turn(2), native]) - expect(c.journal.item(key)).toEqual(prompt) - expect(c.journal.snapshot().items.slice(0, before.items.length)).toEqual(before.items) - expect(c.texts()).toEqual([...beforeTexts, 'assistant:native answer']) - expect(c.journal.submission(clientMessageId)?.dispatchState).toBe('unknown') - expect(c.journal.receiptFor(clientMessageId)).toBeNull() - const whole = c.journal.snapshot() - await c.reopen() - await c.open([turn(1), turn(2), native]) - expect(c.journal.snapshot()).toEqual(whole) - await c.journal.replaceEpochItems('handle_forked', 1, []) - const hidden = c.journal.cursor() - const { readCodexHistoryJournalView } = - await import('../../history/journal-views/codex-history-journal-view') - expect(readCodexHistoryJournalView(c.journal, THREAD, AbortSignal.abort()).latest).toBeNull() - await c.open([native], { - onReceipt: (id, providerIdentity) => - c.journal.acceptLate({ clientMessageId: id, providerIdentity, state: 'accepted', fence: 1 }) - }) - expect(c.journal.submission(clientMessageId)?.dispatchState).toBe('accepted') - expect(c.journal.item(key)).toBeNull() - expect(c.journal.snapshot().items).toEqual([]) - expect(readCodexHistoryJournalView(c.journal, THREAD, AbortSignal.abort()).latest).toBeNull() - expect(c.journal.cursor().epoch).toBe(hidden.epoch) - await c.reopen() - await c.open([native]) - expect(c.journal.snapshot().items).toEqual([]) - }) - - it('completes a represented turn and older gaps through an actual paginated open with partial returned content', async () => { - const c = await chat({ now: 1_000 }) - const original = { - kind: 'message' as const, - role: 'user' as const, - blocks: [{ type: 'text' as const, text: 'native' }] - } - await c.journal.appendSubmission({ - clientMessageId: 'P', - body: original, - payloadFingerprint: 'P', - fence: 1 - }) - await c.journal.resolveDispatch({ - clientMessageId: 'P', - state: 'accepted', - providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-2', ordinal: 0 }, - fence: 1 - }) - const current: Record & { items: Record[] } = { - ...turn(2), - items: [ - { - type: 'userMessage', - id: 'u-2', - clientId: 'P', - content: [{ type: 'text', text: 'native' }] - }, - { type: 'agentMessage', id: 'a-2', text: 'completed answer' } - ] - } - const detailIdentity = { - provider: 'orca' as const, - clientMessageId: `codex-item:${THREAD}:exec-2` - } - await c.journal.appendItem( - detailIdentity, - { kind: 'tool-call', name: 'terminal', input: { command: 'pwd' }, state: 'running' }, - { - fence: 1, - turnScope: { - kind: 'turn', - turnItemId: agentJournalItemKey(codexTurnLifecycleIdentity(SESSION, 'turn-2')) - } - } - ) - current.items.push({ - type: 'commandExecution', - id: 'exec-2', - command: 'pwd', - status: 'completed', - aggregatedOutput: '/workspace', - exitCode: 0 - }) - const first = turn(1) - await c.open([], { - returnedTurns: [ - { ...first, items: Array.isArray(first.items) ? first.items.slice(0, 1) : [] } - ], - paginate: false - }) - const turns = [first, current] - const source = codexWith(turns) - let fullReads = 0 - const codex = fakeCodex({ - 'thread/resume': () => ({ - thread: { - id: THREAD, - historyMode: 'paginated', - turns: [{ ...current, items: current.items.slice(0, 1) }] - } - }), - 'thread/turns/list': async (params) => { - if (params?.itemsView === 'full') { - fullReads++ - } - const page = await source.request('thread/turns/list', params) - return params?.itemsView === 'summary' - ? { - ...page, - data: page.data.map((turn) => ({ - ...turn, - itemsView: 'summary', - items: Array.isArray(turn.items) ? turn.items.slice(0, 2) : [] - })) - } - : page - } - }) - const open = async () => { - const adapter = adapterFor(codex, { resumeThreadId: THREAD }) - try { - await acquireReadyCodexForTest(adapter, { - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - fence: 1, - spawnToken: 'recorded-fixture-child', - events: c.deferred.sink - }) - await c.deferred.drained() - } finally { - await adapter.closeAll() - } - } - await open() - expect(c.texts()).toEqual([ - 'user:native', - '(continued-outside)', - 'user:ask 1', - 'assistant:answer 1', - 'assistant:completed answer' - ]) - expect( - c.journal.snapshot().items.filter((item) => item.body.kind === 'tool-call') - ).toHaveLength(1) - expect(c.journal.item(agentJournalItemKey(detailIdentity))?.body).toMatchObject({ - state: 'completed' - }) - const before = c.journal.cursor() - await open() - expect(c.journal.cursor()).toEqual(before) - expect(fullReads).toBe(1) - const hiddenTool = { - type: 'commandExecution', - id: 'older-tool', - command: 'pwd', - status: 'completed', - aggregatedOutput: '/older', - exitCode: 0 - } - turns[0] = { ...first, items: [...(Array.isArray(first.items) ? first.items : []), hiddenTool] } - await open() - // An identical known summary supplies no discovery signal for unseen intermediate tools. - expect(fullReads).toBe(1) - expect(c.journal.cursor()).toEqual(before) - turns.unshift(turn(0)) - turns.push(turn(3)) - await open() - // The newly selected page also acquires its known sibling's full content. - expect(fullReads).toBe(3) - expect( - c.journal.snapshot().items.filter((item) => item.body.kind === 'tool-call') - ).toHaveLength(2) - const acquired = c.journal.cursor() - await open() - expect(c.journal.cursor()).toEqual(acquired) - // A lifecycle identity alone cannot discard newly supplied current-turn content. - codex.routes['thread/resume'] = () => ({ - thread: { - id: THREAD, - historyMode: 'paginated', - turns: [ - { - ...current, - items: [ - ...current.items, - { type: 'agentMessage', id: 'tail', text: 'final missing tail' } - ] - } - ] - } - }) - await open() - expect(c.texts().at(-1)).toBe('assistant:final missing tail') - await c.reopen() - expect(c.texts().filter((text) => text === 'assistant:completed answer')).toHaveLength(1) - expect(c.texts().at(-1)).toBe('assistant:final missing tail') - }) -} diff --git a/src/main/codex/structured/threads/codex-structured-thread-catch-up-sources.spec.ts b/src/main/codex/structured/threads/codex-structured-thread-catch-up-sources.spec.ts deleted file mode 100644 index 2b563fe8ebc..00000000000 --- a/src/main/codex/structured/threads/codex-structured-thread-catch-up-sources.spec.ts +++ /dev/null @@ -1,497 +0,0 @@ -import { - adapterFor, - fakeCodex, - acquireReadyCodexForTest -} from '../session-lifecycle/codex-structured-session-adapter-fixture' -import { codexProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { expect, it, vi } from 'vitest' -import { codexTurnLifecycleIdentity } from '../journal/codex-structured-journal-translation-turns' -import { journalPayload } from '../../../native-chat/agent-session-journal/item-lifecycle/journal-payload-bounds' -import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type { - chat as catchUpChat, - codexWith as catchUpCodexWith, - turn as catchUpTurn -} from './codex-thread-catch-up-contract-test-fixture' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session/journal/agent-session-journal-types' - -export function registerCodexHistorySourcesTests(input: { - codexWith: typeof catchUpCodexWith - chat: typeof catchUpChat - turn: typeof catchUpTurn - sessionId: string - threadId: string -}): void { - const { chat, turn, sessionId: SESSION, threadId: THREAD } = input - it.each(['completed', 'failed', 'interrupted'] as const)( - 'reconciles an actual paginated opener from partial to non-prefix %s content once', - async (status) => { - const c = await chat({ now: 1_000 }) - const transitions = vi.spyOn(c.deferred.sink, 'tryAppendTransition') - const supplied = { - ...turn(1), - status: 'inProgress', - completedAt: undefined, - items: [ - { type: 'userMessage', id: 'u-old', content: [{ type: 'text', text: 'ask 1' }] }, - { type: 'agentMessage', id: 'a-old', text: 'tentative draft' }, - { - type: 'commandExecution', - id: 'cmd', - command: 'pwd', - cwd: '/workspace', - status: 'inProgress' - } - ] - } - const acquired = { - ...turn(1), - status, - items: [ - { type: 'userMessage', id: 'u-new', content: [{ type: 'text', text: 'ask 1' }] }, - { type: 'agentMessage', id: 'a-new', text: 'A different final answer' }, - { - type: 'commandExecution', - id: 'cmd', - command: 'pwd', - cwd: '/workspace', - status: 'completed', - aggregatedOutput: '/workspace', - exitCode: 0 - }, - { - type: 'mcpToolCall', - id: 'mcp', - server: 'files', - tool: 'read', - arguments: { path: 'a' }, - status: 'completed', - result: { content: [{ type: 'text', text: 'contents' }] } - } - ] - } - const codex = fakeCodex({ - 'thread/resume': () => ({ - thread: { id: THREAD, historyMode: 'paginated', turns: [supplied] } - }), - 'thread/turns/list': (params) => ({ - data: [ - params?.itemsView === 'summary' - ? { ...acquired, itemsView: 'summary', items: [] } - : acquired - ], - nextCursor: null - }) - }) - const open = async () => { - const adapter = adapterFor(codex, { resumeThreadId: THREAD }) - try { - await acquireReadyCodexForTest(adapter, { - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - fence: 1, - spawnToken: 'evolving-history', - events: c.deferred.sink - }) - await c.deferred.drained() - } finally { - await adapter.closeAll() - } - } - await open() - expect(c.texts()).toEqual(['user:ask 1', 'assistant:A different final answer']) - const rows = c.journal.snapshot().items - expect(new Set(rows.map((row) => row.itemId)).size).toBe(rows.length) - expect(rows.find((row) => row.body.kind === 'turn')?.body).toMatchObject({ - kind: 'turn', - state: status === 'interrupted' ? 'interrupted' : 'completed', - outcome: - status === 'completed' ? 'success' : status === 'failed' ? 'failure' : 'cancellation', - startedAt: (1_700_000_000 + 100) * 1000, - completedAt: (1_700_000_000 + 150) * 1000 - }) - expect(rows.filter((row) => row.body.kind === 'tool-call').map((row) => row.body)).toEqual([ - expect.objectContaining({ state: 'completed', output: journalPayload('/workspace') }), - expect.objectContaining({ state: 'completed', output: journalPayload('contents') }) - ]) - expect(new Set(rows.map((row) => row.sequence)).size).toBe(1) - const imports = () => - transitions.mock.calls.flatMap(([call]) => - call.steps.filter( - (step) => - step.kind === 'settlement' && step.settlementId.startsWith('codex-history-import:') - ) - ) - expect(imports()).toHaveLength(1) - const snapshot = c.journal.snapshot() - await c.reopen() - expect(c.journal.snapshot()).toEqual(snapshot) - const repeated = vi.spyOn(c.deferred.sink, 'tryAppendTransition') - await open() - expect(c.journal.snapshot()).toEqual(snapshot) - await c.open([], { - paginate: false, - returnedTurns: [ - { - ...acquired, - items: [ - { type: 'commandExecution', id: 'cmd' }, - { type: 'mcpToolCall', id: 'mcp' } - ] - } - ] - }) - expect(c.journal.snapshot()).toEqual(snapshot) - expect( - repeated.mock.calls.flatMap(([call]) => - call.steps.filter( - (step) => - step.kind === 'settlement' && step.settlementId.startsWith('codex-history-import:') - ) - ) - ).toEqual([]) - } - ) - - it('anchors omitted and later parents while rejecting a different invocation', async () => { - const c = await chat({ now: 1_000 }) - const parent = { - type: 'commandExecution', - id: 'parent', - command: 'pwd', - status: 'completed', - aggregatedOutput: 'retained' - } - await c.open([], { paginate: false, returnedTurns: [{ ...turn(1), items: [parent] }] }) - await c.open([], { paginate: false, returnedTurns: [turn(2)] }) - const legacy = { - provider: 'orca' as const, - clientMessageId: `codex-history-item:${JSON.stringify([1, THREAD, 'turn-1', 'legacy-parent'])}` - } - await c.journal.appendItem( - legacy, - { - kind: 'tool-call', - name: 'shell', - callId: 'legacy-parent', - input: { command: 'legacy' }, - state: 'completed' - }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - const legacySaved = c.journal.item(agentJournalItemKey(legacy)) - await c.reopen() - await c.open([], { - paginate: false, - returnedTurns: [ - { - ...turn(1), - items: [ - { - type: 'plan', - id: 'omitted-child', - parentCallId: 'parent', - text: 'omitted parent child' - }, - { - type: 'plan', - id: 'legacy-child', - parentCallId: 'legacy-parent', - text: 'legacy parent child' - } - ] - } - ] - }) - expect(c.journal.snapshot().items.map(({ body }) => body)).toContainEqual( - expect.objectContaining({ kind: 'status', text: 'omitted parent child' }) - ) - await c.open([], { - paginate: false, - returnedTurns: [ - { - ...turn(1), - items: [ - { ...parent, aggregatedOutput: 'refused result' }, - { type: 'plan', id: 'child', parentCallId: 'parent', text: 'saved parent child' }, - { - type: 'plan', - id: 'early-child', - parentCallId: 'later-parent', - text: 'later parent child' - }, - { type: 'commandExecution', id: 'later-parent', command: 'ls', status: 'completed' } - ] - } - ] - }) - const bodies = c.journal.snapshot().items.map(({ body }) => body) - expect(bodies).toContainEqual( - expect.objectContaining({ kind: 'status', text: 'saved parent child' }) - ) - expect(bodies).toContainEqual( - expect.objectContaining({ kind: 'status', text: 'later parent child' }) - ) - expect(bodies).toContainEqual( - expect.objectContaining({ - kind: 'tool-call', - callId: 'parent', - output: journalPayload('retained') - }) - ) - const before = c.journal.snapshot() - await c.open([], { - paginate: false, - returnedTurns: [ - { - ...turn(1), - items: [ - { ...parent, command: 'different invocation' }, - { type: 'plan', id: 'bad-child', parentCallId: 'parent', text: 'must not attach' } - ] - } - ] - }) - expect(c.journal.snapshot()).toEqual(before) - await c.reopen() - expect(c.journal.item(agentJournalItemKey(legacy))).toEqual(legacySaved) - const snapshot = c.journal.snapshot() - const turnKey = agentJournalItemKey(codexTurnLifecycleIdentity(SESSION, 'turn-1')) - for (const text of [ - 'omitted parent child', - 'saved parent child', - 'later parent child', - 'legacy parent child' - ]) { - const child = snapshot.items.find(({ body }) => body.kind === 'status' && body.text === text) - expect(child?.turnScope).toEqual({ kind: 'turn', turnItemId: turnKey }) - } - }) - - it('conserves saved invocation facts after disk reopen without adopting incompatible dependents', async () => { - const c = await chat({ now: 1_000 }) - const open = async (turns: Record[]) => { - const adapter = adapterFor( - fakeCodex({ - 'thread/resume': () => ({ thread: { id: THREAD, turns } }) - }), - { resumeThreadId: THREAD } - ) - try { - await acquireReadyCodexForTest(adapter, { - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - fence: 1, - spawnToken: 'saved-invocation-facts', - events: c.deferred.sink - }) - await c.deferred.drained() - } finally { - await adapter.closeAll() - } - } - const mcp = { - type: 'mcpToolCall', - server: 's', - tool: 'lookup', - arguments: {}, - status: 'completed' - } - const command = { type: 'commandExecution', command: 'pwd', cwd: '/work', status: 'completed' } - const collisions = [ - { id: 'mcp-command', saved: mcp, incoming: command }, - { - id: 'mcp-file', - saved: mcp, - incoming: { type: 'fileChange', changes: [{ path: 'a', diff: '+a' }] } - }, - { - id: 'mcp-web', - saved: mcp, - incoming: { - type: 'webSearch', - query: 'lookup', - action: { type: 'search', query: 'lookup' } - } - }, - { - id: 'mcp-collab', - saved: mcp, - incoming: { - type: 'collabAgentToolCall', - tool: 'sendInput', - prompt: 'lookup', - status: 'completed' - } - }, - { id: 'command-mcp', saved: command, incoming: mcp }, - { - id: 'command-web', - saved: command, - incoming: { type: 'webSearch', query: 'pwd', action: { type: 'search', query: 'pwd' } } - }, - { - id: 'collab-command', - saved: { - type: 'collabAgentToolCall', - tool: 'sendInput', - prompt: 'retained input', - status: 'completed' - }, - incoming: command - } - ] - const placeholder = { type: 'fileChange', id: 'patch', status: 'inProgress' } - const source = { - ...turn(1), - items: [ - ...collisions.map(({ id, saved }) => ({ ...saved, id })), - { ...command, id: 'sparse-command' }, - placeholder - ] - } - await open([source]) - const saved = collisions.map(({ id }) => - c.journal.snapshot().items.find(({ body }) => body.kind === 'tool-call' && body.callId === id) - ) - expect(saved).toHaveLength(collisions.length) - for (const row of saved) { - expect(row?.body.kind).toBe('tool-call') - } - expect(saved[0]?.body).toMatchObject({ - mcpIdentity: { server: 's', tool: 'lookup' }, - input: null - }) - const sparse = c.journal - .snapshot() - .items.find(({ body }) => body.kind === 'tool-call' && body.callId === 'sparse-command') - expect(sparse?.body).toMatchObject({ - kind: 'tool-call', - input: { command: 'pwd', cwd: '/work' } - }) - const originalPatch = c.journal - .snapshot() - .items.find(({ body }) => body.kind === 'tool-call' && body.callId === 'patch') - expect(originalPatch?.revision).toBe(1) - await c.reopen() - const transitions = vi.spyOn(c.deferred.sink, 'tryAppendTransition') - const incoming = { - ...source, - items: [ - ...collisions.flatMap(({ id, incoming }) => [ - { ...incoming, id }, - { type: 'plan', id: `bad-child-${id}`, parentCallId: id, text: `must not attach ${id}` } - ]), - { type: 'commandExecution', id: 'sparse-command' }, - { ...placeholder, status: 'completed', changes: [{ path: 'a', diff: '+a' }] }, - { type: 'plan', id: 'good', text: 'independent good display' } - ] - } - await open([incoming, turn(2)]) - for (const row of saved) { - expect(row && c.journal.item(row.itemId)).toEqual(row) - } - expect(sparse && c.journal.item(sparse.itemId)).toEqual(sparse) - const snapshot = c.journal.snapshot() - expect(snapshot.items.filter(({ body }) => body.kind === 'tool-call')).toEqual([ - ...saved, - sparse - ]) - expect( - snapshot.items.some( - ({ body }) => body.kind === 'status' && body.text.startsWith('must not attach') - ) - ).toBe(false) - const good = snapshot.items.find( - ({ body }) => body.kind === 'status' && body.text === 'independent good display' - ) - expect(good?.turnScope).toEqual({ - kind: 'turn', - turnItemId: agentJournalItemKey(codexTurnLifecycleIdentity(SESSION, 'turn-1')) - }) - expect(snapshot.items.map(({ body }) => body)).toContainEqual({ - kind: 'diff', - path: 'a', - patch: journalPayload('+a') - }) - expect(c.texts()).toEqual([ - '(continued-outside)', - '(plan-document)', - 'user:ask 2', - 'assistant:answer 2' - ]) - expect( - transitions.mock.calls.flatMap(([call]) => - call.steps.filter( - (step) => - step.kind === 'settlement' && step.settlementId.startsWith('codex-history-import:') - ) - ) - ).toHaveLength(1) - const display = snapshot.items.filter( - ({ body }) => - body.kind === 'diff' || (body.kind === 'status' && body.presentation === 'plan-document') - ) - expect(display).toHaveLength(2) - expect(display.find(({ body }) => body.kind === 'diff')).toMatchObject({ - itemId: originalPatch?.itemId, - sequence: originalPatch?.sequence, - sequenceIndex: originalPatch?.sequenceIndex, - turnScope: originalPatch?.turnScope, - revision: 2 - }) - await c.reopen() - expect(c.journal.snapshot()).toEqual(snapshot) - await open([incoming, turn(2)]) - expect(c.journal.snapshot()).toEqual(snapshot) - }) - - it('releases whole-response groups with more than 1024 unchanged saved keys and keeps a small new turn', async () => { - const c = await chat({ now: 1_000 }) - const old = Array.from({ length: 30 }, (_, n) => ({ - ...turn(n), - items: Array.from({ length: 40 }, (_, i) => ({ - type: 'agentMessage', - id: `a-${i}`, - text: `answer ${n}/${i}` - })) - })) - for (const entry of old) { - await c.open([], { paginate: false, returnedTurns: [entry] }) - } - await c.reopen() - const before = c.journal.snapshot() - const commits = vi.spyOn(c.deferred.sink, 'tryAppendTransition') - await c.open([], { paginate: false, returnedTurns: [...old, turn(31)] }) - expect(c.journal.snapshot().items.slice(0, before.items.length)).toEqual(before.items) - expect(c.texts().slice(-2)).toEqual(['user:ask 31', 'assistant:answer 31']) - const imports = commits.mock.calls.flatMap(([call]) => - call.steps.filter( - (step) => - step.kind === 'settlement' && step.settlementId.startsWith('codex-history-import:') - ) - ) - expect(imports).toHaveLength(1) - const snapshot = c.journal.snapshot() - await c.open([], { paginate: false, returnedTurns: [...old, turn(31)] }) - expect(c.journal.snapshot()).toEqual(snapshot) - expect( - commits.mock.calls.flatMap(([call]) => - call.steps.filter( - (step) => - step.kind === 'settlement' && step.settlementId.startsWith('codex-history-import:') - ) - ) - ).toHaveLength(1) - }) -} diff --git a/src/main/codex/structured/threads/codex-structured-thread-catch-up-variants.spec.ts b/src/main/codex/structured/threads/codex-structured-thread-catch-up-variants.spec.ts deleted file mode 100644 index 43ab2c9cabc..00000000000 --- a/src/main/codex/structured/threads/codex-structured-thread-catch-up-variants.spec.ts +++ /dev/null @@ -1,403 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { codexTurnLifecycleIdentity } from '../journal/codex-structured-journal-translation-turns' -import { CodexSubagentExecutions } from '../background-work/codex-subagent-executions' -import { nativeChatTurnMembership } from '../../../../shared/native-chat/transcript/native-chat-turn-membership' -import { projectStructuredItemsToNativeChat } from '../../../../shared/agent-session/view/structured-agent-session-projection' -import { journalPayload } from '../../../native-chat/agent-session-journal/item-lifecycle/journal-payload-bounds' -import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type { - chat as catchUpChat, - codexWith as catchUpCodexWith, - turn as catchUpTurn -} from './codex-thread-catch-up-contract-test-fixture' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session/journal/agent-session-journal-types' - -export function registerCodexHistoryVariantsTests(input: { - codexWith: typeof catchUpCodexWith - chat: typeof catchUpChat - turn: typeof catchUpTurn - sessionId: string - threadId: string -}): void { - const { chat, turn, sessionId: SESSION, threadId: THREAD } = input - it('admits independent large source and transaction domains and diagnoses real workspace and transaction overflow', async () => { - const c = await chat({ now: 1_000 }) - const output = 'x'.repeat(9 * 1024 * 1024) - const large = { - ...turn(1), - items: [ - { - type: 'commandExecution', - id: 'large', - command: 'cat output', - status: 'completed', - aggregatedOutput: output - } - ] - } - await c.open([large], { - returnedTurns: [ - { - ...large, - status: 'inProgress', - completedAt: undefined, - items: [ - { - type: 'commandExecution', - id: 'large', - command: 'cat output', - status: 'inProgress', - aggregatedOutput: 'z'.repeat(9 * 1024 * 1024) - } - ] - } - ] - }) - expect( - c.journal.snapshot().items.find(({ body }) => body.kind === 'tool-call')?.body - ).toMatchObject({ output: journalPayload(output) }) - const snapshot = c.journal.snapshot() - await c.reopen() - const serialize = vi.spyOn(JSON, 'stringify') - await c.open([], { paginate: false, returnedTurns: [large] }) - // The saved body is borrowed; measuring it is not a second serialization of its output. - expect( - serialize.mock.calls.some(([value]) => { - if (typeof value === 'string') { - return value.length > 8 * 1024 * 1024 - } - if (typeof value !== 'object' || value === null) { - return false - } - return ( - ('aggregatedOutput' in value && value.aggregatedOutput === output) || - ('output' in value && - value.output !== null && - typeof value.output === 'object' && - 'head' in value.output && - value.output.head === output) - ) - }) - ).toBe(false) - serialize.mockRestore() - expect(c.journal.snapshot()).toEqual(snapshot) - const warnings = vi.fn() - const logger = { warn: warnings, info: vi.fn(), error: vi.fn(), debug: vi.fn() } - const huge = { - ...turn(2), - items: [ - { - type: 'commandExecution', - id: 'huge', - command: 'cat huge', - status: 'completed', - aggregatedOutput: 'y'.repeat(17 * 1024 * 1024) - } - ] - } - await c.open([], { paginate: false, returnedTurns: [huge], logger }) - expect(c.journal.snapshot()).toEqual(snapshot) - expect( - warnings.mock.calls.some( - ([, fields]) => - fields.error instanceof Error && fields.error.message === 'history-workspace-too-large' - ) - ).toBe(true) - warnings.mockClear() - await c.open([], { - paginate: false, - returnedTurns: [ - { ...large, id: 'turn-2' }, - { ...large, id: 'turn-3' } - ], - logger - }) - expect(c.journal.snapshot()).toEqual(snapshot) - expect( - warnings.mock.calls.some( - ([, fields]) => fields.error instanceof Error && fields.error.message === 'too-large' - ) - ).toBe(true) - }) - - it('checks a retained omitted parent exactly once and refuses a real queued revision without losing the writer', async () => { - const c = await chat({ now: 1_000 }) - const parent = { - provider: 'orca' as const, - clientMessageId: `codex-history-item:${JSON.stringify([1, THREAD, 'turn-1', 'parent'])}` - } - await c.open([], { - paginate: false, - returnedTurns: [ - { - ...turn(1), - items: [ - { - type: 'commandExecution', - id: 'parent', - command: 'pwd', - status: 'completed', - aggregatedOutput: 'first' - } - ] - }, - turn(2) - ] - }) - const old = c.journal.item(agentJournalItemKey(parent)) - if (old?.body.kind !== 'tool-call') { - throw new Error('missing saved parent') - } - const body = old.body - const append = c.deferred.sink.tryAppendTransition?.bind(c.deferred.sink) - if (!append) { - throw new Error('missing transition') - } - const calls = vi - .spyOn(c.deferred.sink, 'tryAppendTransition') - .mockImplementationOnce((transition) => { - c.deferred.sink.appendItem( - parent, - { ...body, output: journalPayload('concurrent writer') }, - { lifecycle: true, turnScope: old.turnScope ?? AGENT_JOURNAL_THREAD_SCOPE } - ) - return append(transition) - }) - await c.open([], { - paginate: false, - returnedTurns: [ - { - ...turn(1), - items: [ - { type: 'plan', id: 'child', parentCallId: 'parent', text: 'must fail stale parent' } - ] - } - ] - }) - expect( - c.journal - .snapshot() - .items.some(({ body }) => body.kind === 'status' && body.text === 'must fail stale parent') - ).toBe(false) - expect(c.journal.item(old.itemId)?.body).toMatchObject({ - output: journalPayload('concurrent writer') - }) - // Execute the captured real resolver against the now-current journal: stale checked dependency rejects the whole plan. - const settlement = calls.mock.calls[0]?.[0].steps.find((step) => step.kind === 'settlement') - expect(settlement?.kind).toBe('settlement') - if (settlement?.kind === 'settlement') { - expect(settlement.resolve(c.journal)).toEqual([]) - } - }) - - it('retains good observations, pre-filter message slots and exact proof around local collisions', async () => { - const c = await chat({ now: 1_000 }) - const helpers = new CodexSubagentExecutions() - const initial = { - ...turn(1), - status: 'inProgress', - completedAt: undefined, - items: [ - { type: 'futureItem', id: 'shadow' }, - { type: 'agentMessage', text: 'malformed slot' }, - { type: 'userMessage', id: 'u-old', text: 'Original question' }, - { type: 'agentMessage', id: 'a-old', text: 'Partial' }, - { - type: 'commandExecution', - id: 'call', - command: 'pwd', - cwd: '/workspace', - status: 'inProgress' - } - ] - } - const final = { - ...turn(1), - items: [ - { type: 'agentMessage', text: 'malformed slot' }, - { type: 'userMessage', id: 'u-new', text: 'Collision question' }, - { type: 'agentMessage', id: 'a-new', text: 'Independent final' }, - { - type: 'commandExecution', - id: 'call', - command: 'rm important', - cwd: '/workspace', - status: 'completed', - aggregatedOutput: 'untrusted' - }, - { - type: 'collabAgentToolCall', - id: 'bad-helper', - parentCallId: 'call', - tool: 'spawnAgent', - prompt: 'Wrong invocation', - receiverThreadIds: ['wrong-helper'], - status: 'completed' - }, - { - type: 'agentMessage', - id: 'bad-result', - parentToolCallId: 'bad-helper', - text: 'Wrong dependent' - }, - { type: 'agentMessage', id: 'good', text: 'Good after refused slot' }, - { - type: 'commandExecution', - id: 'shadow', - command: 'echo good', - status: 'completed', - aggregatedOutput: 'good' - } - ] - } - await c.journal.appendSubmission({ - clientMessageId: 'proof', - payloadFingerprint: 'original', - body: { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'Captured original' }] - }, - fence: 1, - handoverRecorded: true - }) - const proof = { - ...turn(3), - items: [ - { type: 'userMessage', id: 'proof-row', clientId: 'proof', text: 'Provider rendering' }, - { type: 'agentMessage', id: 'answer', text: 'Proof sibling' } - ] - } - const receipts: string[] = [] - await c.open([final, turn(2), proof], { - returnedTurns: [initial], - subagentExecutions: helpers, - onReceipt: async (id, providerIdentity) => { - receipts.push(id) - await c.journal.acceptLate({ - clientMessageId: id, - providerIdentity, - state: 'accepted', - fence: 1 - }) - } - }) - expect(c.texts().filter((text) => !text.startsWith('('))).toEqual([ - 'user:Captured original', - 'user:Original question', - 'assistant:Independent final', - 'assistant:Good after refused slot', - 'user:ask 2', - 'assistant:answer 2', - 'assistant:Proof sibling' - ]) - expect(receipts).toEqual(['proof']) - expect(c.journal.submission('proof')?.dispatchState).toBe('accepted') - expect(helpers.find('wrong-helper')).toBeUndefined() - const row = (ordinal: number) => - c.journal.item( - agentJournalItemKey({ provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal }) - ) - expect(row(0)).toBeNull() - expect(row(1)?.body).toMatchObject({ - role: 'user', - blocks: [{ type: 'text', text: 'Original question' }] - }) - expect(row(3)).toBeNull() - expect(row(4)?.body).toMatchObject({ - role: 'assistant', - blocks: [{ type: 'text', text: 'Good after refused slot' }] - }) - expect( - c.journal - .snapshot() - .items.filter(({ body }) => body.kind === 'tool-call') - .map(({ body }) => body) - ).toEqual([ - expect.objectContaining({ input: { command: 'pwd', cwd: '/workspace' }, state: 'running' }), - expect.objectContaining({ - input: { command: 'echo good', cwd: null }, - state: 'completed', - output: journalPayload('good') - }) - ]) - const saved = c.journal.snapshot() - await c.reopen() - expect(c.journal.snapshot()).toEqual(saved) - expect(c.journal.receiptFor('proof')).not.toBeNull() - }) - - it.each(['completed', 'failed', 'interrupted'] as const)( - 'enriches a saved unknown verdict with %s while conserving settled anchors and context', - async (status) => { - const c = await chat({ now: 1_000 }) - const initial = { ...turn(1), status: 'inProgress', completedAt: undefined } - await c.open([], { returnedTurns: [initial], paginate: false }) - const identity = codexTurnLifecycleIdentity(SESSION, 'turn-1') - const key = agentJournalItemKey(identity) - const old = c.journal.item(key) - if (old?.body.kind !== 'turn') { - throw new Error('missing saved lifecycle') - } - const contextUsage = { window: { tokens: 100_000, capturedAt: 900 } } - await c.journal.appendItem( - identity, - { ...old.body, contextUsage, requestedAt: 500 }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - const original = c.journal.item( - agentJournalItemKey({ provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 0 }) - ) - await c.open([], { returnedTurns: [turn(2)], paginate: false }) - await c.open([], { - returnedTurns: [ - { - ...turn(1), - status, - items: [ - { type: 'userMessage', id: 'renumbered-user', text: 'ask 1' }, - { type: 'agentMessage', id: 'renumbered-answer', text: 'Nonprefix saved update' }, - { type: 'agentMessage', id: 'extra', text: 'Extra same-turn answer' } - ] - } - ], - paginate: false - }) - const updated = c.journal.item(key) - expect(updated?.body).toEqual({ - ...old.body, - contextUsage, - requestedAt: 500, - state: status === 'interrupted' ? 'interrupted' : 'completed', - outcome: - status === 'completed' ? 'success' : status === 'failed' ? 'failure' : 'cancellation', - completedAt: (1_700_000_000 + 150) * 1000 - }) - expect(updated?.sequence).toBe(old.sequence) - expect(c.journal.item(original?.itemId ?? '')).toEqual(original) - await c.reopen() - const extra = c.journal - .snapshot() - .items.find( - ({ body }) => - body.kind === 'message' && - body.blocks.some( - (block) => block.type === 'text' && block.text === 'Extra same-turn answer' - ) - ) - expect(extra?.turnScope).toEqual({ kind: 'turn', turnItemId: key }) - const projected = projectStructuredItemsToNativeChat(c.journal.snapshot().items) - expect( - nativeChatTurnMembership(projected, c.journal.snapshot()).turnKeys[ - projected.findIndex((item) => item.id === extra?.itemId) - ] - ).toBe(original?.itemId) - const settled = c.journal.item(key) - await c.open([], { - returnedTurns: [{ ...turn(1), status: status === 'completed' ? 'failed' : 'completed' }], - paginate: false - }) - expect(c.journal.item(key)).toEqual(settled) - } - ) -} diff --git a/src/main/codex/structured/threads/codex-structured-thread-catch-up.test.ts b/src/main/codex/structured/threads/codex-structured-thread-catch-up.test.ts index 8e9b484a8a7..d5194e95ff4 100644 --- a/src/main/codex/structured/threads/codex-structured-thread-catch-up.test.ts +++ b/src/main/codex/structured/threads/codex-structured-thread-catch-up.test.ts @@ -1,22 +1,6 @@ -import { recordedCodexRollout } from '../../__fixtures__/codex-rollout-recordings' -import { - prepareLegacyTranscriptImport, - importLegacyTranscriptIntoJournal -} from '../../../native-chat/agent-session-journal/history-import/journal-legacy-import' -import { codexNonMessageIdentity } from '../items/codex-thread-item-identity' -import { codexTurnLifecycleIdentity } from '../journal/codex-structured-journal-translation-turns' -import { testEventSinkLogging } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' -import { writeFile } from 'node:fs/promises' -import { codexProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' -import { join } from 'node:path' -import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' -import { openTestAgentSessionRecordStore } from '../../../runtime/agent-session/records/agent-session-record-store-test-harness' -import { recoverStructuredRewind } from '../../../native-chat/agent-session-wire/rewind/structured-rewind-recovery' -import { usableJournalHistoryOrigin } from '../../../native-chat/agent-session-journal/context-epochs/journal-history-origin' -import { describe, expect, it } from 'vitest' -import { registerCodexCatchUpEchoTests } from './codex-structured-thread-catch-up-echo.spec' -import { projectStructuredItemsToNativeChat } from '../../../../shared/agent-session/view/structured-agent-session-projection' -import { createCodexJournalTranslator } from '../journal/codex-structured-journal-translation' +import { describe } from 'vitest' +import { registerCodexHistoryBoundsTests } from './codex-structured-thread-catch-up-bounds.spec' + import { SESSION, THREAD, @@ -25,693 +9,5 @@ import { codexWith } from './codex-thread-catch-up-contract-test-fixture' describe('Codex chat catch-up', () => { - registerCodexCatchUpEchoTests({ chat, turn, codexWith, sessionId: SESSION, threadId: THREAD }) - - it('settles recent unresolved exact proof before unrelated known history or a failed import', async () => { - const c = await chat({ now: 1_000 }) - for (let n = 0; n < 1_030; n++) { - await c.journal.appendItem( - { provider: 'codex', threadId: THREAD, turnId: `turn-${n}`, ordinal: 0 }, - { kind: 'turn', turnId: `turn-${n}`, state: 'completed' }, - { fence: 1, turnScope: { kind: 'thread' } } - ) - await c.journal.appendItem( - { provider: 'codex', threadId: THREAD, turnId: `turn-${n}`, ordinal: 1 }, - { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: `answer ${n}` }] }, - { fence: 1, turnScope: { kind: 'thread' } } - ) - } - const proof = (id: string) => ({ - ...turn(1_029), - items: [ - { - type: 'userMessage', - id: 'receipt', - clientId: id, - content: [{ type: 'text', text: 'rendering' }] - }, - { type: 'userMessage', id: 'accepted', clientId: 'already-accepted', content: [] } - ] - }) - for (const id of ['already-accepted', 'U', 'failed-import']) { - await c.journal.appendSubmission({ - clientMessageId: id, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: id }] }, - payloadFingerprint: id, - fence: 1, - handoverRecorded: true - }) - } - await c.journal.resolveDispatch({ - clientMessageId: 'already-accepted', - state: 'accepted', - providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1029', ordinal: 2 }, - fence: 1 - }) - const settled: string[] = [] - const onReceipt = async ( - clientMessageId: string, - providerIdentity: Extract< - Parameters[0], - { state: 'accepted' } - >['providerIdentity'] - ) => { - settled.push(clientMessageId) - await c.journal.resolveDispatch({ - clientMessageId, - providerIdentity, - state: 'accepted', - fence: 1 - }) - } - const history = Array.from({ length: 1_030 }, (_, n) => turn(n)) - // This known old turn exceeds the independent full-import budget, but need not be translated. - history[0] = { - ...turn(0), - items: Array.from({ length: 2_000 }, (_, n) => ({ - type: 'agentMessage', - id: `large-${n}`, - text: 'old' - })) - } - history[1_029] = proof('U') - await c.open(history, { onReceipt }) - expect(settled).toEqual(['U']) - expect(c.journal.submission('U')?.dispatchState).toBe('accepted') - await c.open([], { - onReceipt, - connection: { - request: async (_method, params) => { - if (params?.itemsView === 'summary') { - throw new Error('unrelated transcript failure') - } - return { data: [proof('failed-import')], nextCursor: null } - } - } - }) - expect(settled).toEqual(['U', 'failed-import']) - await c.reopen() - expect(c.journal.submission('failed-import')?.dispatchState).toBe('accepted') - await c.journal.appendSubmission({ - clientMessageId: 'cancelled', - body: { kind: 'message', role: 'user', blocks: [] }, - payloadFingerprint: 'cancelled', - fence: 1 - }) - await c.open([], { - onReceipt, - assertCurrent: () => { - throw new Error('obsolete open') - }, - connection: { request: async () => ({ data: [proof('cancelled')], nextCursor: null }) } - }) - expect(settled).toEqual(['U', 'failed-import']) - - for (const id of ['old-gap', 'fetched-known', 'V']) { - await c.journal.appendSubmission({ - clientMessageId: id, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'same input' }] }, - payloadFingerprint: id, - fence: 1, - handoverRecorded: true - }) - } - const olderTurns = [ - { - ...proof('old-gap'), - id: 'old-gap-turn', - items: [ - ...proof('old-gap').items, - ...Array.from({ length: 1_100 }, (_, n) => ({ - type: 'agentMessage', - id: `oversized-${n}`, - text: 'answer' - })) - ] - }, - { ...proof('fetched-known'), id: 'turn-0' }, - { ...turn(0), id: 'failing-gap' }, - ...history.slice(1) - ] - const server = codexWith(olderTurns) - await c.open([], { - onReceipt, - connection: { - request: async (method, params) => { - if (params?.itemsView === 'full' && params.cursor === '1028') { - throw new Error('later import page failed') - } - return server.request(method, params) - } - } - }) - // Recent proof stops at 1024 known turns. The oldest import page also contains a known turn. - expect(settled).toEqual(['U', 'failed-import', 'old-gap', 'fetched-known']) - expect( - c.journal.item( - agentJournalItemKey({ - provider: 'codex', - threadId: THREAD, - turnId: 'old-gap-turn', - ordinal: 0 - }) - ) - ).toBeNull() - await c.reopen() - expect(c.journal.submission('old-gap')?.dispatchState).toBe('accepted') - expect(c.journal.submission('fetched-known')?.dispatchState).toBe('accepted') - expect(c.journal.submission('V')?.dispatchState).toBe('rejected') - - for (const n of [100, 1_000]) { - for (const id of [`tail-${n}`, `second-${n}`]) { - await c.journal.appendSubmission({ - clientMessageId: id, - body: { kind: 'message', role: 'user', blocks: [] }, - payloadFingerprint: id, - fence: 1 - }) - } - let visits = 0 - const tail = Array.from({ length: n }, (_, i) => ({ - get type() { - visits++ - return 'agentMessage' - }, - id: `tail-${i}`, - text: 'old answer' - })) - const exact = (id: string) => ({ type: 'userMessage', id, clientId: id, content: [] }) - const ordinals: number[] = [] - await c.open([], { - onReceipt: async (id, identity) => { - if (identity.provider === 'codex') { - ordinals.push(identity.ordinal) - } - await onReceipt(id, identity) - }, - connection: { - request: async (_method, params) => ({ - data: - params?.itemsView === 'summary' - ? [] - : [ - { - ...turn(0), - items: [exact(`tail-${n}`), ...tail, exact(`second-${n}`), ...tail] - } - ], - nextCursor: null - }) - } - }) - // Other unresolved controls remain in this session, so all tail must still be inspected. - expect(ordinals).toEqual([0, n + 1]) - expect(visits).toBeGreaterThanOrEqual(n) - } - - for (const fence of ['abort', 'owner']) { - const abort = new AbortController() - let current = true - const first = `${fence}-committed` - const next = `${fence}-blocked` - for (const id of [first, next]) { - await c.journal.appendSubmission({ - clientMessageId: id, - body: { kind: 'message', role: 'user', blocks: [] }, - payloadFingerprint: id, - fence: 1, - handoverRecorded: true - }) - } - const read = { - signal: abort.signal, - assertCurrent: () => { - if (!current) { - throw new Error('owner changed') - } - }, - onReceipt, - connection: { - request: async () => ({ data: [proof(first), proof(next)], nextCursor: null }) - } - } - await c.open([], { - ...read, - onReceipt: async (id, identity) => { - await onReceipt(id, identity) - if (fence === 'abort') { - abort.abort() - } else { - current = false - } - } - }) - expect(settled).toContain(first) - expect(settled).not.toContain(next) - expect(c.journal.submission(next)?.dispatchState).toBe('pending') - await c.reopen() - expect(c.journal.submission(first)?.dispatchState).toBe('accepted') - expect(c.journal.submission(next)?.dispatchState).toBe('rejected') - expect(c.journal.submission('V')?.dispatchState).toBe('rejected') - // Losing ownership or cancellation during a read forbids a new proof callback. - const blocked = new AbortController() - current = true - await c.open([], { - ...read, - signal: blocked.signal, - connection: { - request: async () => { - if (fence === 'abort') { - blocked.abort() - } else { - current = false - } - return { data: [proof(next)], nextCursor: null } - } - } - }) - expect(settled).not.toContain(next) - } - }) - - it('retains the complete outside answer tail through catch-up, disk reopen and display', async () => { - const c = await chat({ now: 1_000 }) - await c.open([turn(1)]) - const answer = `${'outside answer paragraph\n'.repeat(1_024)}END-OF-OUTSIDE-ANSWER-30883` - const outside = { ...turn(2), items: [{ type: 'agentMessage', id: 'a-2', text: answer }] } - await c.open([turn(1), outside]) - await c.reopen() - const items = c.journal.snapshot().items - const stored = items.find( - (item) => - item.body.kind === 'message' && - item.body.role === 'assistant' && - item.body.blocks.some((block) => block.type === 'text' && block.text === answer) - ) - expect(stored?.body).toEqual({ - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: answer }] - }) - const displayed = projectStructuredItemsToNativeChat(items).flatMap((message) => message.blocks) - expect(displayed).toContainEqual({ type: 'text', text: answer }) - }) - - it('recovers an older gap behind newer native work after a failed read and restart', async () => { - const c = await chat({ now: 1_000 }) - await c.open([turn(1)]) - const failed = { - request: async () => { - throw new Error('read failed') - } - } - await c.open([turn(1), turn(2)], { connection: failed }) - const native = createCodexJournalTranslator({ - sink: c.deferred.sink, - sessionId: SESSION, - primaryThreadId: () => THREAD - }) - for (const [method, params] of [ - ['turn/started', { turn: { id: 'turn-3' } }], - [ - 'item/completed', - { turnId: 'turn-3', item: { type: 'agentMessage', id: 'native', text: 'native C' } } - ], - ['turn/completed', { turn: { id: 'turn-3', status: 'completed' } }] - ] as const) { - native.handle({ type: 'notification', sessionId: SESSION, threadId: THREAD, method, params }) - } - await c.deferred.drained() - native.dispose() - const before = c.journal.snapshot().items - await c.reopen() - await c.open([turn(1), turn(2), turn(3)]) - expect(c.journal.snapshot().items.slice(0, before.length)).toEqual(before) - expect(c.texts().slice(-4)).toEqual([ - '(continued-outside)', - 'user:ask 2', - 'assistant:answer 2', - 'assistant:answer 3' - ]) - await c.open([turn(1), turn(2), turn(3), turn(4)]) - expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 4', 'assistant:answer 4']) - }) - - it('commits a 600-message import once, rolls back a later partition failure, and recovers', async () => { - const c = await chat({ now: 1_000 }) - await c.open([turn(1)]) - const before = c.journal.snapshot() - const large = { - ...turn(2), - items: Array.from({ length: 600 }, (_, n) => ({ - type: 'agentMessage', - id: `item-${n}`, - text: `answer ${n}` - })) - } - const seq = c.journal.cursor().sequence - c.db.exec( - `CREATE TRIGGER fail_later_partition BEFORE INSERT ON journal_rows WHEN NEW.seq > ${seq + 1} BEGIN SELECT RAISE(ABORT, 'injected later partition failure'); END` - ) - expect((await c.open([turn(1), large])).ok).toBe(false) - expect(c.deferred.state().failed).toBe(true) - expect(c.journal.snapshot()).toEqual(before) - c.db.exec('DROP TRIGGER fail_later_partition') - await c.reopen() - expect(c.journal.snapshot()).toEqual(before) - c.publications.length = 0 - await c.open([turn(1), large]) - expect(c.texts()).toHaveLength(603) - expect(c.publications).toEqual([before.items.length + 602]) - await c.reopen() - await c.open([turn(1), large]) - expect(c.texts()).toHaveLength(603) - }) - - it('keeps rollback reasoning and message identities immutable across turns', async () => { - const c = await chat({ now: 1_000 }) - const withReasoning = (n: number) => ({ - ...turn(n), - items: [ - { type: 'reasoning', id: 'item-2', summary: [{ text: `reason ${n}` }] }, - { type: 'agentMessage', id: 'same-message-id', text: `answer ${n}` } - ] - }) - await c.open([withReasoning(1)]) - const before = c.journal.snapshot().items - await c.open([withReasoning(2)]) - expect(c.journal.snapshot().items.slice(0, before.length)).toEqual(before) - expect(c.texts().filter((text) => text.startsWith('assistant:'))).toEqual([ - 'assistant:answer 1', - 'assistant:answer 2' - ]) - const reasoning = c.journal - .snapshot() - .items.filter((item) => item.body.kind === 'message' && item.body.role === 'reasoning') - expect(new Set(reasoning.map((item) => item.itemId)).size).toBe(2) - expect(new Set(reasoning.map((item) => JSON.stringify(item.turnScope))).size).toBe(2) - }) - - it('retains the original adoption cutoff through native rewind and disk recovery', async () => { - const clock = { now: 50_000 } - const c = await chat(clock) - let store = await openTestAgentSessionRecordStore(c.root) - const callerKey = 'catch-up-test' - await store.reserveOwner({ - sessionId: SESSION, - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: 'workspace-1', - workspaceKind: 'folder' - }, - provider: 'codex', - accountHome: { variable: 'CODEX_HOME', path: join(c.root, 'qa-codex') }, - expectedFence: null, - spawnToken: 'fixture-only', - claimKeyId: 'fixture', - handoffOperationId: null, - probe: { outcome: 'indeterminate', reason: 'fixture' }, - operation: { - callerKey, - operationId: '0000000050000-00000000000000000000000000000001', - fingerprint: 'create' - }, - now: clock.now - }) - await store.commitProcessIdentity({ - sessionId: SESSION, - fence: 1, - process: { - hostId: 'local', - pid: 424242, - processStartTimeMs: clock.now, - spawnToken: 'fixture-only' - }, - now: clock.now - }) - await store.proveOwner({ - sessionId: SESSION, - fence: 1, - link: { - linkId: 'adopted', - handle: codexProviderHandle(THREAD), - origin: 'adopted', - mintedAtFence: 1, - observedAt: clock.now - }, - now: clock.now - }) - const filePath = join(c.root, 'rollout.jsonl') - await writeFile( - filePath, - [ - { - timestamp: '1970-01-01T00:01:40.000Z', - type: 'event_msg', - payload: { type: 'user_message', message: 'old A ask' } - }, - { - timestamp: '1970-01-01T00:01:50.000Z', - type: 'event_msg', - payload: { type: 'agent_message', message: 'old A answer' } - } - ] - .map((line) => JSON.stringify(line)) - .join('\n') - ) - clock.now = 200_000 - expect( - await importLegacyTranscriptIntoJournal({ - journal: c.journal, - agent: 'codex', - sessionId: THREAD, - fence: 1, - options: { filePath } - }) - ).toMatchObject({ ok: true, imported: 2 }) - const original = c.journal.snapshot().items - const dated = (n: number) => ({ ...turn(n), startedAt: n, completedAt: n + 10 }) - await c.open([dated(100), dated(300)]) - const target = agentJournalItemKey({ - provider: 'codex', - threadId: THREAD, - turnId: 'turn-300', - ordinal: 0 - }) - const operationId = '0000000500000-00000000000000000000000000000002' - await store.admitOperation({ - callerKey, - operationId, - fingerprint: 'rewind', - now: 500_000 - }) - await store.transitionHandoff(SESSION, (record) => ({ - ...record, - rewind: { - operationId, - callerKey, - itemId: target, - expectedEpoch: c.journal.epoch, - phase: 'provider-succeeded' - } - })) - clock.now = 500_000 - const deps = () => ({ store, logger: testEventSinkLogging().logger }) - await recoverStructuredRewind(deps(), SESSION, c.journal, 1) - expect( - c.journal - .snapshot() - .items.slice(0, original.length) - .map(({ itemId, body, observedAt, turnScope }) => ({ itemId, body, observedAt, turnScope })) - ).toEqual( - original.map(({ itemId, body, observedAt, turnScope }) => ({ - itemId, - body, - observedAt, - turnScope - })) - ) - await c.reopen() - store = await openTestAgentSessionRecordStore(c.root) - await recoverStructuredRewind(deps(), SESSION, c.journal, 1) - expect(store.getRecord(SESSION)?.rewind?.phase).toBe('completed') - expect(usableJournalHistoryOrigin(c.journal.historyOrigin())).toMatchObject({ - kind: 'legacy_import', - importedAt: 200_000 - }) - await c.open([dated(100), dated(150), dated(200), dated(250), dated(600)]) - expect(c.texts().filter((text) => text.startsWith('assistant:'))).toEqual([ - 'assistant:old A answer', - 'assistant:answer 250', - 'assistant:answer 600' - ]) - expect( - c.journal - .snapshot() - .items.slice(0, original.length) - .map(({ itemId, body, observedAt, turnScope }) => ({ itemId, body, observedAt, turnScope })) - ).toEqual( - original.map(({ itemId, body, observedAt, turnScope }) => ({ - itemId, - body, - observedAt, - turnScope - })) - ) - const complete = c.journal.snapshot() - await c.reopen() - await c.open([dated(100), dated(150), dated(200), dated(250), dated(600)]) - expect(c.journal.snapshot()).toEqual(complete) - }) - - it('keeps erased-origin legacy chats readable without guessing from native IDs', async () => { - const c = await chat({ now: 200_000 }) - const kept = { - identity: { provider: 'legacy', agent: 'codex', sessionId: THREAD, recordId: '#0' } as const, - ownerFence: 1, - body: { - kind: 'message' as const, - role: 'user' as const, - blocks: [{ type: 'text' as const, text: 'legacy' }] - } - } - await c.journal.replaceEpochItems('session_created', 1, [kept]) - await c.reopen() - await c.journal.appendItem( - { provider: 'codex', threadId: THREAD, turnId: 'native', ordinal: 0 }, - { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'ordinary reply' }] }, - { fence: 1, turnScope: { kind: 'thread' } } - ) - await c.open([turn(3)]) - expect(c.texts()).toEqual(['user:legacy', 'assistant:ordinary reply']) - }) + registerCodexHistoryBoundsTests({ chat, turn, codexWith, sessionId: SESSION, threadId: THREAD }) }) - -it.each(['a', 'b'] as const)( - 'conserves recorded %s interruption in an admitted returned-turn transaction', - async (label) => { - const c = await chat({ now: 1_000 }) - const records = await recordedCodexRollout(label) - const filePath = join(c.root, `rollout-${String(records[0]!.payload.id)}.jsonl`) - await writeFile(filePath, records.map((record) => JSON.stringify(record)).join('\n')) - const imported = await prepareLegacyTranscriptImport({ - agent: 'codex', - sessionId: SESSION, - options: { filePath } - }) - expect(imported.ok).toBe(true) - if (!imported.ok) { - return - } - const turnId = - label === 'a' - ? '01a1b0de-97e0-7c01-babd-9d697204ab3e' - : '01a1b0e1-897d-73e0-b910-5b854abbfcb7' - const id = - label === 'a' - ? 'exec-422971fb-5f49-4f00-8701-a031ef77f289' - : 'exec-b421ed59-e65b-4311-acc8-685624133938' - const body = imported.items.find( - (row) => row.body.kind === 'tool-call' && row.body.callId === id - )!.body - const nativeId = codexNonMessageIdentity(THREAD, turnId, id) - const key = agentJournalItemKey(nativeId) - const turnIdentity = codexTurnLifecycleIdentity(SESSION, turnId) - // Saved-live setup has no adoption cutoff; returned full turns are an admitted caller path. - await c.journal.appendItem( - turnIdentity, - { - kind: 'turn', - turnId, - state: label === 'a' ? 'interrupted' : 'completed', - outcome: label === 'a' ? 'cancellation' : 'success' - }, - { fence: 1, turnScope: { kind: 'thread' } } - ) - await c.journal.appendItem(nativeId, body, { - fence: 1, - turnScope: { kind: 'turn', turnItemId: agentJournalItemKey(turnIdentity) } - }) - const before = c.journal.item(key)!.revision - // API contract derived from recorded command fields, not a captured list/read response. - const command = { - type: 'commandExecution', - id, - status: 'failed', - command: "/bin/zsh -lc 'sleep 60'", - cwd: '/Users/brennanbenson/orca/workspaces/orca/qa-codex-exec-import-qg/codex-exec-import/run/workspace', - exitCode: -1, - durationMs: label === 'a' ? 9915 : 53631 - } - const supplied = { - id: turnId, - status: label === 'a' ? 'interrupted' : 'completed', - items: [ - { ...command, aggregatedOutput: 'partial output contract' }, - { ...command, id: 'unsaved-minus-one' }, - { ...command, id: 'still-running', status: 'inProgress', exitCode: undefined }, - { ...command, id: 'failed-seven', exitCode: 7, durationMs: 11872 } - ] - } - await c.open([], { returnedTurns: [supplied], paginate: false }) - const saved = c.journal.item(key)! - expect(saved.revision).toBeGreaterThan(before) - expect(saved.body).toMatchObject({ - kind: 'tool-call', - state: 'failed', - endedAs: 'interrupted', - output: { head: 'partial output contract' } - }) - expect(saved.body).not.toHaveProperty('exitCode') - expect(saved.body).not.toHaveProperty('durationMs') - expect(c.journal.item(agentJournalItemKey(turnIdentity))?.body).toMatchObject({ - state: label === 'a' ? 'interrupted' : 'completed' - }) - const calls = projectStructuredItemsToNativeChat(c.journal.snapshot().items) - .flatMap((message) => message.blocks) - .filter((block) => block.type === 'tool-call') - expect(calls.find((call) => call.callId === id)).not.toHaveProperty('exitCode') - expect(calls.find((call) => call.callId === id)).not.toHaveProperty('durationMs') - expect(calls.find((call) => call.callId === 'unsaved-minus-one')).toMatchObject({ - state: 'failed', - exitCode: -1 - }) - expect(calls.find((call) => call.callId === 'unsaved-minus-one')).not.toHaveProperty('endedAs') - expect(calls.find((call) => call.callId === 'still-running')).toMatchObject({ - state: 'running' - }) - expect(calls.find((call) => call.callId === 'failed-seven')).toMatchObject({ - state: 'failed', - exitCode: 7, - durationMs: 11872 - }) - await c.open([], { - returnedTurns: [ - { - ...supplied, - items: [ - command, - { - ...command, - id: 'failed-seven', - status: undefined, - exitCode: undefined, - durationMs: undefined - } - ] - } - ], - paginate: false - }) - expect(c.journal.item(key)?.body).toEqual(saved.body) - expect( - c.journal - .snapshot() - .items.find((row) => row.body.kind === 'tool-call' && row.body.callId === 'failed-seven') - ?.body - ).toMatchObject({ state: 'failed', exitCode: 7, durationMs: 11872 }) - await c.reopen() - expect(c.journal.item(key)?.body).toEqual(saved.body) - } -) diff --git a/src/main/connector-cloud/connector-cloud-install.ts b/src/main/connector-cloud/connector-cloud-install.ts index 7efd4363e7a..33dd0195a1d 100644 --- a/src/main/connector-cloud/connector-cloud-install.ts +++ b/src/main/connector-cloud/connector-cloud-install.ts @@ -2,7 +2,7 @@ import { hostname } from 'node:os' import { getAppEnvironment } from '../../shared/app-environment' import { admitConnectorAgent, CONNECTOR_AGENTS } from '../external-conversations/connector-agents' import { runtimeConversationHost } from '../external-conversations/external-conversation-seam' -import { getOrcaCloudAuthConfig } from '../orca-profiles/profile-cloud-auth-config' +import { getOrcaCloudAuthConfig } from '../orca-profiles/cloud-auth/profile-cloud-auth-config' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { RuntimeStore } from '../runtime/construction/runtime-store-contract' import { ConnectorCloud } from './connector-cloud' diff --git a/src/main/connector-cloud/connector-token-mint.test.ts b/src/main/connector-cloud/connector-token-mint.test.ts index 1868bda8ec0..f27ce7c4dd0 100644 --- a/src/main/connector-cloud/connector-token-mint.test.ts +++ b/src/main/connector-cloud/connector-token-mint.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { OrcaCloudAuthConfig } from '../orca-profiles/profile-cloud-auth-config' +import type { OrcaCloudAuthConfig } from '../orca-profiles/cloud-auth/profile-cloud-auth-config' import { desktopConnectorTokenMint } from './connector-token-mint' const profile = vi.hoisted(() => { @@ -11,7 +11,7 @@ const runFresh = vi.hoisted(() => vi.fn()) vi.mock('../orca-profiles/profile-index-store', () => ({ ensureActiveOrcaProfile: () => ({ profile: { id: 'p1', cloud: profile.cloud } }) })) -vi.mock('../orca-profiles/profile-cloud-session-refresh', () => ({ +vi.mock('../orca-profiles/cloud-session/profile-cloud-session-refresh', () => ({ runWithFreshOrcaCloudSession: runFresh })) vi.mock('../runtime/hosts/platform-probe/host-descriptor', () => ({ diff --git a/src/main/connector-cloud/connector-token-mint.ts b/src/main/connector-cloud/connector-token-mint.ts index b57b6ed1f1d..c32cb255363 100644 --- a/src/main/connector-cloud/connector-token-mint.ts +++ b/src/main/connector-cloud/connector-token-mint.ts @@ -1,8 +1,8 @@ // Connector tokens for the desktop's signed-in Orca account, fetched the way relay tokens are. import { z } from 'zod' -import type { OrcaCloudAuthConfig } from '../orca-profiles/profile-cloud-auth-config' -import { OrcaCloudRequestError } from '../orca-profiles/profile-cloud-client' -import { runWithFreshOrcaCloudSession } from '../orca-profiles/profile-cloud-session-refresh' +import type { OrcaCloudAuthConfig } from '../orca-profiles/cloud-auth/profile-cloud-auth-config' +import { OrcaCloudRequestError } from '../orca-profiles/cloud-auth/profile-cloud-client' +import { runWithFreshOrcaCloudSession } from '../orca-profiles/cloud-session/profile-cloud-session-refresh' import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' import { loadOrCreateHostInstallationId } from '../runtime/hosts/platform-probe/host-descriptor' import { requestConnector, type ConnectorFailure } from './connector-cloud-request' diff --git a/src/main/daemon/process-scopes/macos-login-session-death-watch.ts b/src/main/daemon/process-scopes/macos-login-session-death-watch.ts index 596334659fe..6354e3c7e15 100644 --- a/src/main/daemon/process-scopes/macos-login-session-death-watch.ts +++ b/src/main/daemon/process-scopes/macos-login-session-death-watch.ts @@ -34,15 +34,11 @@ export class MacosLoginSessionDeathWatch { private readonly onRetire: MacosLoginSessionDeathWatchOptions['onRetire'] private readonly log: DaemonFileLog private readonly clock: LoginSessionWatchClock - private readonly periodicProbeMs: number - private readonly rejectionRecheckMs: number - private readonly minimumRejectionSpanMs: number - private readonly ptyExitDebounceMs: number - private readonly clientActivityMinGapMs: number - private readonly minProbeGapMs: number + private readonly timing: LoginSessionWatchTiming // Only a previously successful login probe can establish a session worth watching. private armed = false + private lastVerdictAccepted = false private consecutiveRejections = 0 private firstRejectionAtMs: number | null = null private lastProbeStartedAtMs: number | null = null @@ -61,15 +57,7 @@ export class MacosLoginSessionDeathWatch { this.onRetire = opts.onRetire this.log = opts.log this.clock = opts.clock ?? createLoginSessionWatchClock() - const defaults = DEFAULT_LOGIN_SESSION_WATCH_TIMING - this.periodicProbeMs = opts.timing?.periodicProbeMs ?? defaults.periodicProbeMs - this.rejectionRecheckMs = opts.timing?.rejectionRecheckMs ?? defaults.rejectionRecheckMs - this.minimumRejectionSpanMs = - opts.timing?.minimumRejectionSpanMs ?? defaults.minimumRejectionSpanMs - this.ptyExitDebounceMs = opts.timing?.ptyExitDebounceMs ?? defaults.ptyExitDebounceMs - this.clientActivityMinGapMs = - opts.timing?.clientActivityMinGapMs ?? defaults.clientActivityMinGapMs - this.minProbeGapMs = opts.timing?.minProbeGapMs ?? defaults.minProbeGapMs + this.timing = { ...DEFAULT_LOGIN_SESSION_WATCH_TIMING, ...opts.timing } } start(): void { @@ -105,7 +93,7 @@ export class MacosLoginSessionDeathWatch { this.ptyExitDebounceTimer = this.clock.setTimeout(() => { this.ptyExitDebounceTimer = null void this.runProbe('pty-exit') - }, this.ptyExitDebounceMs) + }, this.timing.ptyExitDebounceMs) } notifyClientActivity(): void { @@ -120,9 +108,12 @@ export class MacosLoginSessionDeathWatch { } const elapsedSinceProbe = this.lastProbeStartedAtMs === null ? null : this.clock.now() - this.lastProbeStartedAtMs - if (elapsedSinceProbe !== null && elapsedSinceProbe < this.clientActivityMinGapMs) { + if (elapsedSinceProbe !== null && elapsedSinceProbe < this.timing.clientActivityMinGapMs) { // Retain post-login activity so recovery need not wait for the periodic backstop. - this.scheduleProbeNoLaterThan(this.clientActivityMinGapMs - elapsedSinceProbe, 'client-hello') + this.scheduleProbeNoLaterThan( + this.timing.clientActivityMinGapMs - elapsedSinceProbe, + 'client-hello' + ) return } void this.runProbe('client-hello') @@ -160,7 +151,9 @@ export class MacosLoginSessionDeathWatch { } private probeGapMs(trigger: string): number { - return trigger === 'client-hello' ? this.clientActivityMinGapMs : this.minProbeGapMs + return trigger === 'client-hello' + ? this.timing.clientActivityMinGapMs + : this.timing.minProbeGapMs } private retainPendingProbe(trigger: string): void { @@ -186,25 +179,16 @@ export class MacosLoginSessionDeathWatch { } const timerGapMs = scheduledAtMs === undefined ? 0 : Math.max(0, this.clock.now() - scheduledAtMs) - let rejectionWindowRebased = false - if (this.consecutiveRejections > 0 && timerGapMs > this.minProbeGapMs * 3) { - // Sleep or App Nap pauses are not evidence of continued rejection. - this.consecutiveRejections = 0 - this.firstRejectionAtMs = null - rejectionWindowRebased = true - this.log.log('login-session-rejection-window-reset', { - cause: 'timer-gap', - timerGapMs - }) - } + // Sleep or App Nap pauses are not evidence of continued rejection. + let rejectionWindowRebased = this.resetRejectionWindowAfterGap('timer-gap', timerGapMs) const elapsedSinceProbe = this.lastProbeStartedAtMs === null ? null : this.clock.now() - this.lastProbeStartedAtMs if ( trigger !== 'startup' && elapsedSinceProbe !== null && - elapsedSinceProbe < this.minProbeGapMs + elapsedSinceProbe < this.timing.minProbeGapMs ) { - this.scheduleProbeNoLaterThan(this.minProbeGapMs - elapsedSinceProbe, trigger) + this.scheduleProbeNoLaterThan(this.timing.minProbeGapMs - elapsedSinceProbe, trigger) return } this.probeInFlight = true @@ -213,21 +197,25 @@ export class MacosLoginSessionDeathWatch { const abortController = new AbortController() this.probeAbortController = abortController try { + if (this.lastVerdictAccepted) { + // Why: every login(1) probe writes a macOS login record; retirement needs a dead resolver anyway. + const resolverHealth = await this.readResolverHealth(abortController.signal) + if (this.stopped || this.retired) { + return + } + if (resolverHealth !== 'unhealthy') { + this.scheduleNextProbe(this.timing.periodicProbeMs) + return + } + } const outcome = await this.probeLoginSession(abortController.signal) if (this.stopped || this.retired) { return } const probeGapMs = Math.max(0, this.clock.now() - probeStartedAtMs) - if (this.consecutiveRejections > 0 && probeGapMs > this.minProbeGapMs * 3) { - // Sleep may suspend a probe after the earlier timer-gap check. - this.consecutiveRejections = 0 - this.firstRejectionAtMs = null - rejectionWindowRebased = true - this.log.log('login-session-rejection-window-reset', { - cause: 'probe-gap', - probeGapMs - }) - } + // Sleep may suspend a probe after the earlier timer-gap check. + rejectionWindowRebased = + this.resetRejectionWindowAfterGap('probe-gap', probeGapMs) || rejectionWindowRebased if (outcome === null) { // Without an applicable login wrapper, PAM cannot establish session health. this.log.log('login-session-watch-disabled', { trigger }) @@ -236,7 +224,7 @@ export class MacosLoginSessionDeathWatch { } if (!outcome.conclusive) { // Repeated timeouts remain ambiguous and must never authorize retirement of live PTYs. - this.scheduleNextProbe(this.periodicProbeMs) + this.scheduleNextProbe(this.timing.periodicProbeMs) return } if (outcome.ok) { @@ -244,13 +232,15 @@ export class MacosLoginSessionDeathWatch { this.log.log('login-session-watch-armed', { trigger }) } this.armed = true + this.lastVerdictAccepted = true this.consecutiveRejections = 0 this.firstRejectionAtMs = null - this.scheduleNextProbe(this.periodicProbeMs) + this.scheduleNextProbe(this.timing.periodicProbeMs) return } + this.lastVerdictAccepted = false if (!this.armed) { - this.scheduleNextProbe(this.periodicProbeMs) + this.scheduleNextProbe(this.timing.periodicProbeMs) return } this.firstRejectionAtMs ??= this.clock.now() @@ -261,13 +251,13 @@ export class MacosLoginSessionDeathWatch { }) if (this.consecutiveRejections < REQUIRED_CONSECUTIVE_REJECTIONS) { this.scheduleNextProbe( - rejectionWindowRebased ? this.periodicProbeMs : this.rejectionRecheckMs + rejectionWindowRebased ? this.timing.periodicProbeMs : this.timing.rejectionRecheckMs ) return } const rejectionSpanMs = this.clock.now() - this.firstRejectionAtMs - if (rejectionSpanMs < this.minimumRejectionSpanMs) { - const retryInMs = this.minimumRejectionSpanMs - rejectionSpanMs + if (rejectionSpanMs < this.timing.minimumRejectionSpanMs) { + const retryInMs = this.timing.minimumRejectionSpanMs - rejectionSpanMs this.consecutiveRejections = REQUIRED_CONSECUTIVE_REJECTIONS - 1 this.log.log('login-session-retire-deferred', { cause: 'pam-rejections', @@ -282,7 +272,7 @@ export class MacosLoginSessionDeathWatch { } catch (error) { // A diagnostic probe rejection must not escape into the daemon’s fatal error handler. this.log.log('login-session-probe-error', { message: (error as Error)?.message }) - this.scheduleNextProbe(this.periodicProbeMs) + this.scheduleNextProbe(this.timing.periodicProbeMs) } finally { this.probeInFlight = false if (this.probeAbortController === abortController) { @@ -300,6 +290,16 @@ export class MacosLoginSessionDeathWatch { } } + private resetRejectionWindowAfterGap(cause: 'timer-gap' | 'probe-gap', gapMs: number): boolean { + if (this.consecutiveRejections === 0 || gapMs <= this.timing.minProbeGapMs * 3) { + return false + } + this.consecutiveRejections = 0 + this.firstRejectionAtMs = null + this.log.log('login-session-rejection-window-reset', { cause, gapMs }) + return true + } + private async retireIfResolverDegraded( holdAtThreshold: () => void, signal: AbortSignal @@ -315,7 +315,7 @@ export class MacosLoginSessionDeathWatch { resolverHealth }) holdAtThreshold() - this.scheduleNextProbe(this.periodicProbeMs) + this.scheduleNextProbe(this.timing.periodicProbeMs) return } this.retired = true diff --git a/src/main/daemon/process-scopes/testing/macos-login-session-death-watch.test.ts b/src/main/daemon/process-scopes/testing/macos-login-session-death-watch.test.ts index 8d17fb34078..7726e9927dd 100644 --- a/src/main/daemon/process-scopes/testing/macos-login-session-death-watch.test.ts +++ b/src/main/daemon/process-scopes/testing/macos-login-session-death-watch.test.ts @@ -107,10 +107,8 @@ function createWatch( describe('MacosLoginSessionDeathWatch', () => { it('preserves the daemon when a short PAM rejection burst recovers after wake', async () => { - const readResolverHealth = vi.fn(async () => 'unhealthy' as const) const { watch, clock, onRetire, probe } = createWatch({ - outcomes: [ACCEPTED, REJECTED, REJECTED, REJECTED, ACCEPTED], - readResolverHealth + outcomes: [ACCEPTED, REJECTED, REJECTED, REJECTED, ACCEPTED] }) watch.start() await drainMicrotasks() @@ -120,7 +118,6 @@ describe('MacosLoginSessionDeathWatch', () => { await clock.advance(10_000) expect(probe).toHaveBeenCalledTimes(4) - expect(readResolverHealth).not.toHaveBeenCalled() expect(onRetire).not.toHaveBeenCalled() watch.notifyClientActivity() @@ -129,15 +126,12 @@ describe('MacosLoginSessionDeathWatch', () => { expect(probe).toHaveBeenCalledTimes(4) await clock.advance(1) expect(probe).toHaveBeenCalledTimes(5) - expect(readResolverHealth).not.toHaveBeenCalled() expect(onRetire).not.toHaveBeenCalled() }) it('does not count a suspended timer gap as rejection evidence', async () => { - const readResolverHealth = vi.fn(async () => 'unhealthy' as const) const { watch, clock, onRetire, probe } = createWatch({ - outcomes: [ACCEPTED, REJECTED, REJECTED, ACCEPTED], - readResolverHealth + outcomes: [ACCEPTED, REJECTED, REJECTED, ACCEPTED] }) watch.start() await drainMicrotasks() @@ -147,7 +141,6 @@ describe('MacosLoginSessionDeathWatch', () => { await clock.advance(0) expect(probe).toHaveBeenCalledTimes(3) - expect(readResolverHealth).not.toHaveBeenCalled() expect(onRetire).not.toHaveBeenCalled() await clock.advance(119_999) @@ -168,8 +161,7 @@ describe('MacosLoginSessionDeathWatch', () => { .mockResolvedValueOnce(REJECTED) .mockReturnValueOnce(deferredProbe) .mockResolvedValueOnce(ACCEPTED) - const readResolverHealth = vi.fn(async () => 'unhealthy' as const) - const { watch, clock, onRetire } = createWatch({ probeLoginSession: probe, readResolverHealth }) + const { watch, clock, onRetire } = createWatch({ probeLoginSession: probe }) watch.start() await drainMicrotasks() @@ -180,7 +172,6 @@ describe('MacosLoginSessionDeathWatch', () => { await drainMicrotasks() expect(probe).toHaveBeenCalledTimes(3) - expect(readResolverHealth).not.toHaveBeenCalled() expect(onRetire).not.toHaveBeenCalled() await clock.advance(119_999) @@ -202,29 +193,62 @@ describe('MacosLoginSessionDeathWatch', () => { expect(onRetire).not.toHaveBeenCalled() }) + it('retires a logged-out session three rejections and two minutes after the first one', async () => { + const { watch, clock, onRetire } = createWatch({ + outcomes: [ACCEPTED, REJECTED, REJECTED, REJECTED, REJECTED] + }) + watch.start() + await drainMicrotasks() + await clock.advance(239_999) + expect(onRetire).not.toHaveBeenCalled() + await clock.advance(1) + expect(onRetire).toHaveBeenCalledTimes(1) + }) + + it('does not retire when DNS recovers before the retirement check', async () => { + const { watch, clock, onRetire, setResolverHealth } = createWatch({ + outcomes: [ACCEPTED, REJECTED, REJECTED, REJECTED, REJECTED] + }) + watch.start() + await drainMicrotasks() + await clock.advance(140_000) + setResolverHealth('healthy') + await clock.advance(100_000) + expect(onRetire).not.toHaveBeenCalled() + }) + it.each(['healthy', 'unknown'] as const)( - 'suppresses retirement while resolver health is %s, then retires on explicit degradation', - async (initialResolverHealth) => { - const { watch, clock, onRetire, probe, setResolverHealth } = createWatch({ - outcomes: [ACCEPTED, REJECTED, REJECTED, REJECTED, REJECTED, REJECTED] - }) - setResolverHealth(initialResolverHealth) + 'runs no login probe after arming while resolver health is %s', + async (resolverHealth) => { + const { watch, clock, probe, setResolverHealth } = createWatch() + setResolverHealth(resolverHealth) watch.start() await drainMicrotasks() - await clock.advance(120_000) + for (let i = 0; i < 5; i++) { + await clock.advance(120_000) + } + watch.notifyClientActivity() + watch.notifyPtyExit() await clock.advance(10_000) - await clock.advance(10_000) - await clock.advance(100_000) // Retirement still requires explicit resolver corroboration. - expect(onRetire).not.toHaveBeenCalled() - const probesAtSuppression = probe.mock.calls.length - setResolverHealth('unhealthy') - await clock.advance(119_999) - expect(probe).toHaveBeenCalledTimes(probesAtSuppression) - await clock.advance(1) // Suppressed states use the bounded periodic cadence. - expect(onRetire).toHaveBeenCalledTimes(1) + expect(probe).toHaveBeenCalledTimes(1) } ) + it('keeps running the login probe after a rejection until PAM accepts again, even across sleep', async () => { + const { watch, clock, probe, setResolverHealth } = createWatch({ + outcomes: [ACCEPTED, REJECTED, ACCEPTED] + }) + watch.start() + await drainMicrotasks() + await clock.advance(120_000) + expect(probe).toHaveBeenCalledTimes(2) + + setResolverHealth('healthy') + clock.suspend(60 * 60 * 1000) + await clock.advance(0) // The sleep gap resets the rejection streak, not the rejected verdict. + expect(probe).toHaveBeenCalledTimes(3) + }) + it('stop() prevents an in-flight resolver check from retiring the daemon', async () => { let resolveHealth!: (health: SystemResolverHealth) => void let resolverSignal: AbortSignal | undefined @@ -233,10 +257,14 @@ describe('MacosLoginSessionDeathWatch', () => { }) const { watch, clock, onRetire } = createWatch({ outcomes: [ACCEPTED, REJECTED, REJECTED, REJECTED, REJECTED], - readResolverHealth: (signal) => { - resolverSignal = signal - return resolverHealth - } + // The first read is the pre-probe gate; hold only the retirement read. + readResolverHealth: vi + .fn() + .mockResolvedValueOnce('unhealthy') + .mockImplementationOnce((signal) => { + resolverSignal = signal + return resolverHealth + }) }) watch.start() await drainMicrotasks() diff --git a/src/main/emulator/avcc-frame-parser.test.ts b/src/main/emulator/avcc-frame-parser.test.ts new file mode 100644 index 00000000000..ff7a5a5a704 --- /dev/null +++ b/src/main/emulator/avcc-frame-parser.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest' +import { AvccFrameParser, type AvccFrame } from './avcc-frame-parser' + +function packet(tag: number, payload: number[]): number[] { + const length = payload.length + 1 + return [ + length >>> 24, + (length >>> 16) & 0xff, + (length >>> 8) & 0xff, + length & 0xff, + tag, + ...payload + ] +} + +function parse(chunks: number[][]): { frame: AvccFrame; bytes: number[] }[] { + const frames: { frame: AvccFrame; bytes: number[] }[] = [] + const parser = new AvccFrameParser((frame) => + frames.push({ frame, bytes: [...new Uint8Array(frame.bytes)] }) + ) + for (const chunk of chunks) { + parser.push(Uint8Array.from(chunk)) + } + return frames +} + +describe('AvccFrameParser', () => { + it('reassembles description, IDR and delta packets split anywhere across chunks', () => { + const wire = [...packet(1, [1, 0x64, 0, 0x33]), ...packet(2, [9, 9, 9]), ...packet(3, [7])] + const frames = parse([wire.slice(0, 3), wire.slice(3, 11), wire.slice(11, 12), wire.slice(12)]) + + expect(frames.map(({ frame, bytes }) => [frame.config, frame.keyFrame, bytes])).toEqual([ + [true, false, [1, 0x64, 0, 0x33]], + [false, true, [9, 9, 9]], + [false, false, [7]] + ]) + }) + + it('skips the connect-time JPEG seed so decoding starts from the description', () => { + const frames = parse([[...packet(4, [0xff, 0xd8]), ...packet(1, [1, 0x64, 0, 0x33])]]) + + expect(frames).toHaveLength(1) + expect(frames[0].frame.config).toBe(true) + }) + + it('rejects packets that are not part of the serve-sim AVCC protocol', () => { + expect(() => parse([packet(9, [1])])).toThrow('Invalid simulator video packet') + expect(() => parse([[0, 0, 0, 1, 2]])).toThrow('Invalid simulator video packet') + }) +}) diff --git a/src/main/emulator/avcc-frame-parser.ts b/src/main/emulator/avcc-frame-parser.ts new file mode 100644 index 00000000000..ef445583d76 --- /dev/null +++ b/src/main/emulator/avcc-frame-parser.ts @@ -0,0 +1,64 @@ +// serve-sim /stream.avcc wire: u32 big-endian length (tag + payload), then a one-byte tag: +// 1 avcC description, 2 IDR, 3 delta, 4 connect-time JPEG seed. +const DESCRIPTION_TAG = 1 +const KEY_FRAME_TAG = 2 +const SEED_TAG = 4 +const MAX_PACKET_BYTES = 32 * 1024 * 1024 + +export type AvccFrame = { config: boolean; keyFrame: boolean; bytes: ArrayBuffer } + +export class AvccFrameParser { + private readonly header = new Uint8Array(5) + private readonly headerView = new DataView(this.header.buffer) + private headerUsed = 0 + private payload: Uint8Array | null = null + private payloadUsed = 0 + private tag = 0 + + constructor(private readonly onFrame: (frame: AvccFrame) => void) {} + + push(chunk: Uint8Array): void { + let offset = 0 + while (offset < chunk.byteLength) { + if (!this.payload) { + const take = Math.min(this.header.byteLength - this.headerUsed, chunk.byteLength - offset) + this.header.set(chunk.subarray(offset, offset + take), this.headerUsed) + this.headerUsed += take + offset += take + if (this.headerUsed < this.header.byteLength) { + return + } + const length = this.headerView.getUint32(0, false) + this.tag = this.header[4] + if ( + length < 2 || + length > MAX_PACKET_BYTES || + this.tag < DESCRIPTION_TAG || + this.tag > SEED_TAG + ) { + throw new Error(`Invalid simulator video packet (length ${length}, tag ${this.tag}).`) + } + this.payload = new Uint8Array(length - 1) + this.payloadUsed = 0 + this.headerUsed = 0 + } + const take = Math.min(this.payload.byteLength - this.payloadUsed, chunk.byteLength - offset) + this.payload.set(chunk.subarray(offset, offset + take), this.payloadUsed) + this.payloadUsed += take + offset += take + if (this.payloadUsed < this.payload.byteLength) { + return + } + const bytes = this.payload.buffer + this.payload = null + // The connect-time JPEG seed only previews; the decoder starts from the description and IDR. + if (this.tag !== SEED_TAG) { + this.onFrame({ + config: this.tag === DESCRIPTION_TAG, + keyFrame: this.tag === KEY_FRAME_TAG, + bytes + }) + } + } + } +} diff --git a/src/main/emulator/avcc-frame-stream.ts b/src/main/emulator/avcc-frame-stream.ts new file mode 100644 index 00000000000..8ac791f5a10 --- /dev/null +++ b/src/main/emulator/avcc-frame-stream.ts @@ -0,0 +1,95 @@ +import { request as httpRequest, type ClientRequest } from 'node:http' +import type { Socket } from 'node:net' +import { request as httpsRequest } from 'node:https' +import { errorMessage } from '../../shared/error-message' +import { AvccFrameParser, type AvccFrame } from './avcc-frame-parser' + +// serve-sim re-sends unchanged screens at ~5 fps, so seconds of socket silence mean a dead stream. +const STALL_MS = 3_000 + +export type AvccFrameStreamCallbacks = { + onError: (message: string) => void + onFrame: (frame: AvccFrame) => void +} + +export class AvccFrameStream { + private readonly parser: AvccFrameParser + private request: ClientRequest | null = null + private lastDataAt = 0 + private stopped = false + + constructor( + private readonly streamUrl: string, + private readonly callbacks: AvccFrameStreamCallbacks, + private readonly stallMs = STALL_MS + ) { + this.parser = new AvccFrameParser((frame) => { + if (!this.stopped) { + this.callbacks.onFrame(frame) + } + }) + } + + start(): void { + const url = new URL(this.streamUrl) + const request = (url.protocol === 'https:' ? httpsRequest : httpRequest)(url, (response) => { + if (this.stopped) { + response.destroy() + return + } + if (response.statusCode !== 200) { + response.resume() + this.fail(`Simulator video stream returned HTTP ${response.statusCode}.`) + return + } + response.on('data', (chunk: Buffer) => { + // serve-sim sends nothing until capture starts; the renderer's first-frame timeout covers that wait. + if (this.lastDataAt === 0) { + this.watchForStall(response.socket) + } + this.lastDataAt = Date.now() + try { + this.parser.push(chunk) + } catch (error) { + this.fail(errorMessage(error)) + } + }) + response.on('error', (error) => this.fail(error.message)) + response.on('close', () => this.fail('Simulator video stream closed.')) + }) + this.request = request + request.on('error', (error) => this.fail(error.message)) + request.end() + } + + stop(): void { + this.stopped = true + this.request?.destroy() + this.request = null + } + + private watchForStall(socket: Socket): void { + socket.setTimeout(this.stallMs) + socket.on('timeout', () => { + const idleSince = this.lastDataAt + const late = Date.now() - idleSince > 1.5 * this.stallMs + // Overdue timers run before queued socket data is read; sleep makes them overdue with none queued. + setImmediate(() => { + if (!late && this.lastDataAt === idleSince) { + this.fail('Simulator video stream stalled.') + return + } + this.lastDataAt = Date.now() + socket.setTimeout(this.stallMs) + }) + }) + } + + private fail(message: string): void { + if (this.stopped) { + return + } + this.stop() + this.callbacks.onError(message) + } +} diff --git a/src/main/emulator/emulator-bridge.ts b/src/main/emulator/emulator-bridge.ts index b273b2b3b84..7b812880c36 100644 --- a/src/main/emulator/emulator-bridge.ts +++ b/src/main/emulator/emulator-bridge.ts @@ -211,6 +211,11 @@ export class EmulatorBridge { }) } + /** Renderers name only a device; main resolves its registered helper so they cannot pick hosts. */ + getIosVideoStreamUrl(deviceUdid: string): string | null { + return this.sessionRegistry.getIosVideoStreamUrl(deviceUdid) + } + async runCapability( capability: keyof EmulatorBackendCapabilities, opts: EmulatorTargetOpts | undefined, @@ -317,10 +322,7 @@ export class EmulatorBridge { private backendForActiveWorktree(worktreeId: string): EmulatorBackend | null { const key = this.sessionRegistry.getActiveSessionKey(worktreeId) - if (!key) { - return null - } - const session = this.sessionRegistry.getSession(key) + const session = key ? this.sessionRegistry.getSession(key) : undefined return session ? this.backendForKind(session.backend) : null } diff --git a/src/main/emulator/emulator-session-registry.ts b/src/main/emulator/emulator-session-registry.ts index b167bb63efc..8e21ce3c813 100644 --- a/src/main/emulator/emulator-session-registry.ts +++ b/src/main/emulator/emulator-session-registry.ts @@ -6,6 +6,7 @@ import type { import type { EmulatorSessionState } from './emulator-bridge-types' import type { EmulatorBackend } from './backends/emulator-backend' import { withTimeout } from '../../shared/promise-timeout-fallback' +import { deriveAvccUrlFromStreamUrl } from './serve-sim-detached-session' const DEVICE_LISTING_BUDGET_MS = 5_000 @@ -62,6 +63,13 @@ export class EmulatorSessionRegistry { return this.sessions.get(key) } + getIosVideoStreamUrl(key: string): string | null { + const session = this.sessions.get(key) + return session?.backend === 'ios' + ? (deriveAvccUrlFromStreamUrl(session.streamUrl) ?? null) + : null + } + toSessionInfo(session: EmulatorSessionState): EmulatorSessionInfo { return toSessionInfo(session) } diff --git a/src/main/emulator/serve-sim-detached-session.ts b/src/main/emulator/serve-sim-detached-session.ts index b11bb61502b..975c0cee9af 100644 --- a/src/main/emulator/serve-sim-detached-session.ts +++ b/src/main/emulator/serve-sim-detached-session.ts @@ -19,6 +19,13 @@ export function deriveAxUrlFromStreamUrl(streamUrl: string | undefined): string return `${streamUrl.slice(0, -MJPEG_STREAM_SUFFIX.length)}/ax` } +export function deriveAvccUrlFromStreamUrl(streamUrl: string): string | undefined { + if (!streamUrl.endsWith(MJPEG_STREAM_SUFFIX)) { + return undefined + } + return `${streamUrl.slice(0, -MJPEG_STREAM_SUFFIX.length)}/stream.avcc` +} + export function parseServeSimDetachedSession(raw: unknown, udid: string): EmulatorSessionInfo { if (!raw || typeof raw !== 'object') { throw new EmulatorError('emulator_helper_failed', emulatorFailureText('serveSimNoEndpoints')) diff --git a/src/main/environment-providers/environment-provider-driver-contract.test-support.ts b/src/main/environment-providers/environment-provider-driver-contract.test-support.ts index 0ca2c695584..6dce4869236 100644 --- a/src/main/environment-providers/environment-provider-driver-contract.test-support.ts +++ b/src/main/environment-providers/environment-provider-driver-contract.test-support.ts @@ -5,12 +5,10 @@ import { getEphemeralVmRecipeResultProjectRoot, isAbsoluteRuntimePath } from '../../shared/ephemeral-vm-recipes' -import { - ENVIRONMENT_PROVIDER_ERROR_CODES, - isEnvironmentProviderError, - type EnvironmentCreateSpec, - type EnvironmentProviderDriver, - type EnvironmentReady +import type { + EnvironmentCreateSpec, + EnvironmentProviderDriver, + EnvironmentReady } from './environment-provider-driver' export type EnvironmentProviderDriverContractHarness = { @@ -72,34 +70,5 @@ export function runEnvironmentProviderDriverContract( // Idempotent: cleanup retries after a lost response or a restart must not fail. await reopenDriver().destroy(reload(created.handle)) }) - - it('refuses to bring back a destroyed environment, even after a restart', async () => { - const { driver, liveEnvironmentIds, reopenDriver } = await makeHarness() - const created = await driver.create(spec('ws-contract-2')) - await driver.destroy(created.handle) - const error = await reopenDriver() - .resume(reload(created.handle)) - .then( - () => null, - (caught: unknown) => caught - ) - expect(isEnvironmentProviderError(error)).toBe(true) - expect(await liveEnvironmentIds()).not.toContain(created.handle.environmentId) - }) - - it('rejects a cancelled create with a catalogued error and leaks nothing', async () => { - const { driver, liveEnvironmentIds } = await makeHarness() - const controller = new AbortController() - controller.abort() - const error = await driver.create(spec('ws-contract-3'), { signal: controller.signal }).then( - () => null, - (caught: unknown) => caught - ) - expect(isEnvironmentProviderError(error)).toBe(true) - expect(ENVIRONMENT_PROVIDER_ERROR_CODES).toContain( - isEnvironmentProviderError(error) ? error.code : null - ) - expect(await liveEnvironmentIds()).toEqual([]) - }) }) } diff --git a/src/main/ephemeral-vm/runtime-service.test.ts b/src/main/ephemeral-vm/runtime-service.test.ts index fa25993a95d..797c6562aef 100644 --- a/src/main/ephemeral-vm/runtime-service.test.ts +++ b/src/main/ephemeral-vm/runtime-service.test.ts @@ -1,24 +1,15 @@ -import { existsSync, mkdtempSync, readFileSync, truncateSync, writeFileSync } from 'node:fs' +import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { removeTempDirs } from '../../shared/testing/remove-temp-dirs.test-support' import { afterEach, describe, expect, it, vi } from 'vitest' -import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' -import { PAIRING_OFFER_VERSION } from '../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' + import { - getEphemeralVmRuntimeStorePath, listEphemeralVmRuntimes, upsertEphemeralVmRuntime } from '../../shared/ephemeral-vm-runtime-store' -import { - getEphemeralVmRuntimeFeatureStorePath, - MAX_EPHEMERAL_VM_RUNTIME_FEATURE_STORE_FILE_BYTES -} from '../../shared/ephemeral-vm-runtime-feature-store' -import { - cleanupEphemeralVmRuntime, - provisionEphemeralVmRuntime, - resumeEphemeralVmRuntime -} from './runtime-service' +import { getEphemeralVmRuntimeFeatureStorePath } from '../../shared/ephemeral-vm-runtime-feature-store' +import { cleanupEphemeralVmRuntime, provisionEphemeralVmRuntime } from './runtime-service' import { stopEphemeralVmRuntimeCleanup } from './runtime-cleanup-control' import type { OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' @@ -34,118 +25,11 @@ function makeDir(prefix: string): string { return dir } -function makePairingCode(): string { - return encodePairingOffer({ - v: PAIRING_OFFER_VERSION, - endpoint: 'wss://sandbox.example.com', - deviceToken: 'token', - publicKeyB64: 'public-key' - }) -} - function nodeCommand(scriptPath: string): string { return `"${process.execPath}" "${scriptPath}"` } describe('ephemeral VM runtime service', () => { - it('persists a successful recipe-created runtime and cleans it up', async () => { - const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') - const repoPath = makeDir('orca-ephemeral-vm-service-repo-') - const startPath = join(repoPath, 'start.js') - const cleanupPath = join(repoPath, 'cleanup.js') - writeFileSync( - startPath, - [ - 'console.log(JSON.stringify({', - ' schemaVersion: 1,', - ` pairingCode: ${JSON.stringify(makePairingCode())},`, - " projectRoot: '/workspace/repo',", - ' userData: { providerResourceId: process.env.ORCA_VM_INSTANCE_ID }', - '}))' - ].join('\n') - ) - writeFileSync( - cleanupPath, - [ - "let input = ''", - "process.stdin.on('data', (chunk) => { input += chunk })", - "process.stdin.on('end', () => {", - ' const payload = JSON.parse(input)', - ' if (payload.recipeResult.projectRoot !== "/workspace/repo") process.exit(12)', - ' if (!payload.recipeResult.userData.providerResourceId) process.exit(13)', - " require('fs').appendFileSync('cleanup-count.txt', 'x')", - ' console.error(`cleanup:${payload.instanceId}`)', - '})' - ].join('\n') - ) - const recipe: OrcaVmRecipe = { - id: 'cloud-sandbox', - name: 'Cloud Sandbox', - // Legacy repository recipes may exceed plugin limits after resources have already been provisioned. - description: 'x'.repeat(2_048), - create: nodeCommand(startPath), - destroy: nodeCommand(cleanupPath) - } - - const provisioned = await provisionEphemeralVmRuntime({ - userDataPath, - repoPath, - recipe, - repoId: 'repo-1', - projectId: 'project-1', - workspaceName: 'Fix Login Race', - now: 1_000 - }) - - expect(provisioned.ok).toBe(true) - if (!provisioned.ok) { - throw new Error(provisioned.start.error) - } - expect(provisioned.runtime).toMatchObject({ - id: provisioned.start.context.instanceId, - recipeId: 'cloud-sandbox', - recipe, - repoId: 'repo-1', - projectId: 'project-1', - workspaceName: 'Fix Login Race', - status: 'running', - cleanupStatus: 'not_started', - createdAt: 1_000, - updatedAt: 1_000 - }) - expect(listEphemeralVmRuntimes(userDataPath)).toEqual([provisioned.runtime]) - - const cleanupArgs = { - userDataPath, - repoPath, - recipe, - runtimeId: provisioned.runtime.id, - now: 2_000 - } - const [cleanup] = await Promise.all([ - cleanupEphemeralVmRuntime(cleanupArgs), - cleanupEphemeralVmRuntime(cleanupArgs) - ]) - - expect(cleanup).toMatchObject({ - ok: true, - skipped: false, - runtime: { - id: provisioned.runtime.id, - status: 'cleaned', - cleanupStatus: 'succeeded', - cleanupLastAttemptAt: 2_000 - } - }) - expect(readFileSync(join(repoPath, 'cleanup-count.txt'), 'utf8')).toBe('x') - - await expect(cleanupEphemeralVmRuntime(cleanupArgs)).resolves.toMatchObject({ - ok: true, - runtime: { status: 'cleaned' } - }) - expect(readFileSync(join(repoPath, 'cleanup-count.txt'), 'utf8')).toBe('x') - }) - it('stops a hung destroy and starts a fresh retry', async () => { const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') const repoPath = makeDir('orca-ephemeral-vm-service-repo-') @@ -203,292 +87,6 @@ describe('ephemeral VM runtime service', () => { expect(readFileSync(countPath, 'utf8')).toBe('xx') }) - it('keeps no record when create is cancelled before its script starts', async () => { - const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') - const repoPath = makeDir('orca-ephemeral-vm-service-repo-') - const startedPath = join(repoPath, 'started.txt') - const startPath = join(repoPath, 'start.js') - writeFileSync(startPath, `require('fs').writeFileSync(${JSON.stringify(startedPath)}, 'x')\n`) - const controller = new AbortController() - controller.abort() - - const provisioned = await provisionEphemeralVmRuntime({ - userDataPath, - repoPath, - recipe: { id: 'cloud-sandbox', name: 'Cloud Sandbox', create: nodeCommand(startPath) }, - signal: controller.signal - }) - - expect(provisioned).toMatchObject({ ok: false, start: { exitCode: null } }) - expect(existsSync(startedPath)).toBe(false) - expect(listEphemeralVmRuntimes(userDataPath)).toEqual([]) - }) - - it('keeps no record when create fails validation before its script starts', async () => { - const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') - const missingRepoPath = join(makeDir('orca-ephemeral-vm-service-repo-'), 'missing') - - await expect( - provisionEphemeralVmRuntime({ - userDataPath, - repoPath: missingRepoPath, - recipe: { id: 'cloud-sandbox', name: 'Cloud Sandbox', create: 'unused' } - }) - ).rejects.toThrow() - expect(listEphemeralVmRuntimes(userDataPath)).toEqual([]) - }) - - it('keeps a result-less failed record when recipe output cannot be parsed', async () => { - const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') - const repoPath = makeDir('orca-ephemeral-vm-service-repo-') - const startPath = join(repoPath, 'start.js') - writeFileSync(startPath, "console.log('not json')\n") - - const provisioned = await provisionEphemeralVmRuntime({ - userDataPath, - repoPath, - recipe: { - id: 'cloud-sandbox', - name: 'Cloud Sandbox', - create: nodeCommand(startPath) - }, - now: 1_000 - }) - - expect(provisioned).toMatchObject({ - ok: false, - start: { - error: 'Recipe stdout must be one JSON object.' - } - }) - const runtimes = listEphemeralVmRuntimes(userDataPath) - expect(runtimes).toEqual([ - expect.objectContaining({ - id: provisioned.start.context.instanceId, - status: 'failed', - cleanupLastError: 'Recipe stdout must be one JSON object.', - createdAt: 1_000 - }) - ]) - expect(runtimes[0]).not.toHaveProperty('recipeResult') - }) - - it('keeps a timed-out create destroyable by its instance id', async () => { - const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') - const repoPath = makeDir('orca-ephemeral-vm-service-repo-') - const startPath = join(repoPath, 'start.js') - writeFileSync(startPath, 'setInterval(() => {}, 1000)') - const recipe: OrcaVmRecipe = { - id: 'slow-sandbox', - name: 'Slow Sandbox', - create: nodeCommand(startPath), - destroy: nodeCommand(startPath), - timeoutSeconds: { create: 1 } - } - - const provisioned = await provisionEphemeralVmRuntime({ - userDataPath, - repoPath, - recipe, - now: 1_000 - }) - - expect(provisioned).toMatchObject({ ok: false, start: { errorCode: 'recipeTimedOut' } }) - expect(listEphemeralVmRuntimes(userDataPath)).toEqual([ - expect.objectContaining({ - id: provisioned.start.context.instanceId, - status: 'failed', - cleanupStatus: 'not_started', - cleanupLastErrorCode: 'recipeTimedOut', - recipe: expect.not.objectContaining({ timeoutSeconds: expect.anything() }) - }) - ]) - }) - - it('reconciles a create interrupted by a crash into a destroyable failed record', async () => { - const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') - const repoPath = makeDir('orca-ephemeral-vm-service-repo-') - const startPath = join(repoPath, 'start.js') - const destroyPath = join(repoPath, 'destroy.js') - const spawnedPath = join(repoPath, 'create-spawned.txt') - const payloadPath = join(repoPath, 'destroy-payload.json') - writeFileSync( - startPath, - [ - `require('fs').writeFileSync(${JSON.stringify(spawnedPath)}, process.env.ORCA_VM_INSTANCE_ID)`, - 'setInterval(() => {}, 1000)' - ].join('\n') - ) - writeFileSync( - destroyPath, - [ - "let input = ''", - "process.stdin.on('data', (chunk) => { input += chunk })", - `process.stdin.on('end', () => require('fs').writeFileSync(${JSON.stringify(payloadPath)}, input))` - ].join('\n') - ) - const recipe: OrcaVmRecipe = { - id: 'slow-sandbox', - name: 'Slow Sandbox', - create: nodeCommand(startPath), - destroy: nodeCommand(destroyPath) - } - const controller = new AbortController() - const provisioning = provisionEphemeralVmRuntime({ - userDataPath, - repoPath, - recipe, - repoId: 'repo-1', - workspaceName: 'Slow VM', - now: 1_000, - signal: controller.signal - }) - await vi.waitFor(() => expect(existsSync(spawnedPath)).toBe(true), { timeout: 10_000 }) - const instanceId = readFileSync(spawnedPath, 'utf8') - - // Persisted before create returned, and invisible to older builds' store schema. - expect(listEphemeralVmRuntimes(userDataPath)).toEqual([ - expect.objectContaining({ id: instanceId, status: 'provisioning', repoId: 'repo-1' }) - ]) - expect( - JSON.parse(readFileSync(getEphemeralVmRuntimeStorePath(userDataPath), 'utf8')).runtimes - ).toEqual([]) - const { reconcileInterruptedEphemeralVmProvisions: reconcileInSameProcess } = - await import('./runtime-provisioning-persistence') - expect(reconcileInSameProcess(userDataPath)).toEqual([]) - - // A relaunch has no record of the in-flight create. - vi.resetModules() - const { reconcileInterruptedEphemeralVmProvisions } = - await import('./runtime-provisioning-persistence') - const reconciled = reconcileInterruptedEphemeralVmProvisions(userDataPath, 5_000) - controller.abort() - await provisioning - - expect(reconciled).toEqual([ - { - id: instanceId, - recipeId: 'slow-sandbox', - recipe, - repoId: 'repo-1', - repoPath, - workspaceName: 'Slow VM', - status: 'failed', - cleanupStatus: 'not_started', - cleanupLastError: - 'Orca stopped while this VM was being created. Destroy it to release any provider resources.', - cleanupLastErrorCode: 'provisionInterrupted', - createdAt: 1_000, - updatedAt: 5_000 - } - ]) - - const cleanup = await cleanupEphemeralVmRuntime({ - userDataPath, - repoPath, - recipe, - runtimeId: instanceId - }) - expect(cleanup).toMatchObject({ ok: true, runtime: { status: 'cleaned' } }) - const payload = JSON.parse(readFileSync(payloadPath, 'utf8')) - expect(payload).toMatchObject({ mode: 'destroy', instanceId, recipeId: 'slow-sandbox' }) - expect(payload).not.toHaveProperty('recipeResult') - }) - - it('rejects an unwritable feature store before a checkout-mode recipe creates resources', async () => { - const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') - const repoPath = makeDir('orca-ephemeral-vm-service-repo-') - const startPath = join(repoPath, 'start.js') - const markerPath = join(repoPath, 'create-ran.txt') - writeFileSync(startPath, `require('fs').writeFileSync(${JSON.stringify(markerPath)}, 'yes')`) - const featurePath = getEphemeralVmRuntimeFeatureStorePath(userDataPath) - writeFileSync(featurePath, '{}') - truncateSync(featurePath, MAX_EPHEMERAL_VM_RUNTIME_FEATURE_STORE_FILE_BYTES + 1) - - await expect( - provisionEphemeralVmRuntime({ - userDataPath, - repoPath, - recipe: { - id: 'cloud-sandbox', - name: 'Cloud Sandbox', - checkoutMode: 'provisioned-root', - create: nodeCommand(startPath), - destroyDisabled: true - } - }) - ).rejects.toThrow('Could not preserve ephemeral VM runtime compatibility metadata') - expect(existsSync(markerPath)).toBe(false) - }) - - it('rejects an unreadable lifecycle store before a checkout-mode recipe creates resources', async () => { - const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') - const repoPath = makeDir('orca-ephemeral-vm-service-repo-') - const startPath = join(repoPath, 'start.js') - const markerPath = join(repoPath, 'create-ran.txt') - writeFileSync(startPath, `require('fs').writeFileSync(${JSON.stringify(markerPath)}, 'yes')`) - writeFileSync(getEphemeralVmRuntimeStorePath(userDataPath), '{') - - await expect( - provisionEphemeralVmRuntime({ - userDataPath, - repoPath, - recipe: { - id: 'cloud-sandbox', - name: 'Cloud Sandbox', - checkoutMode: 'provisioned-root', - create: nodeCommand(startPath), - destroyDisabled: true - } - }) - ).rejects.toThrow('file is invalid') - expect(existsSync(markerPath)).toBe(false) - }) - - it('destroys a checkout-mode resource when compatibility persistence fails after create', async () => { - const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') - const repoPath = makeDir('orca-ephemeral-vm-service-repo-') - const startPath = join(repoPath, 'start.js') - const cleanupPath = join(repoPath, 'cleanup.js') - const cleanupMarkerPath = join(repoPath, 'cleanup-ran.txt') - const featurePath = getEphemeralVmRuntimeFeatureStorePath(userDataPath) - writeFileSync( - startPath, - [ - `require('fs').writeFileSync(${JSON.stringify(featurePath)}, '{')`, - 'console.log(JSON.stringify({', - ' schemaVersion: 2,', - ' checkoutMode: "provisioned-root",', - ' connection: {', - ' type: "ssh",', - ' projectRoot: "/workspace/repo",', - ' target: { label: "VM", host: "host", port: 22, username: "orca" }', - ' }', - '}))' - ].join('\n') - ) - writeFileSync( - cleanupPath, - `require('fs').writeFileSync(${JSON.stringify(cleanupMarkerPath)}, 'yes')` - ) - - await expect( - provisionEphemeralVmRuntime({ - userDataPath, - repoPath, - recipe: { - id: 'cloud-sandbox', - name: 'Cloud Sandbox', - checkoutMode: 'provisioned-root', - create: nodeCommand(startPath), - destroy: nodeCommand(cleanupPath) - } - }) - ).rejects.toThrow('Could not preserve ephemeral VM runtime compatibility metadata') - expect(readFileSync(cleanupMarkerPath, 'utf8')).toBe('yes') - expect(listEphemeralVmRuntimes(userDataPath)).toEqual([]) - }) - it('keeps rollback-readable cleanup recovery when post-create destroy also fails', async () => { const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') const repoPath = makeDir('orca-ephemeral-vm-service-repo-') @@ -539,257 +137,4 @@ describe('ephemeral VM runtime service', () => { }) ]) }) - - it('destroys a provisioned resource when its checkout handshake is incompatible', async () => { - const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') - const repoPath = makeDir('orca-ephemeral-vm-service-repo-') - const startPath = join(repoPath, 'start.js') - const cleanupPath = join(repoPath, 'cleanup.js') - writeFileSync( - startPath, - `console.log(${JSON.stringify( - JSON.stringify({ - schemaVersion: 1, - pairingCode: makePairingCode(), - projectRoot: '/workspace/repo' - }) - )})` - ) - writeFileSync(cleanupPath, "require('fs').writeFileSync('cleanup-ran.txt', 'yes')") - - const provisioned = await provisionEphemeralVmRuntime({ - userDataPath, - repoPath, - recipe: { - id: 'cloud-sandbox', - name: 'Cloud Sandbox', - checkoutMode: 'provisioned-root', - create: nodeCommand(startPath), - destroy: nodeCommand(cleanupPath) - } - }) - - expect(provisioned).toMatchObject({ - ok: false, - start: { - error: - 'Provisioned-root recipes must return schemaVersion 2 with checkoutMode "provisioned-root".' - } - }) - expect(readFileSync(join(repoPath, 'cleanup-ran.txt'), 'utf8')).toBe('yes') - expect(listEphemeralVmRuntimes(userDataPath)).toEqual([]) - }) - - it('persists failed cleanup after an incompatible checkout handshake', async () => { - const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') - const repoPath = makeDir('orca-ephemeral-vm-service-repo-') - const startPath = join(repoPath, 'start.js') - const cleanupPath = join(repoPath, 'cleanup.js') - writeFileSync( - startPath, - `console.log(${JSON.stringify( - JSON.stringify({ - schemaVersion: 1, - pairingCode: makePairingCode(), - projectRoot: '/workspace/repo' - }) - )})` - ) - writeFileSync(cleanupPath, 'process.exit(1)') - const recipe: OrcaVmRecipe = { - id: 'cloud-sandbox', - name: 'Cloud Sandbox', - checkoutMode: 'provisioned-root', - create: nodeCommand(startPath), - destroy: nodeCommand(cleanupPath) - } - - const provisioned = await provisionEphemeralVmRuntime({ - userDataPath, - repoPath, - recipe, - repoId: 'repo-1', - workspaceName: 'Fix Login Race', - now: 1_000 - }) - - expect(provisioned.ok).toBe(false) - expect(listEphemeralVmRuntimes(userDataPath)).toEqual([ - expect.objectContaining({ - recipe, - repoId: 'repo-1', - workspaceName: 'Fix Login Race', - status: 'cleanup_failed', - cleanupStatus: 'failed', - cleanupLastAttemptAt: 1_000, - cleanupLastError: expect.any(String) - }) - ]) - }) - - it('persists incompatible resources when destroy is disabled', async () => { - const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') - const repoPath = makeDir('orca-ephemeral-vm-service-repo-') - const startPath = join(repoPath, 'start.js') - writeFileSync( - startPath, - `console.log(${JSON.stringify( - JSON.stringify({ - schemaVersion: 1, - pairingCode: makePairingCode(), - projectRoot: '/workspace/repo' - }) - )})` - ) - - await provisionEphemeralVmRuntime({ - userDataPath, - repoPath, - recipe: { - id: 'cloud-sandbox', - name: 'Cloud Sandbox', - checkoutMode: 'provisioned-root', - create: nodeCommand(startPath), - destroyDisabled: true - } - }) - - expect(listEphemeralVmRuntimes(userDataPath)).toEqual([ - expect.objectContaining({ - status: 'cleanup_failed', - cleanupStatus: 'disabled', - cleanupDisabled: true, - cleanupLastError: 'Destroy is disabled for this recipe.' - }) - ]) - }) - - it('rejects a provisioned root that moves during resume', async () => { - const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') - const repoPath = makeDir('orca-ephemeral-vm-service-repo-') - const resumePath = join(repoPath, 'resume.js') - writeFileSync( - resumePath, - [ - 'console.log(JSON.stringify({', - ' schemaVersion: 2,', - ' checkoutMode: "provisioned-root",', - ' connection: {', - ' type: "ssh",', - ' projectRoot: "/workspace/moved",', - ' target: { label: "VM", host: "host", port: 22, username: "orca" }', - ' }', - '}))' - ].join('\n') - ) - const recipe: OrcaVmRecipe = { - id: 'cloud-sandbox', - name: 'Cloud Sandbox', - checkoutMode: 'provisioned-root', - create: 'unused', - resume: nodeCommand(resumePath), - destroyDisabled: true - } - upsertEphemeralVmRuntime(userDataPath, { - id: 'runtime-1', - recipeId: recipe.id, - recipe, - status: 'suspended', - connectionMode: 'ssh', - cleanupStatus: 'disabled', - cleanupDisabled: true, - createdAt: 1, - updatedAt: 1, - recipeResult: { - schemaVersion: 2, - checkoutMode: 'provisioned-root', - connection: { - type: 'ssh', - projectRoot: '/workspace/original', - target: { label: 'VM', host: 'host', port: 22, username: 'orca' } - } - } - }) - - const resumed = await resumeEphemeralVmRuntime({ - userDataPath, - repoPath, - recipe, - runtimeId: 'runtime-1' - }) - - expect(resumed).toMatchObject({ - ok: false, - error: 'The provisioned workspace root changed while the runtime was suspended.', - runtime: { - status: 'resume_failed', - recipeResult: { connection: { projectRoot: '/workspace/original' } } - } - }) - }) - - it('rejects provisioned-root connection-mode drift during resume', async () => { - const userDataPath = makeDir('orca-ephemeral-vm-service-user-data-') - const repoPath = makeDir('orca-ephemeral-vm-service-repo-') - const resumePath = join(repoPath, 'resume.js') - writeFileSync( - resumePath, - `console.log(${JSON.stringify( - JSON.stringify({ - schemaVersion: 2, - checkoutMode: 'provisioned-root', - connection: { - type: 'orca-server', - pairingCode: makePairingCode(), - projectRoot: '/workspace/original' - } - }) - )})` - ) - const recipe: OrcaVmRecipe = { - id: 'cloud-sandbox', - name: 'Cloud Sandbox', - checkoutMode: 'provisioned-root', - create: 'unused', - resume: nodeCommand(resumePath), - destroyDisabled: true - } - upsertEphemeralVmRuntime(userDataPath, { - id: 'runtime-1', - recipeId: recipe.id, - recipe, - status: 'suspended', - connectionMode: 'ssh', - cleanupStatus: 'disabled', - cleanupDisabled: true, - createdAt: 1, - updatedAt: 1, - recipeResult: { - schemaVersion: 2, - checkoutMode: 'provisioned-root', - connection: { - type: 'ssh', - projectRoot: '/workspace/original', - target: { label: 'VM', host: 'host', port: 22, username: 'orca' } - } - } - }) - - const resumed = await resumeEphemeralVmRuntime({ - userDataPath, - repoPath, - recipe, - runtimeId: 'runtime-1' - }) - - expect(resumed).toMatchObject({ - ok: false, - error: 'The provisioned workspace connection type changed while the runtime was suspended.', - runtime: { - status: 'resume_failed', - connectionMode: 'ssh', - recipeResult: { connection: { type: 'ssh' } } - } - }) - }) }) diff --git a/src/main/git/source-control/status-symlink-probe-budget.test.ts b/src/main/git/source-control/status-symlink-probe-budget.test.ts deleted file mode 100644 index cd7b0bafcd2..00000000000 --- a/src/main/git/source-control/status-symlink-probe-budget.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { getStatus } from './status-read' - -const { lstat, stream, conflict } = vi.hoisted(() => ({ - lstat: vi.fn(), - stream: vi.fn(), - conflict: vi.fn() -})) -vi.mock('node:fs/promises', () => ({ lstat })) -vi.mock('./git-conflict-operation', () => ({ detectConflictOperation: conflict })) -vi.mock('../command-runner/git-stream-stdout', async (importOriginal) => ({ - ...(await importOriginal>()), - gitStreamStdout: stream -})) - -vi.mock('../command-runner/git-process-env', async (importOriginal) => ({ - ...(await importOriginal>()), - gitOptionalLocksDisabledEnv: () => ({ GIT_OPTIONAL_LOCKS: '0' }) -})) - -beforeEach(() => { - vi.clearAllMocks() - conflict.mockResolvedValue(undefined) - lstat.mockResolvedValue({ isSymbolicLink: () => true }) - stream.mockImplementation(async (_args, options) => { - options.onStdout('? unrelated.txt\n') - return { stoppedEarly: false } - }) -}) - -function status(sharedLinkPaths: string[]) { - return getStatus('/repo', { sharedLinkPaths, includeLineStats: false }) -} - -describe('status shared symlink probe budget', () => { - it.each([1, 8, 32])( - 'does no unrelated symlink probes for %i configured paths over 100 refreshes', - async (count) => { - const paths = Array.from({ length: count }, (_, index) => `shared-${index}`) - for (let refresh = 0; refresh < 100; refresh++) { - expect((await status(paths)).entries).toEqual([ - { path: 'unrelated.txt', status: 'untracked', area: 'untracked' } - ]) - } - expect(lstat).not.toHaveBeenCalled() - } - ) - - it('rechecks matching paths after the filesystem changes and preserves unreadable paths', async () => { - const paths = ['unrelated.txt'] - expect((await status(paths)).entries).toEqual([]) - lstat.mockResolvedValueOnce({ isSymbolicLink: () => false }) - expect((await status(paths)).entries).toHaveLength(1) - lstat.mockRejectedValueOnce(new Error('EACCES')) - expect((await status(paths)).entries).toHaveLength(1) - expect(lstat).toHaveBeenCalledTimes(3) - }) -}) diff --git a/src/main/git/worktrees/creation/worktree-create-preparation-real-git.test.ts b/src/main/git/worktrees/creation/worktree-create-preparation-real-git.test.ts index 1489f753f31..0ad8ff611e1 100644 --- a/src/main/git/worktrees/creation/worktree-create-preparation-real-git.test.ts +++ b/src/main/git/worktrees/creation/worktree-create-preparation-real-git.test.ts @@ -1,28 +1,16 @@ import { execFileSync } from 'node:child_process' -import { existsSync, watch, type FSWatcher } from 'node:fs' -import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises' + +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, expect, it, vi } from 'vitest' import * as gitRunner from '../../command-runner/git-exec-file' +import { createWorktreePreparationLockReason } from '../../../../shared/worktree/create-preparation' + import { - createWorktreePreparationLockReason, - WORKTREE_CREATE_PREPARATION_DIRECTORY -} from '../../../../shared/worktree/create-preparation' -import { listWorktrees } from '../catalog/worktree-scan-cache' -import { - discardPreparedWorktree, finalizePreparedWorktree, prepareWorktreeCreateCheckout } from './worktree-create-preparation' -import { areWorktreePathsEqual } from '../catalog/worktree-path-comparison' -import { - _resetPreparationPoolForTests, - listPreparations, - startPreparation, - takePreparation -} from '../../../workspaces/creation/preparation/worktree-create-preparation-pool' -import { hasPendingStalePreparationCleanup } from '../../../workspaces/creation/preparation/worktree-create-preparation-stale-cleanup' const tempRoots: string[] = [] @@ -53,575 +41,6 @@ afterEach(async () => { await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) }) -describe('prepared worktree creation with real Git', () => { - it('registers during fetch and materializes its settled tip only once before the final hook', async () => { - const { repoPath, root } = await createRepo() - const preparedPath = join(root, 'prepared-barrier') - const finalPath = join(root, 'final-barrier') - const base = 'refs/remotes/origin/main' - const reason = createWorktreePreparationLockReason('barrier-tip') - const originalHead = git(repoPath, ['rev-parse', 'HEAD']) - git(repoPath, ['update-ref', base, originalHead]) - const hooksPath = join(root, 'hooks') - await mkdir(hooksPath) - await writeFile( - join(hooksPath, 'post-checkout'), - '#!/bin/sh\nprintf \'%s\\n\' "$@" >> checkout-hook.txt\n', - { mode: 0o755 } - ) - git(repoPath, ['config', 'core.hooksPath', hooksPath]) - let release!: () => void - const barrier = new Promise((resolve) => { - release = resolve - }) - const spy = vi.spyOn(gitRunner, 'gitExecFileAsync') - const preparing = prepareWorktreeCreateCheckout( - repoPath, - preparedPath, - base, - reason, - {}, - barrier - ) - await vi.waitFor(() => expect(existsSync(join(preparedPath, '.git'))).toBe(true)) - await expect(readFile(join(preparedPath, 'version.txt'))).rejects.toMatchObject({ - code: 'ENOENT' - }) - expect(spy.mock.calls.some(([args]) => args.includes('reset'))).toBe(false) - await writeFile(join(repoPath, 'version.txt'), 'fetched\n') - git(repoPath, ['commit', '--quiet', '-am', 'fetched tip']) - const fetchedHead = git(repoPath, ['rev-parse', 'HEAD']) - git(repoPath, ['update-ref', base, fetchedHead]) - release() - try { - await preparing - expect(git(preparedPath, ['rev-parse', 'HEAD'])).toBe(fetchedHead) - expect(await readFile(join(preparedPath, 'version.txt'), 'utf8')).toBe('fetched\n') - expect(existsSync(join(preparedPath, 'checkout-hook.txt'))).toBe(false) - await finalizePreparedWorktree( - repoPath, - preparedPath, - finalPath, - 'feature/barrier', - base, - false, - {}, - reason - ) - const resets = spy.mock.calls.filter(([args]) => args.includes('reset')) - expect(resets).toHaveLength(1) - expect(resets[0]?.[0].at(-1)).toBe(fetchedHead) - expect(await readFile(join(finalPath, 'checkout-hook.txt'), 'utf8')).toBe( - `${fetchedHead}\n${fetchedHead}\n1\n` - ) - expect(git(finalPath, ['symbolic-ref', '--short', 'HEAD'])).toBe('feature/barrier') - await rm(join(finalPath, 'checkout-hook.txt')) - expect(git(finalPath, ['status', '--porcelain'])).toBe('') - } finally { - release() - spy.mockRestore() - } - }) - - it('cancels a never-settling fetch barrier and cleans the registered checkout before it resolves', async () => { - const { repoPath, root } = await createRepo() - const preparedPath = join(root, 'canceled-barrier') - const reason = createWorktreePreparationLockReason('barrier-cancel') - const controller = new AbortController() - let release!: () => void - const barrier = new Promise((resolve) => { - release = resolve - }) - const barrierSubscribed = vi.spyOn(barrier, 'then') - const spy = vi.spyOn(gitRunner, 'gitExecFileAsync') - const preparing = prepareWorktreeCreateCheckout( - repoPath, - preparedPath, - 'main', - reason, - { signal: controller.signal }, - barrier - ) - const assertion = expect(preparing).rejects.toThrow('expired while fetching') - try { - await vi.waitFor(() => expect(existsSync(join(preparedPath, '.git'))).toBe(true)) - const lock = git(preparedPath, ['rev-parse', '--git-path', 'locked']) - await vi.waitFor(async () => expect(await readFile(lock, 'utf8')).toBe(`${reason}\n`)) - await vi.waitFor(() => - expect( - barrierSubscribed.mock.calls.some(([onFulfilled]) => typeof onFulfilled === 'function') - ).toBe(true) - ) - controller.abort(new Error('expired while fetching')) - await assertion - expect(existsSync(preparedPath)).toBe(false) - expect(git(repoPath, ['worktree', 'list', '--porcelain'])).not.toContain(preparedPath) - release() - await Promise.resolve() - expect(spy.mock.calls.some(([args]) => args.includes('reset'))).toBe(false) - } finally { - release() - barrierSubscribed.mockRestore() - spy.mockRestore() - } - }) - - it('preserves a replacement owner after the fetch barrier before probing or materializing', async () => { - const { repoPath, root } = await createRepo() - const preparedPath = join(root, 'replaced-barrier') - const reason = createWorktreePreparationLockReason('barrier-replacement') - let release!: () => void - const barrier = new Promise((resolve) => { - release = resolve - }) - const preparing = prepareWorktreeCreateCheckout( - repoPath, - preparedPath, - 'main', - reason, - {}, - barrier - ) - const assertion = expect(preparing).rejects.toThrow('lock owner changed') - await vi.waitFor(() => expect(existsSync(join(preparedPath, '.git'))).toBe(true)) - const lock = git(preparedPath, ['rev-parse', '--git-path', 'locked']) - await vi.waitFor(async () => expect(await readFile(lock, 'utf8')).toBe(`${reason}\n`)) - await writeFile(lock, 'manual barrier owner\n') - await writeFile(join(preparedPath, 'version.txt'), 'manual content\n') - const spy = vi.spyOn(gitRunner, 'gitExecFileAsync') - try { - release() - await assertion - expect(spy).not.toHaveBeenCalled() - expect(await readFile(lock, 'utf8')).toBe('manual barrier owner\n') - expect(await readFile(join(preparedPath, 'version.txt'), 'utf8')).toBe('manual content\n') - } finally { - release() - spy.mockRestore() - } - }) - - it('pins first materialization to the resolved fetched OID when the ref moves before reset', async () => { - const { repoPath, root } = await createRepo() - const preparedPath = join(root, 'moving-barrier-tip') - const originalHead = git(repoPath, ['rev-parse', 'HEAD']) - await writeFile(join(repoPath, 'version.txt'), 'newer\n') - git(repoPath, ['commit', '--quiet', '-am', 'later tip']) - const newerHead = git(repoPath, ['rev-parse', 'HEAD']) - git(repoPath, ['update-ref', 'refs/remotes/origin/main', originalHead]) - const run = gitRunner.gitExecFileAsync - const spy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation((args, options) => { - if (args.includes('reset')) { - git(repoPath, ['update-ref', 'refs/remotes/origin/main', newerHead]) - } - return run(args, options) - }) - try { - await prepareWorktreeCreateCheckout( - repoPath, - preparedPath, - 'refs/remotes/origin/main', - createWorktreePreparationLockReason('barrier-oid-race'), - {}, - Promise.resolve() - ) - expect(git(preparedPath, ['rev-parse', 'HEAD'])).toBe(originalHead) - expect(await readFile(join(preparedPath, 'version.txt'), 'utf8')).toBe('one\n') - expect(spy.mock.calls.find(([args]) => args.includes('reset'))?.[0].at(-1)).toBe(originalHead) - } finally { - spy.mockRestore() - } - }) - - it.each([false, true])( - 'attaches the prepared HEAD and runs the hook (base advanced: %s)', - async (advanceBase) => { - const { repoPath, root } = await createRepo() - const preparedPath = join(root, 'prepared checkout') - const finalPath = join(root, 'final checkout') - const hooksPath = join(root, 'hooks') - await mkdir(hooksPath) - await writeFile( - join(hooksPath, 'post-checkout'), - '#!/bin/sh\nprintf \'%s\\n\' "$@" >> checkout-hook.txt\ngit symbolic-ref --short HEAD >> checkout-hook.txt\n', - { mode: 0o755 } - ) - git(repoPath, ['config', 'core.hooksPath', hooksPath]) - git(repoPath, ['config', 'branch.autoSetupMerge', 'always']) - const lockReason = createWorktreePreparationLockReason('attach-with-hook') - await prepareWorktreeCreateCheckout(repoPath, preparedPath, 'main', lockReason) - expect(existsSync(join(preparedPath, 'checkout-hook.txt'))).toBe(false) - if (advanceBase) { - await writeFile(join(repoPath, 'version.txt'), 'advanced\n') - git(repoPath, ['commit', '--quiet', '-am', 'advance base']) - } - const targetHead = git(repoPath, ['rev-parse', 'HEAD']) - await finalizePreparedWorktree( - repoPath, - preparedPath, - finalPath, - 'feature/attached', - 'main', - false, - {}, - lockReason - ) - - expect(git(finalPath, ['rev-parse', 'HEAD'])).toBe(targetHead) - expect(git(finalPath, ['symbolic-ref', '--short', 'HEAD'])).toBe('feature/attached') - expect( - git(finalPath, ['for-each-ref', '--format=%(upstream)', 'refs/heads/feature/attached']) - ).toBe('') - expect(await readFile(join(finalPath, 'checkout-hook.txt'), 'utf8')).toBe( - `${targetHead}\n${targetHead}\n1\nfeature/attached\n` - ) - await rm(join(finalPath, 'checkout-hook.txt')) - expect(await readFile(join(finalPath, 'version.txt'), 'utf8')).toBe( - advanceBase ? 'advanced\n' : 'one\n' - ) - expect(git(finalPath, ['status', '--porcelain'])).toBe('') - } - ) - - it('never publishes a branch at a HEAD changed before attachment', async () => { - const { repoPath, root } = await createRepo() - const preparedPath = join(root, 'prepared-race') - const finalPath = join(root, 'final-race') - const lockReason = createWorktreePreparationLockReason('head-race') - await prepareWorktreeCreateCheckout(repoPath, preparedPath, 'main', lockReason) - const expectedHead = git(repoPath, ['rev-parse', 'HEAD']) - git(repoPath, ['checkout', '--quiet', '-b', 'other']) - await writeFile(join(repoPath, 'version.txt'), 'other\n') - git(repoPath, ['commit', '--quiet', '-am', 'other commit']) - const otherHead = git(repoPath, ['rev-parse', 'HEAD']) - git(repoPath, ['checkout', '--quiet', 'main']) - - const original = gitRunner.gitExecFileAsync - const spy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation((args, options) => { - if (args.includes('checkout') || args.includes('switch')) { - git(finalPath, ['reset', '--hard', otherHead]) - } - return original(args, options) - }) - try { - await finalizePreparedWorktree( - repoPath, - preparedPath, - finalPath, - 'feature/race', - 'main', - false, - {}, - lockReason - ) - } finally { - spy.mockRestore() - } - expect(git(repoPath, ['rev-parse', 'main'])).toBe(expectedHead) - expect(git(finalPath, ['rev-parse', 'HEAD'])).toBe(expectedHead) - expect(git(finalPath, ['symbolic-ref', '--short', 'HEAD'])).toBe('feature/race') - expect(await readFile(join(finalPath, 'version.txt'), 'utf8')).toBe('one\n') - }) - - it('accepts a commit made by the post-checkout hook during attachment', async () => { - const { repoPath, root } = await createRepo() - const preparedPath = join(root, 'prepared-hook-commit') - const finalPath = join(root, 'final-hook-commit') - const hooksPath = join(root, 'hooks') - await mkdir(hooksPath) - await writeFile( - join(hooksPath, 'post-checkout'), - '#!/bin/sh\nprintf "invoked\\n" >> hook-invocations.txt\ngit add hook-invocations.txt\ngit commit --quiet -m "hook commit"\n', - { mode: 0o755 } - ) - git(repoPath, ['config', 'core.hooksPath', hooksPath]) - const lockReason = createWorktreePreparationLockReason('hook-commit') - await prepareWorktreeCreateCheckout(repoPath, preparedPath, 'main', lockReason) - const baseHead = git(repoPath, ['rev-parse', 'HEAD']) - - await finalizePreparedWorktree( - repoPath, - preparedPath, - finalPath, - 'feature/hook-commit', - 'main', - false, - {}, - lockReason - ) - - expect(git(finalPath, ['symbolic-ref', '--short', 'HEAD'])).toBe('feature/hook-commit') - expect(git(finalPath, ['rev-parse', 'HEAD^'])).toBe(baseHead) - expect(git(finalPath, ['show', '-s', '--format=%s', 'HEAD'])).toBe('hook commit') - expect(await readFile(join(finalPath, 'hook-invocations.txt'), 'utf8')).toBe('invoked\n') - expect(git(finalPath, ['status', '--porcelain'])).toBe('') - }) - - it('cleans up a branch when post-checkout rejects the attachment', async () => { - const { repoPath, root } = await createRepo() - const preparedPath = join(root, 'prepared-hook-failure') - const finalPath = join(root, 'final-hook-failure') - const hooksPath = join(root, 'hooks') - await mkdir(hooksPath) - await writeFile(join(hooksPath, 'post-checkout'), '#!/bin/sh\nexit 1\n', { mode: 0o755 }) - git(repoPath, ['config', 'core.hooksPath', hooksPath]) - const lockReason = createWorktreePreparationLockReason('hook-failure') - await prepareWorktreeCreateCheckout(repoPath, preparedPath, 'main', lockReason) - - await expect( - finalizePreparedWorktree( - repoPath, - preparedPath, - finalPath, - 'feature/hook-failure', - 'main', - false, - {}, - lockReason - ) - ).rejects.toThrow() - expect(existsSync(finalPath)).toBe(false) - expect(git(repoPath, ['branch', '--list', 'feature/hook-failure'])).toBe('') - }) - - it('retains preparation ownership when the removal command cannot start', async () => { - const fixture = await createRepo() - const repoPath = await realpath(fixture.repoPath) - const root = await realpath(fixture.root) - const preparedPath = join(root, WORKTREE_CREATE_PREPARATION_DIRECTORY, 'owned-removal') - await mkdir(join(root, WORKTREE_CREATE_PREPARATION_DIRECTORY), { recursive: true }) - const lockReason = createWorktreePreparationLockReason('removal-failure') - await prepareWorktreeCreateCheckout(repoPath, preparedPath, 'main', lockReason) - const original = gitRunner.gitExecFileAsync - const spy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation((args, options) => { - if (args.includes('remove') && args.some((arg) => areWorktreePathsEqual(arg, preparedPath))) { - return Promise.reject(new Error('injected removal launch failure')) - } - return original(args, options) - }) - try { - await expect(discardPreparedWorktree(repoPath, preparedPath, {}, lockReason)).rejects.toThrow( - 'injected removal launch failure' - ) - const remaining = await listWorktrees(repoPath, { includeCreatePreparations: true }) - const prepared = remaining.find((worktree) => - areWorktreePathsEqual(worktree.path, preparedPath) - ) - expect(prepared).toBeDefined() - expect(prepared?.lockReason).toBe(lockReason) - expect(await readFile(join(preparedPath, 'version.txt'), 'utf8')).toBe('one\n') - } finally { - spy.mockRestore() - await discardPreparedWorktree(repoPath, preparedPath, {}, lockReason) - } - expect(existsSync(preparedPath)).toBe(false) - }) - - it('creates and finalizes while dead-owner reclamation is stalled', async () => { - const fixture = await createRepo() - const repoPath = await realpath(fixture.repoPath) - const root = await realpath(fixture.root) - const preparationRoot = join(root, WORKTREE_CREATE_PREPARATION_DIRECTORY) - const stalePath = join(preparationRoot, '999999999-11111111-1111-4111-8111-111111111111') - await mkdir(preparationRoot, { recursive: true }) - await prepareWorktreeCreateCheckout( - repoPath, - stalePath, - 'main', - 'orca-create-preparation:v1:999999999:stale' - ) - let releaseRemoval!: () => void - const removalGate = new Promise((resolve) => { - releaseRemoval = resolve - }) - let markRemovalStarted!: () => void - const removalStarted = new Promise((resolve) => { - markRemovalStarted = resolve - }) - const original = gitRunner.gitExecFileAsync - const spy = vi - .spyOn(gitRunner, 'gitExecFileAsync') - .mockImplementation(async (args, options) => { - if (args.includes('remove') && args.some((arg) => areWorktreePathsEqual(arg, stalePath))) { - markRemovalStarted() - await removalGate - } - return original(args, options) - }) - try { - const preparing = startPreparation({ - repoPath, - workspaceRoot: root, - baseBranch: 'main', - canonicalBase: 'refs/heads/main', - options: {} - }) - await removalStarted - expect(hasPendingStalePreparationCleanup()).toBe(true) - await preparing - const [entry] = listPreparations() - expect(entry).toBeDefined() - takePreparation(entry) - const finalPath = join(root, 'fresh-worktree') - await finalizePreparedWorktree( - repoPath, - entry.preparedPath, - finalPath, - 'fresh', - 'main', - false, - {}, - entry.lockReason - ) - expect(git(finalPath, ['status', '--porcelain'])).toBe('') - expect(git(finalPath, ['symbolic-ref', '--short', 'HEAD'])).toBe('fresh') - expect(await readFile(join(finalPath, 'version.txt'), 'utf8')).toBe('one\n') - expect(existsSync(stalePath)).toBe(true) - expect(hasPendingStalePreparationCleanup()).toBe(true) - releaseRemoval() - await _resetPreparationPoolForTests() - expect(existsSync(stalePath)).toBe(false) - const remaining = await listWorktrees(repoPath, { includeCreatePreparations: true }) - expect(remaining).toHaveLength(2) - expect(remaining.some((w) => areWorktreePathsEqual(w.path, repoPath))).toBe(true) - expect(remaining.some((w) => areWorktreePathsEqual(w.path, finalPath))).toBe(true) - expect(hasPendingStalePreparationCleanup()).toBe(false) - } finally { - releaseRemoval() - await _resetPreparationPoolForTests() - spy.mockRestore() - } - }) - - it('removes partial checkout files and registration after materialization is aborted', async () => { - const { repoPath, root } = await createRepo() - await Promise.all( - Array.from({ length: 1000 }, (_, index) => - writeFile( - join(repoPath, `payload-${index.toString().padStart(4, '0')}.txt`), - 'payload'.repeat(128) - ) - ) - ) - git(repoPath, ['add', '.']) - git(repoPath, ['commit', '--quiet', '-m', 'materialization fixture']) - const preparationRoot = join(root, WORKTREE_CREATE_PREPARATION_DIRECTORY) - const preparedPath = join(preparationRoot, `${process.pid}-partial`) - await mkdir(preparationRoot, { recursive: true }) - const controller = new AbortController() - const original = gitRunner.gitExecFileAsync - let watcher: FSWatcher | undefined - let observedMaterialization = false - const calls: string[][] = [] - const spy = vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation((args, options) => { - calls.push([...args]) - if (args.includes('reset')) { - watcher = watch(preparedPath, (_event, filename) => { - // Only the reset writes here, so an event without a filename is still materialization. - if (filename === null || filename.toString().startsWith('payload-')) { - observedMaterialization = true - watcher?.close() - controller.abort() - } - }) - } - return original(args, options) - }) - try { - await expect( - prepareWorktreeCreateCheckout( - repoPath, - preparedPath, - 'main', - createWorktreePreparationLockReason('partial-test'), - { signal: controller.signal } - ) - ).rejects.toThrow() - expect(observedMaterialization).toBe(true) - expect(calls.some((args) => args[args.indexOf('worktree') + 1] === 'lock')).toBe(false) - expect(existsSync(preparedPath)).toBe(false) - expect(await listWorktrees(repoPath, { includeCreatePreparations: true })).toHaveLength(1) - } finally { - watcher?.close() - spy.mockRestore() - } - }) - - it('cleans up when the create signal is canceled', async () => { - const { repoPath, root } = await createRepo() - const preparationRoot = join(root, WORKTREE_CREATE_PREPARATION_DIRECTORY) - const preparedPath = join(preparationRoot, `${process.pid}-canceled`) - await mkdir(preparationRoot, { recursive: true }) - - const lockReason = createWorktreePreparationLockReason('canceled-test') - await prepareWorktreeCreateCheckout(repoPath, preparedPath, 'main', lockReason) - - const controller = new AbortController() - controller.abort() - await expect( - discardPreparedWorktree(repoPath, preparedPath, { signal: controller.signal }, lockReason) - ).resolves.toBe('removed') - - expect(await listWorktrees(repoPath, { includeCreatePreparations: true })).toHaveLength(1) - }) - - it('lands a cross-base retarget on exactly the requested commit', async () => { - const { repoPath, root } = await createRepo() - const preparationRoot = join(root, WORKTREE_CREATE_PREPARATION_DIRECTORY) - const preparedPath = join(preparationRoot, `${process.pid}-retarget`) - const finalPath = join(root, 'retargeted-worktree') - await mkdir(preparationRoot, { recursive: true }) - - await writeFile(join(repoPath, 'shared.txt'), 'kept\n') - git(repoPath, ['add', 'shared.txt']) - git(repoPath, ['commit', '--quiet', '-m', 'local main']) - const localMainHead = git(repoPath, ['rev-parse', 'HEAD']) - - git(repoPath, ['checkout', '--quiet', '-b', 'upstream-main']) - await writeFile(join(repoPath, 'version.txt'), 'two\n') - await writeFile(join(repoPath, 'only-upstream.txt'), 'upstream\n') - git(repoPath, ['rm', '--quiet', 'shared.txt']) - git(repoPath, ['add', 'version.txt', 'only-upstream.txt']) - git(repoPath, ['commit', '--quiet', '-m', 'upstream main']) - git(repoPath, ['update-ref', 'refs/remotes/origin/main', 'HEAD']) - git(repoPath, ['checkout', '--quiet', 'main']) - git(repoPath, ['branch', '--quiet', '-D', 'upstream-main']) - - await prepareWorktreeCreateCheckout( - repoPath, - preparedPath, - 'refs/remotes/origin/main', - createWorktreePreparationLockReason('retarget-test') - ) - expect(git(preparedPath, ['rev-parse', 'HEAD'])).not.toBe(localMainHead) - - await finalizePreparedWorktree( - repoPath, - preparedPath, - finalPath, - 'feature/retargeted', - 'main', - false, - {}, - createWorktreePreparationLockReason('retarget-test') - ) - - expect(git(finalPath, ['rev-parse', 'HEAD'])).toBe(localMainHead) - expect(git(finalPath, ['status', '--porcelain'])).toBe('') - expect((await readFile(join(finalPath, 'version.txt'), 'utf8')).replaceAll('\r\n', '\n')).toBe( - 'one\n' - ) - expect((await readFile(join(finalPath, 'shared.txt'), 'utf8')).replaceAll('\r\n', '\n')).toBe( - 'kept\n' - ) - await expect(readFile(join(finalPath, 'only-upstream.txt'), 'utf8')).rejects.toThrow() - expect(git(finalPath, ['branch', '--show-current'])).toBe('feature/retargeted') - expect(git(finalPath, ['config', '--get', 'branch.feature/retargeted.base'])).toBe( - 'refs/heads/main' - ) - }) -}) - it.each(['replacement', 'permission'])( 'preserves the requested path when rollback loses %s authority', async (kind) => { diff --git a/src/main/github/pr-refresh-coordinator-error-cadence.test.ts b/src/main/github/pr-refresh-coordinator-error-cadence.test.ts deleted file mode 100644 index 07c84232bbc..00000000000 --- a/src/main/github/pr-refresh-coordinator-error-cadence.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { coordinatorMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./pr-refresh-coordinator-test-mocks') - return { coordinatorMocks: moduleMocks.createPRRefreshCoordinatorMocks(), moduleMocks } -}) -vi.mock('./pr-refresh-renderer-port', () => moduleMocks.rendererPortModuleMock(coordinatorMocks)) -vi.mock('./client', () => moduleMocks.clientModuleMock(coordinatorMocks)) -vi.mock('./github-api-repository', () => - moduleMocks.githubApiRepositoryModuleMock(coordinatorMocks) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(coordinatorMocks)) - -import { makeCandidate } from './pr-refresh-coordinator-test-harness' - -const { getPRForBranchOutcomeMock } = coordinatorMocks - -describe('failed main refresh pacing', () => { - beforeEach(() => { - moduleMocks.resetPRRefreshCoordinatorMocks(coordinatorMocks) - getPRForBranchOutcomeMock.mockImplementation(async () => ({ - kind: 'upstream-error', - errorType: 'network', - message: 'offline', - fetchedAt: Date.now() - })) - }) - afterEach(() => vi.useRealTimers()) - - it('panel foreground exposure cannot bypass a failed lookup deadline', async () => { - const { reportVisiblePRRefreshCandidates, enqueuePRRefresh } = - await import('./pr-refresh-coordinator') - const candidate = makeCandidate({ isSelected: true }) - reportVisiblePRRefreshCandidates([candidate], 1, 1) - await vi.advanceTimersByTimeAsync(0) - enqueuePRRefresh(candidate, 'visible', 80, 1) - await vi.advanceTimersByTimeAsync(59_999) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(1) - expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/main/ipc/ai-vault/ai-vault-search-all-hosts-real-index.test.ts b/src/main/ipc/ai-vault/ai-vault-search-all-hosts-real-index.test.ts index 8ad7e9e9ff4..b5ce86b44b6 100644 --- a/src/main/ipc/ai-vault/ai-vault-search-all-hosts-real-index.test.ts +++ b/src/main/ipc/ai-vault/ai-vault-search-all-hosts-real-index.test.ts @@ -1,4 +1,4 @@ -import '../../ai-vault-search/session-search-worker.test-fixture' +import '../../ai-vault-search/worker/session-search-worker.test-fixture' import { mkdir, rm, writeFile } from 'node:fs/promises' import { join } from 'node:path' import { afterEach, beforeEach, expect, it } from 'vitest' @@ -9,7 +9,7 @@ import { claudeLines, openSessionSearchIndexerHarness, type SessionSearchIndexerHarness -} from '../../ai-vault-search/session-search-indexer-test-fixture' +} from '../../ai-vault-search/indexing/session-search-indexer-test-fixture' import type { AiVaultSearchResponse } from '../../../shared/ai-vault/search/ai-vault-search-types' import type { ExecutionHostId } from '../../../shared/execution-host' import { searchAllExecutionHosts, type SessionSearchHostLeg } from './ai-vault-search-all-hosts' @@ -107,39 +107,6 @@ function everyKey(): string[] { ) } -async function paginate( - limit: number, - sort: 'relevance' | 'newest', - hostLegs = legs() -): Promise<{ keys: string[]; pages: number }> { - const request = { query: 'needle', limit, filters: { sort } } - const keys: string[] = [] - let cursor: string | null = null - let pages = 0 - do { - const response = resultsOf( - await searchAllExecutionHosts(cursor === null ? request : { ...request, cursor }, hostLegs) - ) - keys.push(...keysOf(response)) - cursor = response.page.cursor - pages++ - expect(pages).toBeLessThan(40) - } while (cursor !== null) - return { keys, pages } -} - -it('hands out every hit on every host exactly once, at limit 5 and limit 20', async () => { - const expected = everyKey().sort() - expect(expected).toHaveLength(40) - for (const limit of [5, 20]) { - for (const sort of ['relevance', 'newest'] as const) { - const { keys } = await paginate(limit, sort) - expect(new Set(keys).size, `${sort} at ${limit} repeated a hit`).toBe(keys.length) - expect([...keys].sort(), `${sort} at ${limit} lost a hit`).toEqual(expected) - } - } -}) - it('replays snapshot tails then fences the changed host at its next read while healthy hosts finish', async () => { const request = { query: 'needle', limit: 5 } const first = resultsOf(await searchAllExecutionHosts(request, legs())) diff --git a/src/main/ipc/ai-vault/ai-vault-search-all-hosts.ts b/src/main/ipc/ai-vault/ai-vault-search-all-hosts.ts index 595908e8c1c..ee7cb55f00f 100644 --- a/src/main/ipc/ai-vault/ai-vault-search-all-hosts.ts +++ b/src/main/ipc/ai-vault/ai-vault-search-all-hosts.ts @@ -1,5 +1,5 @@ import { createHash } from 'node:crypto' -import { sessionSearchPageKey } from '../../ai-vault-search/session-search-page-cursor' +import { sessionSearchPageKey } from '../../ai-vault-search/query/session-search-page-cursor' import { resolveSessionSearchLimit } from '../../../shared/ai-vault/search/ai-vault-search-limit' import type { AiVaultSearchHit, diff --git a/src/main/ipc/browser/browser-session-profile-ipc.test.ts b/src/main/ipc/browser/browser-session-profile-ipc.test.ts index 39d8ad1876f..ef1bf1f0d7b 100644 --- a/src/main/ipc/browser/browser-session-profile-ipc.test.ts +++ b/src/main/ipc/browser/browser-session-profile-ipc.test.ts @@ -1,3 +1,4 @@ +// @orca-isolated-worker: browser registration retains grant listeners bound to this file's mocks. import { beforeEach, describe, expect, it, vi } from 'vitest' const { diff --git a/src/main/ipc/emulator-renderer-lifetime.test.ts b/src/main/ipc/emulator-renderer-lifetime.test.ts index 02aba12db8d..23e8414e39a 100644 --- a/src/main/ipc/emulator-renderer-lifetime.test.ts +++ b/src/main/ipc/emulator-renderer-lifetime.test.ts @@ -1,5 +1,6 @@ import { EventEmitter } from 'node:events' import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { AvccFrameStreamCallbacks } from '../emulator/avcc-frame-stream' import type { MjpegFrameStreamCallbacks } from '../emulator/mjpeg-frame-stream' import type { ScrcpyVideoSubscriber } from '../emulator/scrcpy-video-registry' @@ -10,7 +11,10 @@ const mocks = vi.hoisted(() => ({ frameStarts: vi.fn(), frameStops: vi.fn(), videoStarts: vi.fn(), - videoStops: vi.fn() + videoStops: vi.fn(), + avccStarts: vi.fn<(url: string) => void>(), + avccStops: vi.fn(), + avccCallbacks: new Set() })) vi.mock('electron', () => ({ @@ -49,6 +53,22 @@ vi.mock('../emulator/scrcpy-video-registry', () => ({ } } })) +vi.mock('../emulator/avcc-frame-stream', () => ({ + AvccFrameStream: class { + constructor( + private url: string, + private callbacks: AvccFrameStreamCallbacks + ) {} + start(): void { + mocks.avccStarts(this.url) + mocks.avccCallbacks.add(this.callbacks) + } + stop(): void { + mocks.avccStops() + mocks.avccCallbacks.delete(this.callbacks) + } + } +})) vi.mock('../emulator/emulator-probe', () => ({ emulatorProbe: () => {} })) import { registerEmulatorFrameStreamHandlers } from './emulator-frame-stream' @@ -61,6 +81,7 @@ class Owner extends EventEmitter { const owners: Owner[] = [] const goneEvents = ['did-navigate', 'render-process-gone', 'destroyed'] as const +const IOS_UDID = '5C1A9A5E-0000-4000-8000-000000000001' function owner(): Owner { const sender = new Owner() @@ -100,7 +121,9 @@ beforeEach(() => { vi.useFakeTimers() vi.clearAllMocks() registerEmulatorFrameStreamHandlers() - registerEmulatorVideoStreamHandlers() + registerEmulatorVideoStreamHandlers((deviceId) => + deviceId === IOS_UDID ? `http://127.0.0.1:3100/helper/${IOS_UDID}/stream.avcc` : null + ) }) afterEach(() => { @@ -111,6 +134,7 @@ afterEach(() => { vi.useRealTimers() mocks.frameCallbacks.clear() mocks.videoSubscribers.clear() + mocks.avccCallbacks.clear() }) it.each(goneEvents)('stops both live streams on %s and leaves no per-frame delivery', (event) => { @@ -214,3 +238,51 @@ it.each([...goneEvents, 'explicit stop'] as const)( expect(sender.send).toHaveBeenCalledOnce() } ) + +function startIosVideo(sender: Owner): void { + mocks.handlers.get('emulator:videoStreamStart')?.( + { sender }, + { deviceId: IOS_UDID, streamId: 'ios-stream' } + ) + vi.runOnlyPendingTimers() +} + +it('streams a registered iOS device from its helper and releases it with the renderer', () => { + const sender = owner() + startIosVideo(sender) + expect(mocks.avccStarts).toHaveBeenCalledOnce() + expect(mocks.avccStarts).toHaveBeenCalledWith( + `http://127.0.0.1:3100/helper/${IOS_UDID}/stream.avcc` + ) + expect(mocks.videoStarts).not.toHaveBeenCalled() + + const [callbacks] = mocks.avccCallbacks + const bytes = new ArrayBuffer(4) + callbacks.onFrame({ config: true, keyFrame: false, bytes }) + expect(sender.send).toHaveBeenCalledWith('emulator:videoStreamFrame', { + streamId: 'ios-stream', + deviceId: IOS_UDID, + config: true, + keyFrame: false, + bytes + }) + + sender.emit('render-process-gone') + expect(mocks.avccStops).toHaveBeenCalledOnce() + expect(mocks.avccCallbacks.size).toBe(0) +}) + +it('reports an iOS video failure on the stream error channel and releases the helper stream', () => { + const sender = owner() + startIosVideo(sender) + const [callbacks] = mocks.avccCallbacks + callbacks.onError('Simulator video stream returned HTTP 404.') + expect(sender.send).toHaveBeenCalledWith('emulator:frameStreamError', { + streamId: 'ios-stream', + message: 'Simulator video stream returned HTTP 404.' + }) + expect(mocks.avccStops).toHaveBeenCalledOnce() + for (const event of goneEvents) { + expect(sender.listenerCount(event)).toBe(0) + } +}) diff --git a/src/main/ipc/emulator-video-stream.ts b/src/main/ipc/emulator-video-stream.ts index 734871d7fa0..fc06467a3ad 100644 --- a/src/main/ipc/emulator-video-stream.ts +++ b/src/main/ipc/emulator-video-stream.ts @@ -1,11 +1,14 @@ import { BrowserWindow, ipcMain, type WebContents } from 'electron' import { randomUUID } from 'node:crypto' +import { AvccFrameStream } from '../emulator/avcc-frame-stream' import { scrcpyVideoRegistry } from '../emulator/scrcpy-video-registry' import { emulatorProbe } from '../emulator/emulator-probe' +import { errorMessage } from '../../shared/error-message' import { abortWhenRendererGone } from './renderer-lifetime-abort' -// Relay scrcpy metadata/H.264 units to renderer subscribers, parallel to the MJPEG stream handler. -export function registerEmulatorVideoStreamHandlers(): void { +export function registerEmulatorVideoStreamHandlers( + resolveIosVideoStreamUrl: (deviceId: string) => string | null | undefined +): void { type Subscription = { owner: WebContents unsubscribe: () => void @@ -62,6 +65,34 @@ export function registerEmulatorVideoStreamHandlers(): void { if (owner.isDestroyed() || subscriptions.get(streamId) !== pendingSubscription) { return } + const iosVideoStreamUrl = resolveIosVideoStreamUrl(args.deviceId) + if (iosVideoStreamUrl) { + const fail = (message: string): void => { + stopSubscription(streamId, owner) + if (!owner.isDestroyed()) { + owner.send('emulator:frameStreamError', { streamId, message }) + } + } + const stream = new AvccFrameStream(iosVideoStreamUrl, { + onFrame: (frame) => { + if (!owner.isDestroyed()) { + owner.send('emulator:videoStreamFrame', { + streamId, + deviceId: args.deviceId, + ...frame + }) + } + }, + onError: fail + }) + pendingSubscription.unsubscribe = () => stream.stop() + try { + stream.start() + } catch (error) { + fail(errorMessage(error)) + } + return + } const unsubscribe = scrcpyVideoRegistry.subscribe(args.deviceId, (videoEvent) => { if (owner.isDestroyed()) { return diff --git a/src/main/ipc/filesystem/filesystem-read-handlers.ts b/src/main/ipc/filesystem/filesystem-read-handlers.ts index 1ae71c73ec1..c93a3f126f8 100644 --- a/src/main/ipc/filesystem/filesystem-read-handlers.ts +++ b/src/main/ipc/filesystem/filesystem-read-handlers.ts @@ -1,4 +1,5 @@ import { classifyFilesystemDirectoryEntries } from './filesystem-symlink-directory-entries' +import { hasSymlinkBelowRoot } from './filesystem-symlink-ancestor' import { markdownDocumentsFromRelativePaths } from '../../../shared/file-listing/markdown-document-paths' import { capturePathExistence, @@ -200,6 +201,16 @@ export function registerFilesystemReadHandlers(context: FilesystemHandlerContext } ) + ipcMain.handle( + 'fs:hasSymlinkBelowRoot', + (_event, args: { rootPath: string; path: string }): Promise => + guardWslUncPathAccess(args.rootPath, async () => { + // Why the root: the walk stops at the first link, so it never touches anything outside it. + await resolveDesktopAuthorizedPath(args.rootPath, store) + return hasSymlinkBelowRoot(args.rootPath, args.path) + }) + ) + ipcMain.handle( 'fs:pathsExist', async ( diff --git a/src/main/ipc/filesystem/filesystem-symlink-ancestor.test.ts b/src/main/ipc/filesystem/filesystem-symlink-ancestor.test.ts new file mode 100644 index 00000000000..224a1f2596c --- /dev/null +++ b/src/main/ipc/filesystem/filesystem-symlink-ancestor.test.ts @@ -0,0 +1,44 @@ +import { mkdir, mkdtemp, rm, symlink } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { hasSymlinkBelowRoot } from './filesystem-symlink-ancestor' + +describe('hasSymlinkBelowRoot', () => { + let base: string + + beforeEach(async () => { + base = await mkdtemp(join(tmpdir(), 'orca-symlink-ancestor-')) + await mkdir(join(base, 'outside', 'Tasks', 'sub'), { recursive: true }) + await mkdir(join(base, 'workspace', 'Documents', 'real'), { recursive: true }) + // Why junction: Windows creates it without admin rights; POSIX ignores the type. + await symlink( + join(base, 'outside', 'Tasks'), + join(base, 'workspace', 'Documents', 'Tasks'), + 'junction' + ) + await symlink(join(base, 'workspace'), join(base, 'workspace-link'), 'junction') + }) + + afterEach(async () => { + await rm(base, { recursive: true, force: true }) + }) + + it('finds a linked folder between the root and the path', async () => { + const root = join(base, 'workspace') + await expect(hasSymlinkBelowRoot(root, join(root, 'Documents', 'Tasks'))).resolves.toBe(true) + await expect(hasSymlinkBelowRoot(root, join(root, 'Documents', 'Tasks', 'sub'))).resolves.toBe( + true + ) + }) + + it('ignores ordinary folders, including under a root that is itself a link', async () => { + await expect( + hasSymlinkBelowRoot(join(base, 'workspace'), join(base, 'workspace', 'Documents', 'real')) + ).resolves.toBe(false) + const linkedRoot = join(base, 'workspace-link') + await expect( + hasSymlinkBelowRoot(linkedRoot, join(linkedRoot, 'Documents', 'real')) + ).resolves.toBe(false) + }) +}) diff --git a/src/main/ipc/filesystem/filesystem-symlink-ancestor.ts b/src/main/ipc/filesystem/filesystem-symlink-ancestor.ts new file mode 100644 index 00000000000..e4e5e2cb104 --- /dev/null +++ b/src/main/ipc/filesystem/filesystem-symlink-ancestor.ts @@ -0,0 +1,22 @@ +import { lstat } from 'node:fs/promises' +import { join, relative, resolve, sep } from 'node:path' +import { windowsFsPath } from '../../wsl/filesystem/wsl-unc-drive-fs-path' +import { isDescendantOrEqualExact } from './access/filesystem-path-containment' + +/** True when a component strictly below `rootPath` on the way to `targetPath` is a symlink or junction. */ +export async function hasSymlinkBelowRoot(rootPath: string, targetPath: string): Promise { + const root = resolve(rootPath) + const target = resolve(targetPath) + if (root === target || !isDescendantOrEqualExact(target, root)) { + return false + } + let current = root + for (const segment of relative(root, target).split(sep)) { + current = join(current, segment) + // Why lstat, not realpath: realpath also folds letter case, which would flag ordinary folders. + if ((await lstat(windowsFsPath(current))).isSymbolicLink()) { + return true + } + } + return false +} diff --git a/src/main/ipc/filesystem/filesystem-write-identical.test.ts b/src/main/ipc/filesystem/filesystem-write-identical.test.ts deleted file mode 100644 index c1594da207e..00000000000 --- a/src/main/ipc/filesystem/filesystem-write-identical.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { getDiskBaselineSignature } from '../../../shared/file-write/disk-baseline-signature' - -import { registerFilesystemWriteHandlers } from './filesystem-write-handlers' -import type { FilesystemHandlerContext } from './filesystem-handler-context' - -const handlers = vi.hoisted(() => new Map unknown>()) -vi.mock('electron', () => ({ - ipcMain: { - handle: (name: string, handler: (_event: unknown, args: unknown) => unknown) => - handlers.set(name, handler) - }, - shell: {} -})) -vi.mock('./access/local-file-access-resolution', () => ({ - resolveLocalWriteRequestPath: async (path: string) => path -})) -vi.mock('./filesystem-mutations', () => ({ registerFilesystemMutationHandlers: vi.fn() })) -vi.mock('../agent-session-attachment-upload-ipc', () => ({ - registerAgentSessionAttachmentUploadHandlers: vi.fn() -})) - -let root = '' -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-identical-ipc-')) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: authorization is stubbed, and no other context member is used by this handler. - registerFilesystemWriteHandlers({ store: {} } as FilesystemHandlerContext) -}) -afterEach(async () => { - await rm(root, { recursive: true, force: true }) - handlers.clear() -}) - -it('accepts identical content on a readable, non-writable file through IPC', async () => { - const filePath = join(root, 'read-only.txt') - await writeFile(filePath, 'edited') - await chmod(filePath, 0o444) - try { - await expect( - handlers.get('fs:writeFile')!(null, { - filePath, - content: 'edited', - diskPrecondition: { expectedSignature: getDiskBaselineSignature('original') } - }) - ).resolves.toEqual({ ok: true, unchanged: true }) - expect(await readFile(filePath, 'utf8')).toBe('edited') - } finally { - await chmod(filePath, 0o644) - } -}) diff --git a/src/main/ipc/profiles/orca-profile-org-members-handlers.ts b/src/main/ipc/profiles/orca-profile-org-members-handlers.ts index 40121eadff6..153e95a94ac 100644 --- a/src/main/ipc/profiles/orca-profile-org-members-handlers.ts +++ b/src/main/ipc/profiles/orca-profile-org-members-handlers.ts @@ -16,7 +16,7 @@ import { listOrcaProfileOrgMembers, removeOrcaProfileOrgMember, revokeOrcaProfileOrgInvite -} from '../../orca-profiles/profile-cloud-org-members-service' +} from '../../orca-profiles/cloud-org/profile-cloud-org-members-service' function orgMembersScopedArgs(args: unknown): { orgId: string; record: Record } { if (!args || typeof args !== 'object') { diff --git a/src/main/ipc/profiles/orca-profiles-switch-persistence.test.ts b/src/main/ipc/profiles/orca-profiles-switch-persistence.test.ts index f30c497ae0b..64b2af0533c 100644 --- a/src/main/ipc/profiles/orca-profiles-switch-persistence.test.ts +++ b/src/main/ipc/profiles/orca-profiles-switch-persistence.test.ts @@ -1,4 +1,4 @@ -import { existsSync } from 'node:fs' +import 'node:fs' import { describe, expect, it, vi } from 'vitest' import { createWorkerMaintenanceFixture, @@ -26,7 +26,7 @@ vi.mock('../../orca-profiles/profile-index-store', () => ({ createLocalOrcaProfile: vi.fn() })) -vi.mock('../../orca-profiles/new-profile-state', () => ({ +vi.mock('../../orca-profiles/storage/new-profile-state', () => ({ initializeNewOrcaProfileState: vi.fn() })) vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) @@ -77,40 +77,4 @@ describe('plain profile switch persistence', () => { workspaceSession: { activeTabId: 'last-tab' } }) }) - - it('admits pre-relaunch writes and includes quit-time edits in the final source checkpoint', async () => { - const { store, readState, dataFile } = await createWorkerMaintenanceFixture() - vi.spyOn(console, 'warn').mockImplementation(() => {}) - await store.flushPendingOrThrowAsync() - const cleanupSaved = vi.fn() - let final: Promise | undefined - quit.mockImplementation(() => { - store.getWorkspaceSession().activeTabId = 'last-tab' - final = store.flushFinalOrThrowAsync() - }) - registerOrcaProfileHandlers(store, { - onBeforeRelaunch: async () => { - store.updateSettings({ theme: 'light' }) - await store.flushPendingOrThrowAsync({ drainToStableGeneration: false }) - cleanupSaved() - } - }) - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) - const switchProfile = handlers.get('orcaProfiles:switch') - expect(switchProfile).toBeDefined() - await switchProfile?.( - { sender: { isDestroyed: () => false, send: vi.fn() } }, - { profileId: 'target' } - ) - await vi.advanceTimersByTimeAsync(150) - expect(final).toBeDefined() - await final - expect(select).toHaveBeenCalledWith('target') - expect(cleanupSaved).toHaveBeenCalledOnce() - expect(readState()).toMatchObject({ - settings: { theme: 'light' }, - workspaceSession: { activeTabId: 'last-tab' } - }) - expect(existsSync(dataFile)).toBe(false) - }) }) diff --git a/src/main/ipc/profiles/orca-profiles.ts b/src/main/ipc/profiles/orca-profiles.ts index 4c77c741c56..78ee337a66a 100644 --- a/src/main/ipc/profiles/orca-profiles.ts +++ b/src/main/ipc/profiles/orca-profiles.ts @@ -27,16 +27,16 @@ import { getOrcaProfileListState, setActiveOrcaProfile } from '../../orca-profiles/profile-index-store' -import { initializeNewOrcaProfileState } from '../../orca-profiles/new-profile-state' +import { initializeNewOrcaProfileState } from '../../orca-profiles/storage/new-profile-state' import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths' import { isMultiProfileUiEnabled } from '../../orca-profiles/profile-ui-scope' -import { transferOrcaProfileProject } from '../../orca-profiles/profile-project-transfer' -import { transferActiveProfileProject } from '../../orca-profiles/profile-active-transfer' -import { findOrcaProfileProjectsByPath } from '../../orca-profiles/profile-project-presence' +import { transferOrcaProfileProject } from '../../orca-profiles/project-transfer/profile-project-transfer' +import { transferActiveProfileProject } from '../../orca-profiles/project-transfer/profile-active-transfer' +import { findOrcaProfileProjectsByPath } from '../../orca-profiles/catalog/profile-project-presence' import { flushActiveProfileBeforeFileMutation, flushActiveProfileBeforeRelaunch -} from '../../orca-profiles/profile-persistence-deadline' +} from '../../orca-profiles/storage/profile-persistence-deadline' import { normalizeExecutionHostId } from '../../../shared/execution-host' import { createCloudLinkedOrcaProfile, @@ -44,10 +44,10 @@ import { getCurrentOrcaProfileAuthStatus, selectCurrentOrcaProfileOrg, signOutCurrentOrcaProfile -} from '../../orca-profiles/profile-cloud-service' -import { refreshCurrentOrcaProfileAuth } from '../../orca-profiles/profile-cloud-capability-refresh' +} from '../../orca-profiles/cloud-auth/profile-cloud-service' +import { refreshCurrentOrcaProfileAuth } from '../../orca-profiles/cloud-auth/profile-cloud-capability-refresh' import { registerOrcaProfileOrgMemberHandlers } from './orca-profile-org-members-handlers' -import { onOrcaCloudSessionInvalidated } from '../../orca-profiles/profile-cloud-session-invalidation' +import { onOrcaCloudSessionInvalidated } from '../../orca-profiles/cloud-session/profile-cloud-session-invalidation' import { broadcastOrcaProfileAuthStatusChanged, broadcastOrcaProfileSignInProgressChanged @@ -56,7 +56,7 @@ import { cancelOrcaCloudSignIn, getOrcaCloudSignInProgress, onOrcaCloudSignInProgressChanged -} from '../../orca-profiles/profile-cloud-sign-in-progress' +} from '../../orca-profiles/cloud-auth/profile-cloud-sign-in-progress' import { profileIdFromArgs } from './orca-profile-id-arg' import { transferProjectArgsFromUnknown } from './orca-profile-project-transfer-args' diff --git a/src/main/ipc/pty/pane/join-pane-spawn.test.ts b/src/main/ipc/pty/pane/join-pane-spawn.test.ts deleted file mode 100644 index ab213bf8488..00000000000 --- a/src/main/ipc/pty/pane/join-pane-spawn.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { afterEach, expect, it } from 'vitest' -import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' -import { WORKTREE_TERMINALS_SLEEPING_ERROR } from '../../../../shared/workspace-sleep' -import { adoptStablePane } from './adopt-stable' -import { - makePaneSpawnReservationKey, - paneSpawnReservationsByOwnerKey, - rejectPaneSpawnReservation, - reservePaneSpawn -} from './spawn-reservation' - -const pane = { - worktreeId: 'repo::/w', - connectionId: null, - tabId: 'tab-1', - leafId: '11111111-1111-4111-8111-111111111111' -} -const ownerKey = makePaneSpawnReservationKey( - pane.worktreeId, - null, - makePaneKey(pane.tabId, pane.leafId) -)! - -afterEach(() => paneSpawnReservationsByOwnerKey.clear()) - -it('does not hand an automatic refusal to a user adoption of the same pane', async () => { - const reservation = reservePaneSpawn(ownerKey) - const adopted = adoptStablePane(undefined, undefined, { ...pane, cols: 80, rows: 24 }) - rejectPaneSpawnReservation(ownerKey, reservation, new Error(WORKTREE_TERMINALS_SLEEPING_ERROR)) - await expect(adopted).resolves.toBeNull() -}) diff --git a/src/main/ipc/pty/runtime/kill-legacy-relay-bridged.test.ts b/src/main/ipc/pty/runtime/kill-legacy-relay-bridged.test.ts deleted file mode 100644 index b09ca853efe..00000000000 --- a/src/main/ipc/pty/runtime/kill-legacy-relay-bridged.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' -import type { SshRemotePtyLease } from '../../../../shared/ssh-types' -import { - closeLegacyRelayPane, - installLegacyRelayBridge -} from '../../../ssh/legacy-relay/bridge/legacy-relay-bridge-registry' -import { stopRendererOwnedPty, type PtyKillIpcDeps } from '../ipc/renderer-kill' - -const TARGET = 'ssh-box' -const lease: SshRemotePtyLease = { - targetId: TARGET, - ptyId: 'pty2:epoch:1', - tabId: 'tab-1', - state: 'detached', - createdAt: 1, - updatedAt: 1 -} - -describe('a tab close of a terminal an older relay still runs', () => { - it('hands the stop to the bridge instead of tombstoning the lease the bridge needs', async () => { - const leases: SshRemotePtyLease[] = [{ ...lease }] - const store = { - markSshRemotePtyLease: vi.fn((_target: string, relayPtyId: string) => { - for (const row of leases) { - if (row.ptyId === relayPtyId) { - row.state = 'terminated' - } - } - }) - } - installLegacyRelayBridge({ - leases: () => leases, - retireLease: vi.fn(), - recordStop: vi.fn(), - // Disconnected, so the SSH provider is unregistered: the bridge records the stop. - connection: () => null, - onPanesChanged: () => {}, - onData: () => {}, - onReplay: () => {}, - onExit: () => {}, - report: () => {} - }) - const ptyId = toAppSshPtyId(TARGET, lease.ptyId) - const deps = { - store, - getLocalPtyProviderStartupPromise: () => undefined, - shutdownProviderAndDetectExit: vi.fn(), - rememberSyntheticKillExit: vi.fn(), - sendPtyExitToRenderer: vi.fn() - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the bridged branch reads only these deps. - await stopRendererOwnedPty(deps as unknown as PtyKillIpcDeps, { id: ptyId }) - expect(store.markSshRemotePtyLease).not.toHaveBeenCalled() - expect(deps.shutdownProviderAndDetectExit).not.toHaveBeenCalled() - // The transport's own close that follows still reaches a pending stop, not `not-bridged`. - await expect(closeLegacyRelayPane(ptyId)).resolves.toEqual({ status: 'unverifiable' }) - installLegacyRelayBridge(null) - }) -}) diff --git a/src/main/ipc/register-core-handlers/register-core-handlers.ts b/src/main/ipc/register-core-handlers/register-core-handlers.ts index e7d56746c88..1e92599e1df 100644 --- a/src/main/ipc/register-core-handlers/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers/register-core-handlers.ts @@ -251,7 +251,7 @@ export function registerCoreHandlers( registerSessionHandlers(store, runtime) registerUIHandlers(store, { isDashboardPopoutRenderer }) registerEmulatorFrameStreamHandlers() - registerEmulatorVideoStreamHandlers() + registerEmulatorVideoStreamHandlers((id) => runtime.getEmulatorBridge()?.getIosVideoStreamUrl(id)) registerEmulatorScrcpyTouchHandler() registerEmulatorScrcpyKeyboardHandler() registerWorkspaceSpaceHandlers(store) diff --git a/src/main/ipc/renderer-lifetime-abort.test.ts b/src/main/ipc/renderer-lifetime-abort.test.ts deleted file mode 100644 index e0df317ab32..00000000000 --- a/src/main/ipc/renderer-lifetime-abort.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { EventEmitter } from 'node:events' -import { describe, expect, it } from 'vitest' -import { abortWhenRendererGone } from './renderer-lifetime-abort' -import type { FanoutEventSource } from '../runtime/events/event-listener-fanout' - -function fakeSender(): FanoutEventSource & EventEmitter { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: EventEmitter implements the once/on/removeListener surface this helper uses, and those three are all it calls; WebContents' overloaded signatures cannot be satisfied structurally. - return new EventEmitter() as FanoutEventSource & EventEmitter -} - -describe('abortWhenRendererGone', () => { - it('aborts once a reload has replaced the document, not on in-app route changes', () => { - const sender = fakeSender() - const { signal } = abortWhenRendererGone(sender) - - sender.emit('did-start-navigation', { - isMainFrame: true, - isSameDocument: true, - url: 'file:///app#x' - }) - sender.emit('did-navigate-in-page', 'file:///app#x') - expect(signal.aborted).toBe(false) - - sender.emit('did-start-navigation', { - isMainFrame: true, - isSameDocument: false, - url: 'file:///app' - }) - sender.emit('did-navigate', 'file:///app', 200, 'OK') - expect(signal.aborted).toBe(true) - }) -}) diff --git a/src/main/ipc/repos/local-repo-registration.test.ts b/src/main/ipc/repos/local-repo-registration.test.ts index 53b854a0ab4..1411541af41 100644 --- a/src/main/ipc/repos/local-repo-registration.test.ts +++ b/src/main/ipc/repos/local-repo-registration.test.ts @@ -51,16 +51,4 @@ describe('addLocalRepoFromPath through a symlink alias', () => { expect(second).toMatchObject({ alreadyExisted: true }) expect(repos).toHaveLength(1) }) - - it('keeps two different folders as two workspaces', async () => { - await mkdir(join(root, 'a')) - await mkdir(join(root, 'b')) - const repos: Repo[] = [] - const store = createStore(repos) - - await addLocalRepoFromPath(store, join(root, 'a'), 'folder') - await addLocalRepoFromPath(store, join(root, 'b'), 'folder') - - expect(repos).toHaveLength(2) - }) }) diff --git a/src/main/ipc/runtime-environments/runtime-environment-redundant-managed-removal.test.ts b/src/main/ipc/runtime-environments/runtime-environment-redundant-managed-removal.test.ts deleted file mode 100644 index fc5b0686d01..00000000000 --- a/src/main/ipc/runtime-environments/runtime-environment-redundant-managed-removal.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { addManagedOrcadEnvironment } from '../../../shared/remote-runtime/host-store/runtime-environment-managed-orcad-store' -import { encodePairingOffer } from '../../../shared/remote-runtime/pairing/pairing' -import { PAIRING_OFFER_VERSION } from '../../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import { - registerManagedServerActions, - type ManagedServerActions -} from '../../runtime/hosts/management/managed-server-actions-registry' -import { removeRedundantManagedPairing } from './runtime-environment-redundant-managed-removal' - -const forgetRedundant = vi.fn() -let userDataPath: string - -const pairingCode = (port: number, publicKeyB64: string) => - encodePairingOffer({ - v: PAIRING_OFFER_VERSION, - endpoint: `ws://127.0.0.1:${port}/`, - deviceToken: `device-${port}`, - publicKeyB64 - }) - -function addManaged(id: string, sshTargetId: string, port: number, publicKeyB64: string) { - return addManagedOrcadEnvironment(userDataPath, { - id, - name: id, - pairingCode: pairingCode(port, publicKeyB64), - orcadDeployment: { sshTargetId, sshTargetGeneration: 1, localPort: port, remotePort: 6_768 } - }) -} - -beforeEach(() => { - userDataPath = mkdtempSync(join(tmpdir(), 'redundant-managed-removal-')) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: removal only calls forgetRedundant. - registerManagedServerActions({ forgetRedundant } as unknown as ManagedServerActions) -}) - -afterEach(() => { - registerManagedServerActions(null) - forgetRedundant.mockReset() - rmSync(userDataPath, { recursive: true, force: true }) -}) - -it('leaves the pairing to the store guard when the other entry manages a different server', () => { - const environment = addManaged('managed', 'ssh-1', 46_768, 'public-key') - addManaged('other', 'ssh-2', 46_769, 'other-key') - expect(removeRedundantManagedPairing(userDataPath, environment)).toBeNull() - expect(forgetRedundant).not.toHaveBeenCalled() -}) diff --git a/src/main/ipc/ssh/ssh-disconnect-cancellation.test.ts b/src/main/ipc/ssh/ssh-disconnect-cancellation.test.ts deleted file mode 100644 index 4e5f7948461..00000000000 --- a/src/main/ipc/ssh/ssh-disconnect-cancellation.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = await vi.hoisted(async () => { - const { createSshIpcMocks } = await import('./ssh-ipc-module-mocks') - return createSshIpcMocks() -}) - -vi.mock('../../ssh/config/ssh-config-host-picker', () => mocks.sshConfigHostPicker) -vi.mock('electron', () => mocks.electron) -vi.mock('../../ssh/targets/ssh-connection-store', () => mocks.sshConnectionStore) -vi.mock('./ssh-host-server-connect', () => mocks.hostServerConnect) -vi.mock('../../ssh/connection/ssh-connection-manager', () => mocks.sshConnectionManager) -vi.mock('../../ssh/protocol/ssh-channel-multiplexer', () => mocks.sshChannelMultiplexer) -vi.mock('../../ssh/port-forwarding/ssh-port-forward', () => mocks.sshPortForward) -vi.mock('../ssh/ssh-port-scanner', () => mocks.sshPortScanner) - -import type { SshConnectionState, SshTarget } from '../../../shared/ssh-types' -import { createSshIpcHarness } from './ssh-ipc-test-harness' - -const { mockSshStore, mockConnectionManager } = mocks - -describe('SSH IPC handlers', () => { - const harness = createSshIpcHarness(mocks) - const { handlers } = harness - - beforeEach(harness.reset) - - it('lets a same-turn disconnect invalidate connect before transport admission', async () => { - const target: SshTarget = { - id: 'ssh-1', - label: 'Server', - host: 'example.com', - port: 22, - username: 'deploy' - } - mockSshStore.getTarget.mockReturnValue(target) - mockConnectionManager.connect.mockResolvedValue({}) - mockConnectionManager.disconnect.mockResolvedValue(undefined) - - const connect = handlers.get('ssh:connect')!(null, { - targetId: 'ssh-1' - }) as Promise - const disconnect = handlers.get('ssh:disconnect')!(null, { - targetId: 'ssh-1' - }) as Promise - - await disconnect - await expect(connect).rejects.toThrow('SSH connection attempt was cancelled') - expect(mockConnectionManager.connect).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ipc/usage-provider-handlers-readiness.test.ts b/src/main/ipc/usage-provider-handlers-readiness.test.ts deleted file mode 100644 index 50a02a8c425..00000000000 --- a/src/main/ipc/usage-provider-handlers-readiness.test.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { ClaudeUsagePersistedState } from '../claude-usage/types' -import type { UsageCacheSplitResult } from '../usage/usage-source-cache-file' - -const { handlers, getPathMock } = vi.hoisted(() => ({ - handlers: new Map unknown>(), - getPathMock: vi.fn<() => string>() -})) - -vi.mock('electron', () => ({ - app: { getPath: getPathMock }, - ipcMain: { - handle: (channel: string, handler: (event: unknown, args?: unknown) => unknown) => { - handlers.set(channel, handler) - } - } -})) - -vi.mock('../usage/usage-scan-worker-spawn', () => ({ - scanClaudeUsageFilesViaWorker: vi.fn(), - scanCodexUsageFilesViaWorker: vi.fn(), - scanOpenCodeUsageDatabasesViaWorker: vi.fn(), - scanMuseUsageFilesViaWorker: vi.fn(), - splitUsageCacheFileViaWorker: vi.fn() -})) - -import { ClaudeUsageStore, initClaudeUsagePath } from '../claude-usage/store' -import { CodexUsageStore, initCodexUsagePath } from '../codex-usage/store' -import { OpenCodeUsageStore, initOpenCodeUsagePath } from '../opencode-usage/store' -import { MuseUsageStore, initMuseUsagePath } from '../muse-usage/store' -import { - scanClaudeUsageFilesViaWorker, - splitUsageCacheFileViaWorker -} from '../usage/usage-scan-worker-spawn' -import { registerUsageProviderHandlers } from './usage-provider-handlers' - -let directory: string -let stores: { flush: () => Promise }[] -let releasePending: (() => void)[] - -function historicalState(): ClaudeUsagePersistedState { - return { - schemaVersion: 6, - worktreeFingerprint: null, - processedFiles: [], - sessions: [], - dailyAggregates: [ - { - day: '2026-10-09', - model: null, - projectKey: 'unscoped', - projectLabel: 'Unknown location', - repoId: null, - worktreeId: null, - turnCount: 1, - zeroCacheReadTurnCount: 1, - inputTokens: 7, - outputTokens: 2, - cacheReadTokens: 0, - cacheWriteTokens: 0, - cacheWrite1hTokens: 0 - } - ], - scanState: { - enabled: false, - lastScanStartedAt: null, - lastScanCompletedAt: 1, - lastScanError: null - } - } -} - -function createProviders(): Parameters[0] { - const backingStore = { getRepos: () => [], getAllWorktreeMeta: () => ({}) } - const providers = { - claudeUsage: new ClaudeUsageStore(backingStore), - codexUsage: new CodexUsageStore(backingStore), - openCodeUsage: new OpenCodeUsageStore(backingStore), - museUsage: new MuseUsageStore(backingStore) - } - stores.push(...Object.values(providers)) - registerUsageProviderHandlers(providers) - return providers -} - -function reportText(state: ClaudeUsagePersistedState): string { - const { processedFiles: _files, ...report } = state - return JSON.stringify(report) -} - -function invoke(channel: string, args?: unknown): unknown { - const handler = handlers.get(channel) - if (!handler) { - throw new Error(`No registered usage handler for ${channel}.`) - } - return handler({}, args) -} - -function nextTurn(): Promise { - return new Promise((resolve) => setImmediate(resolve)) -} - -beforeEach(() => { - directory = mkdtempSync(join(tmpdir(), 'orca-usage-ipc-readiness-')) - stores = [] - releasePending = [] - handlers.clear() - getPathMock.mockReturnValue(directory) - vi.mocked(scanClaudeUsageFilesViaWorker).mockReset() - vi.mocked(splitUsageCacheFileViaWorker).mockReset() - initClaudeUsagePath() - initCodexUsagePath() - initOpenCodeUsagePath() - initMuseUsagePath() -}) - -afterEach(async () => { - releasePending.forEach((release) => release()) - await Promise.all(stores.map((store) => store.flush())) - rmSync(directory, { recursive: true, force: true }) - vi.restoreAllMocks() -}) - -it('awaits loading before the first disabled cached snapshot and all historical queries', async () => { - const cached = historicalState() - writeFileSync( - join(directory, 'orca-claude-usage.json'), - `${JSON.stringify(cached)}${' '.repeat(9 * 1024 * 1024)}` - ) - const pending = Promise.withResolvers() - releasePending.push(() => pending.resolve({ reportText: reportText(cached), migrated: false })) - vi.mocked(splitUsageCacheFileViaWorker).mockReturnValueOnce(pending.promise) - const { claudeUsage } = createProviders() - const snapshotGetter = vi.spyOn(claudeUsage, 'getSnapshot') - const scanStateGetter = vi.spyOn(claudeUsage, 'getScanState') - const settled = vi.fn() - const args = { scope: 'all', range: 'all', limit: 7, kind: 'model' } - const requests = [ - 'getSnapshot', - 'getScanState', - 'getSummary', - 'getDaily', - 'getBreakdown', - 'getRecentSessions' - ].map((query) => - Promise.resolve(invoke(`claudeUsage:${query}`, args)).then((value) => { - settled() - return value - }) - ) - await nextTurn() - expect(settled).not.toHaveBeenCalled() - expect(snapshotGetter).not.toHaveBeenCalled() - expect(scanStateGetter).not.toHaveBeenCalled() - expect(scanClaudeUsageFilesViaWorker).not.toHaveBeenCalled() - pending.resolve({ reportText: reportText(cached), migrated: false }) - const [snapshot, scanState, summary, daily] = await Promise.all(requests) - expect(snapshot).toMatchObject({ - scanState: { enabled: false, isScanning: false, hasAnyClaudeData: true }, - summary: { turns: 1, inputTokens: 7 } - }) - expect(scanState).toMatchObject({ enabled: false, isScanning: false, hasAnyClaudeData: true }) - expect(summary).toMatchObject({ turns: 1, inputTokens: 7 }) - expect(daily).toEqual([ - { day: '2026-10-09', inputTokens: 7, outputTokens: 2, cacheReadTokens: 0, cacheWriteTokens: 0 } - ]) - expect(snapshotGetter).toHaveBeenCalledWith('all', 'all', 7) - expect(scanClaudeUsageFilesViaWorker).not.toHaveBeenCalled() -}) diff --git a/src/main/ipc/wsl/wsl-drive-unc-conversion-handlers.ts b/src/main/ipc/wsl/wsl-drive-unc-conversion-handlers.ts index 7bfa33fd3c4..bcc3113b0d6 100644 --- a/src/main/ipc/wsl/wsl-drive-unc-conversion-handlers.ts +++ b/src/main/ipc/wsl/wsl-drive-unc-conversion-handlers.ts @@ -11,7 +11,7 @@ import type { } from '../../../shared/wsl-drive-unc-conversion-types' import { relaunchApp } from '../../startup/quit/app-relaunch' import { gitExecFileAsync } from '../../git/command-runner/git-exec-file' -import { readProfileProjectTransferState } from '../../orca-profiles/profile-project-domain-state' +import { readProfileProjectTransferState } from '../../orca-profiles/project-transfer/profile-project-domain-state' import { getOrcaProfileListState } from '../../orca-profiles/profile-index-store' import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths' import type { Store } from '../../persistence/loading-store/store' diff --git a/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts b/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts index 0a0886b8a34..8649ae59125 100644 --- a/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts +++ b/src/main/ipc/wsl/wsl-host-handlers-user-actions.test.ts @@ -81,8 +81,7 @@ function register(): void { } describe('WSL host IPC: the user Add and Remove (D3a)', () => { - // Removes are reported by the host service itself (see wsl-host-service.test.ts), so both the - // sidebar and Settings paths count; here the service is mocked and only the Add is the IPC's. + // The service is mocked; only Add reporting belongs to these IPC cases. afterEach(() => { vi.unstubAllEnvs() service.add.mockClear() diff --git a/src/main/linear/issue-relation-write.test.ts b/src/main/linear/issue-relation-write.test.ts deleted file mode 100644 index 9eb2ba48ae5..00000000000 --- a/src/main/linear/issue-relation-write.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -const { rawRequest } = vi.hoisted(() => ({ rawRequest: vi.fn() })) - -vi.mock('./linear-request-concurrency', () => ({ - acquire: vi.fn().mockResolvedValue(undefined), - release: vi.fn() -})) - -vi.mock('./linear-token-store', () => ({ - clearToken: vi.fn() -})) - -vi.mock('./client', () => ({ - getClients: () => [{ workspace: { id: 'workspace-1' }, client: { client: { rawRequest } } }], - isAuthError: () => false -})) - -import { writeIssueRelation } from './issue-relation-write' - -describe('writeIssueRelation', () => { - it('does not create a relation when the duplicate lookup omits pageInfo', async () => { - rawRequest.mockImplementation(async (query: string) => - query.includes('issueRelationCreate') - ? { - data: { - issueRelationCreate: { - success: true, - issueRelation: { - id: 'rel-new', - type: 'blocks', - issue: { id: 'issue-1' }, - relatedIssue: { id: 'issue-2' } - } - } - } - } - : { data: { issue: { relations: { nodes: [] } } } } - ) - const issue = { id: 'issue-1', identifier: 'LIN-1', title: 'One', url: 'https://x/1' } - const relatedIssue = { id: 'issue-2', identifier: 'LIN-2', title: 'Two', url: 'https://x/2' } - - await expect( - writeIssueRelation({ - issue, - relatedIssue, - relationship: 'blocks', - operation: 'add', - workspaceId: 'workspace-1' - }) - ).rejects.toMatchObject({ code: 'linear_partial' }) - expect(rawRequest).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/managed-server/install/orcad-remote-primitives.test.ts b/src/main/managed-server/install/orcad-remote-primitives.test.ts deleted file mode 100644 index 3bd4bebda74..00000000000 --- a/src/main/managed-server/install/orcad-remote-primitives.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type * as ExecCommandModule from '../../ssh/remote-exec/remote-exec-command' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => ({ - ...(await importOriginal()), - execCommand: vi.fn(), - isUnconfirmedSshCommandTermination: (error: unknown) => - error instanceof Error && error.message === 'channel lost' -})) - -vi.mock('../../ssh/remote-host/ssh-remote-platform-detection', () => ({ - detectRemoteHostPlatform: vi.fn() -})) -vi.mock('../host-state/orcad-windows-host-preparation', () => ({ - prepareWindowsOrcadHost: vi.fn() -})) - -import { execCommand } from '../../ssh/remote-exec/remote-exec-command' -import { getRemoteHostPlatform } from '../../ssh/remote-host/ssh-remote-platform' -import { parseOrcadReadinessOutput } from './orcad-remote-launch' - -const mockExec = vi.mocked(execCommand) -getRemoteHostPlatform('linux-x64') -getRemoteHostPlatform('win32-x64') -Object.create(null) - -beforeEach(() => { - mockExec.mockReset() -}) - -describe('readiness parsing bounds', () => { - it('waits on a half-written last line but rejects a finished invalid one', () => { - expect(parseOrcadReadinessOutput('{"type":"orca_ser')).toEqual({ state: 'pending' }) - expect(parseOrcadReadinessOutput('{"type":"orca_ser\n')).toMatchObject({ - state: 'malformed' - }) - }) -}) diff --git a/src/main/muse-usage/muse-usage-provider.ts b/src/main/muse-usage/muse-usage-provider.ts index f314dd6a070..04c08057e65 100644 --- a/src/main/muse-usage/muse-usage-provider.ts +++ b/src/main/muse-usage/muse-usage-provider.ts @@ -1,5 +1,5 @@ -import type { UsageProvider } from '../usage/usage-provider-contract' -import { scanMuseUsageFilesViaWorker } from '../usage/usage-scan-worker-spawn' +import type { UsageProvider } from '../usage/provider-lifecycle/usage-provider-contract' +import { scanMuseUsageFilesViaWorker } from '../usage/scan-worker/usage-scan-worker-spawn' import type { MuseUsageDailyAggregate, MuseUsageSession } from './types' // Event-key ordinals require invalidating older caches. diff --git a/src/main/muse-usage/muse-usage-record-parser.ts b/src/main/muse-usage/muse-usage-record-parser.ts index 687ab69a46f..15d3bcb80a3 100644 --- a/src/main/muse-usage/muse-usage-record-parser.ts +++ b/src/main/muse-usage/muse-usage-record-parser.ts @@ -1,6 +1,6 @@ import { record, type JsonRecord } from '../../shared/codex-rollout-jsonl-cursor' import { unwrapMuseLogRecords } from '../../shared/muse-session-log' -import { ensureNumber, extractString } from '../usage/usage-record-coercion' +import { ensureNumber, extractString } from '../usage/source-input/usage-record-coercion' import type { MuseUsageParsedEvent } from './types' export type MuseUsageParseContext = { diff --git a/src/main/muse-usage/scanner.ts b/src/main/muse-usage/scanner.ts index 7418b462b78..fb89c0b10c1 100644 --- a/src/main/muse-usage/scanner.ts +++ b/src/main/muse-usage/scanner.ts @@ -1,12 +1,12 @@ import { stat } from 'node:fs/promises' -import { attributeUsageEvent } from '../usage/usage-event-attribution' -import { createUsageEventAggregation } from '../usage/usage-event-aggregation' -import { readJsonlLinesFromOffset } from '../usage/jsonl-line-offsets' -import type { UsageScanWorktreeRef } from '../usage/usage-provider-contract' +import { attributeUsageEvent } from '../usage/worktree-attribution/usage-event-attribution' +import { createUsageEventAggregation } from '../usage/rollups/usage-event-aggregation' +import { readJsonlLinesFromOffset } from '../usage/source-input/jsonl/jsonl-line-offsets' +import type { UsageScanWorktreeRef } from '../usage/provider-lifecycle/usage-provider-contract' import { createUsageWorktreeResolver, type UsageWorktreeResolver -} from '../usage/usage-worktree-resolver' +} from '../usage/worktree-attribution/usage-worktree-resolver' import { listMuseSessionLogFiles, type MuseSessionLogRef } from './muse-session-log-discovery' import { parseMuseUsageLine, type MuseUsageParseContext } from './muse-usage-record-parser' import type { diff --git a/src/main/muse-usage/snapshot-rollups.ts b/src/main/muse-usage/snapshot-rollups.ts index 11794cb3779..f35cb30e9c1 100644 --- a/src/main/muse-usage/snapshot-rollups.ts +++ b/src/main/muse-usage/snapshot-rollups.ts @@ -1,4 +1,4 @@ -import { highestUsageKey } from '../usage/highest-usage-key' +import { highestUsageKey } from '../usage/rollups/highest-usage-key' import type { MuseUsageBreakdownKind, MuseUsageBreakdownRow, diff --git a/src/main/muse-usage/store.ts b/src/main/muse-usage/store.ts index 82207b0e367..da2ab662aff 100644 --- a/src/main/muse-usage/store.ts +++ b/src/main/muse-usage/store.ts @@ -11,9 +11,12 @@ import type { MuseUsageSummary } from '../../shared/muse-usage-types' import type { Store } from '../persistence/loading-store/store' -import { UsageProviderStoreLifecycle } from '../usage/usage-provider-store-lifecycle' -import { splitUsageCacheFileViaWorker } from '../usage/usage-scan-worker-spawn' -import { filterUsageDaily, filterUsageSessions } from '../usage/usage-scope-filters' +import { UsageProviderStoreLifecycle } from '../usage/provider-lifecycle/usage-provider-store-lifecycle' +import { splitUsageCacheFileViaWorker } from '../usage/scan-worker/usage-scan-worker-spawn' +import { + filterUsageDaily, + filterUsageSessions +} from '../usage/reporting/range-query/usage-scope-filters' import { museUsageProvider } from './muse-usage-provider' import { getDefaultMuseUsageState, normalizeMuseUsageState } from './persisted-state-normalization' import { diff --git a/src/main/muse-usage/types.ts b/src/main/muse-usage/types.ts index 8d9e3956253..dac2a88bdcd 100644 --- a/src/main/muse-usage/types.ts +++ b/src/main/muse-usage/types.ts @@ -4,7 +4,7 @@ import type { UsageLocationModelBreakdown, UsageModelBreakdown, UsageSession -} from '../usage/usage-rollup-records' +} from '../usage/rollups/usage-rollup-records' // Muse supplies no prices for rollups. export type MuseUsageMetric = Record diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-persistence.test.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-persistence.test.ts deleted file mode 100644 index b53123fa52e..00000000000 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-persistence.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it } from 'vitest' -import { createAgentModelCatalogFilePersistence } from './agent-model-catalog-persistence' -import { AgentModelCatalogStore } from './agent-model-catalog-store' - -const directories: string[] = [] -afterEach(() => { - for (const directory of directories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } -}) - -it("imports an older build's catalog file once and keeps later listings", async () => { - const directory = mkdtempSync(join(tmpdir(), 'orca-model-catalog-')) - directories.push(directory) - const legacyPath = join(directory, 'agent-model-catalog.json') - writeFileSync( - legacyPath, - JSON.stringify({ - version: 3, - entries: [ - { - agent: 'grok', - fingerprint: 'fp', - discovered: { - origin: 'probe', - at: 1, - models: [{ id: 'A', label: 'A', efforts: [], isDefault: true }] - }, - live: null - } - ] - }) - ) - const store = new AgentModelCatalogStore() - await store.attachPersistence(createAgentModelCatalogFilePersistence(directory)) - expect(store.get('fp')?.models[0]?.id).toBe('A') - expect(existsSync(legacyPath)).toBe(false) - - store.recordSuccess( - 'fp', - 'grok', - { origin: 'probe', models: [{ id: 'B', label: 'B', efforts: [], isDefault: true }] }, - 'discovery' - ) - await store.flushPersistence() - - const restarted = await createAgentModelCatalogFilePersistence(directory).load() - expect(restarted.map((entry) => entry.models[0]?.id)).toEqual(['B']) -}) diff --git a/src/main/native-chat/agent-session-journal/queued-messages/queued-message-context-clear.test.ts b/src/main/native-chat/agent-session-journal/queued-messages/queued-message-context-clear.test.ts index e4b37d386ca..c5ad225dbe9 100644 --- a/src/main/native-chat/agent-session-journal/queued-messages/queued-message-context-clear.test.ts +++ b/src/main/native-chat/agent-session-journal/queued-messages/queued-message-context-clear.test.ts @@ -1,10 +1,5 @@ import { describe, expect, it } from 'vitest' -import { - deriveQueuePauses, - journalQueuePauseRestatement, - queuePauseHolding, - nextSendableQueuedCard -} from './queued-message-pause' +import { deriveQueuePauses, journalQueuePauseRestatement } from './queued-message-pause' import { createJournalQueuePauseMarks } from './queued-message-pause-marks' const card = (messageId: string) => ({ @@ -27,18 +22,6 @@ const pauses = (cards = [card('before-one'), card('before-two')], m = marks(), a }) describe('exact waiting-card membership after context clear', () => { - it('holds only recorded waiting IDs and intersects them with cards still waiting', () => { - const after = card('after') - const current = [card('before-two'), after] - const held = pauses(current) - expect(held).toEqual([ - { reason: 'cleared', since: { epoch: 'epoch', sequence: 5 }, messageIds: ['before-two'] } - ]) - expect(queuePauseHolding(held, after)).toBeUndefined() - expect(pauses([after])).toEqual([]) - expect(nextSendableQueuedCard(pauses([after]), [after])).toEqual(after) - }) - it('restates an explicit lift when rewind retires the accepted turn', () => { const prior = marks() const cards = [card('before-one'), card('before-two')] diff --git a/src/main/native-chat/transcript-zstd-decompression.test.ts b/src/main/native-chat/transcript-zstd-decompression.test.ts new file mode 100644 index 00000000000..8242eb6112e --- /dev/null +++ b/src/main/native-chat/transcript-zstd-decompression.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest' +import { Readable } from 'node:stream' +import { randomBytes } from 'node:crypto' +import { zstdCompressSync } from 'node:zlib' +import { readZstdTranscriptSlice, zstdTranscriptStream } from './transcript-zstd-decompression' + +describe('zstdTranscriptStream', () => { + it('closes the raw stream when the decoded stream stops before EOF', async () => { + const compressed = zstdCompressSync(randomBytes(1024 * 1024)) + async function* rawChunks(): AsyncGenerator { + for (let offset = 0; offset < compressed.length; offset += 16 * 1024) { + yield compressed.subarray(offset, offset + 16 * 1024) + } + } + const raw = Readable.from(rawChunks()) + const decoded = zstdTranscriptStream(raw) + + const head = await readZstdTranscriptSlice(decoded, 64 * 1024) + + expect(head.length).toBe(64 * 1024) + await new Promise((resolve) => setImmediate(resolve)) + expect(raw.destroyed).toBe(true) + }) +}) diff --git a/src/main/native-chat/transcript-zstd-decompression.ts b/src/main/native-chat/transcript-zstd-decompression.ts new file mode 100644 index 00000000000..4e34d42f9de --- /dev/null +++ b/src/main/native-chat/transcript-zstd-decompression.ts @@ -0,0 +1,29 @@ +import { pipeline, type Readable } from 'node:stream' +import { createZstdDecompress } from 'node:zlib' + +export function isZstdTranscriptPath(path: string): boolean { + return path.endsWith('.zst') +} + +/** Pipes raw compressed bytes through the zstd decoder; errors on the raw stream surface on the output. */ +export function zstdTranscriptStream(raw: Readable): Readable { + const decoder = createZstdDecompress() + // pipeline links lifetimes so an early close of the decoded stream releases the raw stream's fd. + pipeline(raw, decoder, () => undefined) + return decoder +} + +/** Collects at most `length` decompressed bytes; compressed transcripts are small enough to keep in memory. */ +export async function readZstdTranscriptSlice(stream: Readable, length: number): Promise { + const parts: Buffer[] = [] + let total = 0 + for await (const chunk of stream) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) + parts.push(buffer) + total += buffer.length + if (total >= length) { + break + } + } + return Buffer.concat(parts).subarray(0, Math.min(total, length)) +} diff --git a/src/main/opencode-usage/opencode-usage-provider.ts b/src/main/opencode-usage/opencode-usage-provider.ts index f9d1ce68e5a..1911b5c5623 100644 --- a/src/main/opencode-usage/opencode-usage-provider.ts +++ b/src/main/opencode-usage/opencode-usage-provider.ts @@ -1,5 +1,5 @@ -import type { UsageProvider } from '../usage/usage-provider-contract' -import { scanOpenCodeUsageDatabasesViaWorker } from '../usage/usage-scan-worker-spawn' +import type { UsageProvider } from '../usage/provider-lifecycle/usage-provider-contract' +import { scanOpenCodeUsageDatabasesViaWorker } from '../usage/scan-worker/usage-scan-worker-spawn' import type { OpenCodeUsageDailyAggregate, OpenCodeUsageSession } from './types' // Invalidate older caches: merge migrated rows per column, normalize input and preserve cache writes. diff --git a/src/main/opencode-usage/opencode-usage-row-parsing.ts b/src/main/opencode-usage/opencode-usage-row-parsing.ts index 504a15efd63..b254787f582 100644 --- a/src/main/opencode-usage/opencode-usage-row-parsing.ts +++ b/src/main/opencode-usage/opencode-usage-row-parsing.ts @@ -1,4 +1,4 @@ -import { ensureNumber, extractString } from '../usage/usage-record-coercion' +import { ensureNumber, extractString } from '../usage/source-input/usage-record-coercion' import type { OpenCodeUsageRow } from './opencode-usage-row-queries' import type { OpenCodeUsageParsedEvent } from './types' diff --git a/src/main/opencode-usage/opencode-usage-worktree-attribution.ts b/src/main/opencode-usage/opencode-usage-worktree-attribution.ts index 3f236ccc1d2..ef4265478be 100644 --- a/src/main/opencode-usage/opencode-usage-worktree-attribution.ts +++ b/src/main/opencode-usage/opencode-usage-worktree-attribution.ts @@ -1,6 +1,6 @@ -import { normalizeComparablePath } from '../usage/usage-path-comparison' -import type { UsageScanWorktreeRef } from '../usage/usage-provider-contract' -import type { UsageWorktreeResolver } from '../usage/usage-worktree-resolver' +import { normalizeComparablePath } from '../usage/worktree-attribution/usage-path-comparison' +import type { UsageScanWorktreeRef } from '../usage/provider-lifecycle/usage-provider-contract' +import type { UsageWorktreeResolver } from '../usage/worktree-attribution/usage-worktree-resolver' import type { OpenCodeUsageAttributedEvent, OpenCodeUsageParsedEvent } from './types' export type OpenCodeUsageWorktreeRef = UsageScanWorktreeRef diff --git a/src/main/opencode-usage/scanner.ts b/src/main/opencode-usage/scanner.ts index 4748ab61d2a..1fefb4f279a 100644 --- a/src/main/opencode-usage/scanner.ts +++ b/src/main/opencode-usage/scanner.ts @@ -1,10 +1,10 @@ import { yieldToEventLoop } from '../../shared/event-loop-yield' import Database from '../sqlite/sync-database' -import { createUsageEventAggregation } from '../usage/usage-event-aggregation' +import { createUsageEventAggregation } from '../usage/rollups/usage-event-aggregation' import { createUsageWorktreeResolver, type UsageWorktreeResolver -} from '../usage/usage-worktree-resolver' +} from '../usage/worktree-attribution/usage-worktree-resolver' import { compareOpenCodeClaimPriority, getProcessedDatabaseInfo, diff --git a/src/main/opencode-usage/scope-range-filter.ts b/src/main/opencode-usage/scope-range-filter.ts index 5c9fe6db2f0..d851c37d155 100644 --- a/src/main/opencode-usage/scope-range-filter.ts +++ b/src/main/opencode-usage/scope-range-filter.ts @@ -1,6 +1,9 @@ import type { OpenCodeUsageRange, OpenCodeUsageScope } from '../../shared/opencode-usage-types' import type { OpenCodeUsageDailyAggregate, OpenCodeUsageSession } from './types' -import { getLocalUsageDay, getUsageRangeCutoff } from '../usage/usage-calendar-range' +import { + getLocalUsageDay, + getUsageRangeCutoff +} from '../usage/reporting/range-query/usage-calendar-range' export function filterDailyAggregatesByScopeAndRange( dailyAggregates: OpenCodeUsageDailyAggregate[], diff --git a/src/main/opencode-usage/snapshot-rollups.ts b/src/main/opencode-usage/snapshot-rollups.ts index 84e91d7ae78..065704479ad 100644 --- a/src/main/opencode-usage/snapshot-rollups.ts +++ b/src/main/opencode-usage/snapshot-rollups.ts @@ -1,4 +1,4 @@ -import { highestUsageKey } from '../usage/highest-usage-key' +import { highestUsageKey } from '../usage/rollups/highest-usage-key' import type { OpenCodeUsageBreakdownKind, OpenCodeUsageBreakdownRow, diff --git a/src/main/opencode-usage/store.ts b/src/main/opencode-usage/store.ts index dee4c5b3eb6..790c6d9325b 100644 --- a/src/main/opencode-usage/store.ts +++ b/src/main/opencode-usage/store.ts @@ -1,4 +1,4 @@ -import { codexOpenCodeTokenSessions } from '../usage/agent-token-usage' +import { codexOpenCodeTokenSessions } from '../usage/reporting/token-usage/agent-token-usage' import { app } from 'electron' import { join } from 'node:path' import type { @@ -29,8 +29,8 @@ import { buildOpenCodeUsageRecentSessions, buildOpenCodeUsageSummary } from './snapshot-rollups' -import { UsageProviderStoreLifecycle } from '../usage/usage-provider-store-lifecycle' -import { splitUsageCacheFileViaWorker } from '../usage/usage-scan-worker-spawn' +import { UsageProviderStoreLifecycle } from '../usage/provider-lifecycle/usage-provider-store-lifecycle' +import { splitUsageCacheFileViaWorker } from '../usage/scan-worker/usage-scan-worker-spawn' let _openCodeUsageFile: string | null = null diff --git a/src/main/orca-profiles/other-profile-workspace-catalog.test.ts b/src/main/orca-profiles/catalog/other-profile-workspace-catalog.test.ts similarity index 57% rename from src/main/orca-profiles/other-profile-workspace-catalog.test.ts rename to src/main/orca-profiles/catalog/other-profile-workspace-catalog.test.ts index 6cf2e3ff194..117c79f6634 100644 --- a/src/main/orca-profiles/other-profile-workspace-catalog.test.ts +++ b/src/main/orca-profiles/catalog/other-profile-workspace-catalog.test.ts @@ -1,11 +1,11 @@ -import { existsSync, mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'node:fs' +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { folderWorkspaceKey } from '../../shared/workspace-scope' -import { importProfileStateJson } from '../persistence/profile-state/profile-state-documents' -import { openProfileStateDatabase } from '../persistence/profile-state/profile-state-database' -import { getOrcaProfileStateDatabaseFile } from './profile-storage-paths' +import '../../../shared/workspace-scope' +import '../../persistence/profile-state/profile-state-documents' +import { openProfileStateDatabase } from '../../persistence/profile-state/profile-state-database' +import { getOrcaProfileStateDatabaseFile } from '../profile-storage-paths' import { getOtherProfileWorktreeIdsForHistoryGc } from './other-profile-workspace-catalog' const roots: string[] = [] @@ -55,62 +55,6 @@ function userDataWithProfiles( describe('getOtherProfileWorktreeIdsForHistoryGc', () => { // The live Store owns active-profile IDs; rereading its file could race writes. - it('prefers the profile database over a stale JSON export', () => { - const root = userDataWithProfiles('active', [ - { id: 'active', state: {} }, - { - id: 'other', - state: { worktreeMeta: { 'repo::/json': {} }, folderWorkspaces: [] } - } - ]) - const database = openProfileStateDatabase( - getOrcaProfileStateDatabaseFile('other', root), - 'other' - ) - try { - importProfileStateJson( - database.db, - JSON.stringify({ - worktreeMeta: { 'repo::/database': {} }, - folderWorkspaces: [{ id: 'folder-database' }] - }) - ) - } finally { - database.db.close() - } - - expect(getOtherProfileWorktreeIdsForHistoryGc(root)).toEqual({ - unreadableProfiles: 0, - ids: new Set(['repo::/database', folderWorkspaceKey('folder-database')]) - }) - }) - - it.each([true, false])( - 'refuses history pruning when SQLite is missing but a retained export exists (JSON: %s)', - (hasJson) => { - const state = { worktreeMeta: { 'repo::/stale-json': {} } } - const root = userDataWithProfiles('active', [ - { id: 'active', state: {} }, - { id: 'other', ...(hasJson ? { state } : {}) } - ]) - const dataFile = join(root, 'profiles', 'other', 'orca-data.json') - const exportPath = `${dataFile}.sqlite-export.1.json` - const exportJson = JSON.stringify({ worktreeMeta: { 'repo::/export': {} } }) - writeFileSync(exportPath, exportJson) - - expect(getOtherProfileWorktreeIdsForHistoryGc(root)).toEqual({ - unreadableProfiles: 1, - ids: new Set() - }) - expect(existsSync(getOrcaProfileStateDatabaseFile('other', root))).toBe(false) - expect(existsSync(dataFile)).toBe(hasJson) - if (hasJson) { - expect(readFileSync(dataFile, 'utf8')).toBe(JSON.stringify(state)) - } - expect(readFileSync(exportPath, 'utf8')).toBe(exportJson) - } - ) - it('does not fall back to JSON when an existing database is corrupt', () => { const root = userDataWithProfiles('active', [ { id: 'active', state: {} }, diff --git a/src/main/orca-profiles/other-profile-workspace-catalog.ts b/src/main/orca-profiles/catalog/other-profile-workspace-catalog.ts similarity index 93% rename from src/main/orca-profiles/other-profile-workspace-catalog.ts rename to src/main/orca-profiles/catalog/other-profile-workspace-catalog.ts index 84329aae2ac..59c99eec49c 100644 --- a/src/main/orca-profiles/other-profile-workspace-catalog.ts +++ b/src/main/orca-profiles/catalog/other-profile-workspace-catalog.ts @@ -1,13 +1,14 @@ import { lstatSync, readFileSync } from 'node:fs' -import { folderWorkspaceKey } from '../../shared/workspace-scope' +import { folderWorkspaceKey } from '../../../shared/workspace-scope' import { getOrcaProfileDataFile, getOrcaProfileStateDatabaseFile, - getProfileUserDataPath -} from './profile-storage-paths' -import { getOrcaProfileIndexPath, readProfileIndex } from './profile-index-store' -import { readProfileStateDomains } from '../persistence/profile-state/profile-state-domain-reader' -import { assertNoRetainedProfileStateExports } from '../persistence/profile-state/profile-state-recovery-required' + getProfileUserDataPath, + getOrcaProfileIndexPath +} from '../profile-storage-paths' +import { readProfileIndex } from '../profile-index-store' +import { readProfileStateDomains } from '../../persistence/profile-state/profile-state-domain-reader' +import { assertNoRetainedProfileStateExports } from '../../persistence/profile-state/profile-state-recovery-required' /** Histories lack profile segments, so include inactive profiles before GC. * Read persisted IDs without Store migrations; unreadable profiles must prevent pruning. */ diff --git a/src/main/orca-profiles/profile-project-presence.ts b/src/main/orca-profiles/catalog/profile-project-presence.ts similarity index 83% rename from src/main/orca-profiles/profile-project-presence.ts rename to src/main/orca-profiles/catalog/profile-project-presence.ts index 23f54884dee..0ecead33774 100644 --- a/src/main/orca-profiles/profile-project-presence.ts +++ b/src/main/orca-profiles/catalog/profile-project-presence.ts @@ -1,10 +1,10 @@ import type { FindOrcaProfileProjectsByPathArgs, FindOrcaProfileProjectsByPathResult -} from '../../shared/orca-profiles' -import { getOrcaProfileListState } from './profile-index-store' -import { readProfileState } from './profile-project-state-file' -import { repoPhysicalKey } from './profile-project-worktree-identity' +} from '../../../shared/orca-profiles' +import { getOrcaProfileListState } from '../profile-index-store' +import { readProfileState } from '../project-transfer/profile-project-state-file' +import { repoPhysicalKey } from '../project-transfer/profile-project-worktree-identity' function cleanOptionalString(value: string | null | undefined): string | null { const trimmed = value?.trim() diff --git a/src/main/orca-profiles/profile-artifact-cloud-cleanup.test.ts b/src/main/orca-profiles/cloud-auth/profile-artifact-cloud-cleanup.test.ts similarity index 85% rename from src/main/orca-profiles/profile-artifact-cloud-cleanup.test.ts rename to src/main/orca-profiles/cloud-auth/profile-artifact-cloud-cleanup.test.ts index e054a15675c..5c9d1860bb2 100644 --- a/src/main/orca-profiles/profile-artifact-cloud-cleanup.test.ts +++ b/src/main/orca-profiles/cloud-auth/profile-artifact-cloud-cleanup.test.ts @@ -2,19 +2,19 @@ import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { OrcaProfileCloudSummary } from '../../shared/orca-profiles' -import type * as ArtifactCreateIntentStore from '../artifacts/artifact-create-intent-store' -import type * as ProfileIndexStore from './profile-index-store' +import type { OrcaProfileCloudSummary } from '../../../shared/orca-profiles' +import type * as ArtifactCreateIntentStore from '../../artifacts/artifact-create-intent-store' +import type * as ProfileIndexStore from '../profile-index-store' -vi.mock('../artifacts/artifact-create-intent-store', async () => { +vi.mock('../../artifacts/artifact-create-intent-store', async () => { const actual = await vi.importActual( - '../artifacts/artifact-create-intent-store' + '../../artifacts/artifact-create-intent-store' ) return { ...actual, clearArtifactCreateIntents: vi.fn(actual.clearArtifactCreateIntents) } }) -vi.mock('./profile-index-store', async () => { - const actual = await vi.importActual('./profile-index-store') +vi.mock('../profile-index-store', async () => { + const actual = await vi.importActual('../profile-index-store') return { ...actual, writeProfileIndex: vi.fn(actual.writeProfileIndex) } }) @@ -22,16 +22,16 @@ import { clearArtifactCreateIntents, getArtifactCreateIntent, getOrCreateArtifactCreateIntent -} from '../artifacts/artifact-create-intent-store' -import type { ArtifactShareScope } from '../artifacts/artifact-share-record-store' +} from '../../artifacts/artifact-create-intent-store' +import type { ArtifactShareScope } from '../../artifacts/artifact-share-record-store' import { linkOrcaProfileToCloud } from './profile-cloud-index' import { - getOrcaProfileIndexPath, loadOrCreateProfileIndex, readProfileIndex, writeProfileIndex -} from './profile-index-store' +} from '../profile-index-store' +import { getOrcaProfileIndexPath } from '../profile-storage-paths' const createdPaths: string[] = [] const profileId = 'local-default' diff --git a/src/main/orca-profiles/profile-artifact-cloud-cleanup.ts b/src/main/orca-profiles/cloud-auth/profile-artifact-cloud-cleanup.ts similarity index 92% rename from src/main/orca-profiles/profile-artifact-cloud-cleanup.ts rename to src/main/orca-profiles/cloud-auth/profile-artifact-cloud-cleanup.ts index be71a725984..e616a653968 100644 --- a/src/main/orca-profiles/profile-artifact-cloud-cleanup.ts +++ b/src/main/orca-profiles/cloud-auth/profile-artifact-cloud-cleanup.ts @@ -1,13 +1,13 @@ import { existsSync, readFileSync, rmSync } from 'node:fs' import { join } from 'node:path' -import type { OrcaProfileCloudSummary, OrcaProfileSummary } from '../../shared/orca-profiles' +import type { OrcaProfileCloudSummary, OrcaProfileSummary } from '../../../shared/orca-profiles' import { bestEffortFsyncDirectorySync, writeDurableSecureJsonFile -} from '../../shared/secure-storage/secure-file' -import { clearArtifactCreateIntents } from '../artifacts/artifact-create-intent-store' -import { clearArtifactShareRecords } from '../artifacts/artifact-share-record-store' -import { getOrcaProfileDirectory } from './profile-storage-paths' +} from '../../../shared/secure-storage/secure-file' +import { clearArtifactCreateIntents } from '../../artifacts/artifact-create-intent-store' +import { clearArtifactShareRecords } from '../../artifacts/artifact-share-record-store' +import { getOrcaProfileDirectory } from '../profile-storage-paths' type ArtifactCloudCleanupMarker = { version: 1 diff --git a/src/main/orca-profiles/profile-cloud-auth-config.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-auth-config.ts similarity index 97% rename from src/main/orca-profiles/profile-cloud-auth-config.ts rename to src/main/orca-profiles/cloud-auth/profile-cloud-auth-config.ts index 55fbcc4e350..fc25268707e 100644 --- a/src/main/orca-profiles/profile-cloud-auth-config.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-auth-config.ts @@ -2,8 +2,8 @@ import { app } from 'electron' import { cleanCloudServiceUrl as cleanUrl, cleanCloudServiceOrigin as cleanOrigin -} from '../../shared/cloud-service-url' -import { resolvePushGatewayOrigin } from '../runtime/push/push-gateway-origin' +} from '../../../shared/cloud-service-url' +import { resolvePushGatewayOrigin } from '../../runtime/push/push-gateway-origin' export type OrcaCloudAuthConfig = { apiBaseUrl: string diff --git a/src/main/orca-profiles/profile-cloud-auth-status.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-auth-status.ts similarity index 88% rename from src/main/orca-profiles/profile-cloud-auth-status.ts rename to src/main/orca-profiles/cloud-auth/profile-cloud-auth-status.ts index 89d03e5bc99..1cbbb8e9936 100644 --- a/src/main/orca-profiles/profile-cloud-auth-status.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-auth-status.ts @@ -1,7 +1,7 @@ -import type { OrcaProfileAuthStatus } from '../../shared/orca-profiles' -import type { ActiveOrcaProfileState } from './profile-index-store' +import type { OrcaProfileAuthStatus } from '../../../shared/orca-profiles' +import type { ActiveOrcaProfileState } from '../profile-index-store' import { getOrcaCloudAuthConfig, isOrcaCloudDevAuthEnabled } from './profile-cloud-auth-config' -import { readCloudSession } from './profile-cloud-session-owner' +import { readCloudSession } from '../cloud-session/profile-cloud-session-owner' export function getOrcaProfileAuthStatusFromProfile( active: ActiveOrcaProfileState, diff --git a/src/main/orca-profiles/profile-cloud-callback-page.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-callback-page.ts similarity index 100% rename from src/main/orca-profiles/profile-cloud-callback-page.ts rename to src/main/orca-profiles/cloud-auth/profile-cloud-callback-page.ts diff --git a/src/main/orca-profiles/profile-cloud-capability-refresh.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-capability-refresh.ts similarity index 92% rename from src/main/orca-profiles/profile-cloud-capability-refresh.ts rename to src/main/orca-profiles/cloud-auth/profile-cloud-capability-refresh.ts index 428356c8404..3f21ba08b5e 100644 --- a/src/main/orca-profiles/profile-cloud-capability-refresh.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-capability-refresh.ts @@ -1,15 +1,15 @@ -import type { RefreshCurrentOrcaProfileAuthResult } from '../../shared/orca-profiles' +import type { RefreshCurrentOrcaProfileAuthResult } from '../../../shared/orca-profiles' import { getOrcaCloudAuthConfig, isOrcaCloudDevAuthEnabled } from './profile-cloud-auth-config' import { getOrcaProfileAuthStatusFromProfile } from './profile-cloud-auth-status' import { refreshOrcaCloudCapabilities } from './profile-cloud-client' -import { ensureActiveOrcaProfile } from './profile-index-store' +import { ensureActiveOrcaProfile } from '../profile-index-store' import { refreshDevOrcaCloudProfile } from './profile-cloud-dev-service' import { commitCloudSessionCapabilities, takeCloudSessionTicket, type CloudSessionTicket -} from './profile-cloud-session-owner' -import { runWithFreshOrcaCloudSession } from './profile-cloud-session-refresh' +} from '../cloud-session/profile-cloud-session-owner' +import { runWithFreshOrcaCloudSession } from '../cloud-session/profile-cloud-session-refresh' export async function refreshCurrentOrcaProfileAuth( userDataPath: string diff --git a/src/main/orca-profiles/profile-cloud-client.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-client.ts similarity index 96% rename from src/main/orca-profiles/profile-cloud-client.ts rename to src/main/orca-profiles/cloud-auth/profile-cloud-client.ts index a8835d167ce..86a46fa48d7 100644 --- a/src/main/orca-profiles/profile-cloud-client.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-client.ts @@ -2,11 +2,11 @@ import type { OrcaCloudCapabilities, OrcaCloudOrgSummary, OrcaProfileCloudSummary -} from '../../shared/orca-profiles' +} from '../../../shared/orca-profiles' import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' -import type { OrcaCloudSession } from './profile-cloud-session-store' -import type { OrcaCloudSessionExchangeResponse } from './profile-cloud-session-exchange' -import { cancelUnreadResponseBody } from '../lib/unread-response-body' +import type { OrcaCloudSession } from '../cloud-session/profile-cloud-session-store' +import type { OrcaCloudSessionExchangeResponse } from '../cloud-session/profile-cloud-session-exchange' +import { cancelUnreadResponseBody } from '../../lib/unread-response-body' type ExchangeCodeArgs = { code: string diff --git a/src/main/orca-profiles/profile-cloud-dev-auth.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-dev-auth.ts similarity index 93% rename from src/main/orca-profiles/profile-cloud-dev-auth.ts rename to src/main/orca-profiles/cloud-auth/profile-cloud-dev-auth.ts index 137696e17ce..c78fa932196 100644 --- a/src/main/orca-profiles/profile-cloud-dev-auth.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-dev-auth.ts @@ -1,6 +1,6 @@ import { randomUUID } from 'node:crypto' -import type { OrcaCloudCapabilities, OrcaCloudOrgSummary } from '../../shared/orca-profiles' -import type { OrcaCloudSessionExchangeResponse } from './profile-cloud-session-exchange' +import type { OrcaCloudCapabilities, OrcaCloudOrgSummary } from '../../../shared/orca-profiles' +import type { OrcaCloudSessionExchangeResponse } from '../cloud-session/profile-cloud-session-exchange' const DEV_SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000 diff --git a/src/main/orca-profiles/profile-cloud-dev-service.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-dev-service.ts similarity index 90% rename from src/main/orca-profiles/profile-cloud-dev-service.ts rename to src/main/orca-profiles/cloud-auth/profile-cloud-dev-service.ts index 736e03a5562..595d53b5dbe 100644 --- a/src/main/orca-profiles/profile-cloud-dev-service.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-dev-service.ts @@ -1,14 +1,12 @@ import type { CreateCloudLinkedOrcaProfileArgs, OrcaProfileListState -} from '../../shared/orca-profiles' -import type { ActiveOrcaProfileState } from './profile-index-store' +} from '../../../shared/orca-profiles' +import type { ActiveOrcaProfileState } from '../profile-index-store' import { createCloudLinkedOrcaProfileRecord, linkOrcaProfileToCloud } from './profile-cloud-index' -import { readCloudSession, signInCloudSession } from './profile-cloud-session-owner' +import { readCloudSession, signInCloudSession } from '../cloud-session/profile-cloud-session-owner' import { createDevOrcaCloudSession } from './profile-cloud-dev-auth' -type DevProfileListResult = OrcaProfileListState - type DevCreateProfileResult = | { status: 'created' @@ -19,14 +17,14 @@ type DevCreateProfileResult = type DevMutationResult = | { status: 'updated' - list: DevProfileListResult + list: OrcaProfileListState } | { status: 'reconnect-required' } export function connectDevOrcaCloudProfile( active: ActiveOrcaProfileState, userDataPath: string -): DevProfileListResult { +): OrcaProfileListState { const session = createDevOrcaCloudSession({ localProfileId: active.profile.id }) signInCloudSession(active.profile.id, userDataPath, session) return linkOrcaProfileToCloud(active.profile.id, session.cloud, userDataPath) diff --git a/src/main/orca-profiles/profile-cloud-index.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-index.ts similarity index 96% rename from src/main/orca-profiles/profile-cloud-index.ts rename to src/main/orca-profiles/cloud-auth/profile-cloud-index.ts index ccf7e70adb9..8bf434a320a 100644 --- a/src/main/orca-profiles/profile-cloud-index.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-index.ts @@ -4,13 +4,9 @@ import type { OrcaProfileCloudSummary, OrcaProfileListState, OrcaProfileSummary -} from '../../shared/orca-profiles' -import { - getOrcaProfileDirectory, - getOrcaProfileIndexPath, - loadOrCreateProfileIndex, - writeProfileIndex -} from './profile-index-store' +} from '../../../shared/orca-profiles' +import { loadOrCreateProfileIndex, writeProfileIndex } from '../profile-index-store' +import { getOrcaProfileDirectory, getOrcaProfileIndexPath } from '../profile-storage-paths' import { artifactCloudCleanupNeedsCommit, commitArtifactCloudCleanup, diff --git a/src/main/orca-profiles/profile-cloud-pkce.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-pkce.ts similarity index 100% rename from src/main/orca-profiles/profile-cloud-pkce.ts rename to src/main/orca-profiles/cloud-auth/profile-cloud-pkce.ts diff --git a/src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-service-connect-overlap.test.ts similarity index 99% rename from src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts rename to src/main/orca-profiles/cloud-auth/profile-cloud-service-connect-overlap.test.ts index 04dd63f7e67..1f9db6ecc9e 100644 --- a/src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-service-connect-overlap.test.ts @@ -6,7 +6,7 @@ import type { OrcaCloudCapabilities, OrcaCloudOrgSummary, OrcaProfileCloudSummary -} from '../../shared/orca-profiles' +} from '../../../shared/orca-profiles' const { beginOrcaCloudPkceFlowMock, diff --git a/src/main/orca-profiles/profile-cloud-service-sign-out-connect-race.test.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-service-sign-out-connect-race.test.ts similarity index 99% rename from src/main/orca-profiles/profile-cloud-service-sign-out-connect-race.test.ts rename to src/main/orca-profiles/cloud-auth/profile-cloud-service-sign-out-connect-race.test.ts index 46dfae4fe39..d88825a2b2c 100644 --- a/src/main/orca-profiles/profile-cloud-service-sign-out-connect-race.test.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-service-sign-out-connect-race.test.ts @@ -6,7 +6,7 @@ import type { OrcaCloudCapabilities, OrcaCloudOrgSummary, OrcaProfileCloudSummary -} from '../../shared/orca-profiles' +} from '../../../shared/orca-profiles' const { beginOrcaCloudPkceFlowMock, diff --git a/src/main/orca-profiles/profile-cloud-service.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-service.ts similarity index 86% rename from src/main/orca-profiles/profile-cloud-service.ts rename to src/main/orca-profiles/cloud-auth/profile-cloud-service.ts index 9a355500146..df765279535 100644 --- a/src/main/orca-profiles/profile-cloud-service.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-service.ts @@ -5,15 +5,15 @@ import type { OrcaProfileAuthStatus, SelectOrcaProfileOrgResult, SignOutCurrentOrcaProfileResult -} from '../../shared/orca-profiles' -import { ensureActiveOrcaProfile } from './profile-index-store' +} from '../../../shared/orca-profiles' +import { ensureActiveOrcaProfile } from '../profile-index-store' import { getOrcaCloudAuthConfig, isOrcaCloudDevAuthEnabled } from './profile-cloud-auth-config' import { invalidateCloudSessionChanges, readCloudSession, signInCloudSession, signOutCloudSession -} from './profile-cloud-session-owner' +} from '../cloud-session/profile-cloud-session-owner' import { createOrcaCloudProfile, exchangeOrcaCloudAuthCode, @@ -25,22 +25,22 @@ import { linkOrcaProfileToCloud, unlinkOrcaProfileFromCloud } from './profile-cloud-index' -import { runWithFreshOrcaCloudSession } from './profile-cloud-session-refresh' +import { runWithFreshOrcaCloudSession } from '../cloud-session/profile-cloud-session-refresh' import { connectDevOrcaCloudProfile, createDevCloudLinkedOrcaProfile, selectDevOrcaCloudOrg } from './profile-cloud-dev-service' import { getOrcaProfileAuthStatusFromProfile } from './profile-cloud-auth-status' -import { selectCloudOrg } from './profile-cloud-org-selection' +import { selectCloudOrg } from '../cloud-org/profile-cloud-org-selection' import { endOrcaCloudSignInProgress, setOrcaCloudSignInLink, startOrcaCloudSignInProgress } from './profile-cloud-sign-in-progress' -import { clearRelayRegionPreferenceCache } from '../runtime/mobile-cloud-relay/relay-region-preference' +import { clearRelayRegionPreferenceCache } from '../../runtime/mobile-cloud-relay/relay-region-preference' -export { refreshCurrentOrcaProfileAuth } from './profile-cloud-capability-refresh' +import './profile-cloud-capability-refresh' let nextCloudConnectAttempt = 0 let linkedCloudConnectAttempt = 0 @@ -51,13 +51,6 @@ function invalidateOutstandingCloudConnectAttempts(): void { endOrcaCloudSignInProgress() } -function activeAuth( - active: ReturnType, - userDataPath: string -): OrcaProfileAuthStatus { - return getOrcaProfileAuthStatusFromProfile(active, userDataPath) -} - export function getCurrentOrcaProfileAuthStatus(userDataPath: string): OrcaProfileAuthStatus { return getOrcaProfileAuthStatusFromProfile(ensureActiveOrcaProfile(userDataPath), userDataPath) } @@ -80,7 +73,7 @@ export async function connectCurrentOrcaProfile( if (!configState.configured) { return { status: 'unconfigured', - auth: activeAuth(active, userDataPath) + auth: getOrcaProfileAuthStatusFromProfile(active, userDataPath) } } @@ -193,7 +186,10 @@ export async function createCloudLinkedOrcaProfile( if (isOrcaCloudDevAuthEnabled()) { const result = createDevCloudLinkedOrcaProfile(active, userDataPath, args) if (result.status !== 'created') { - return { status: 'reconnect-required', auth: activeAuth(active, userDataPath) } + return { + status: 'reconnect-required', + auth: getOrcaProfileAuthStatusFromProfile(active, userDataPath) + } } return { status: 'created', @@ -206,7 +202,10 @@ export async function createCloudLinkedOrcaProfile( const configState = getOrcaCloudAuthConfig() if (!configState.configured) { - return { status: 'unconfigured', auth: activeAuth(active, userDataPath) } + return { + status: 'unconfigured', + auth: getOrcaProfileAuthStatusFromProfile(active, userDataPath) + } } try { const operation = await runWithFreshOrcaCloudSession( @@ -216,7 +215,10 @@ export async function createCloudLinkedOrcaProfile( (session) => createOrcaCloudProfile(configState.config, session, args) ) if (operation.status !== 'ok') { - return { status: 'reconnect-required', auth: activeAuth(active, userDataPath) } + return { + status: 'reconnect-required', + auth: getOrcaProfileAuthStatusFromProfile(active, userDataPath) + } } const created = operation.value const list = createCloudLinkedOrcaProfileRecord( @@ -249,7 +251,10 @@ export async function selectCurrentOrcaProfileOrg( if (isOrcaCloudDevAuthEnabled()) { const result = selectDevOrcaCloudOrg(active, userDataPath, orgId) if (result.status !== 'updated') { - return { status: 'reconnect-required', auth: activeAuth(active, userDataPath) } + return { + status: 'reconnect-required', + auth: getOrcaProfileAuthStatusFromProfile(active, userDataPath) + } } return { status: 'selected', @@ -261,7 +266,10 @@ export async function selectCurrentOrcaProfileOrg( const configState = getOrcaCloudAuthConfig() if (!configState.configured) { - return { status: 'unconfigured', auth: activeAuth(active, userDataPath) } + return { + status: 'unconfigured', + auth: getOrcaProfileAuthStatusFromProfile(active, userDataPath) + } } try { const list = await selectCloudOrg({ @@ -271,7 +279,10 @@ export async function selectCurrentOrcaProfileOrg( orgId }) if (!list) { - return { status: 'reconnect-required', auth: activeAuth(active, userDataPath) } + return { + status: 'reconnect-required', + auth: getOrcaProfileAuthStatusFromProfile(active, userDataPath) + } } return { status: 'selected', diff --git a/src/main/orca-profiles/profile-cloud-sign-in-progress.ts b/src/main/orca-profiles/cloud-auth/profile-cloud-sign-in-progress.ts similarity index 95% rename from src/main/orca-profiles/profile-cloud-sign-in-progress.ts rename to src/main/orca-profiles/cloud-auth/profile-cloud-sign-in-progress.ts index 88cb98cc23d..a9d1428f488 100644 --- a/src/main/orca-profiles/profile-cloud-sign-in-progress.ts +++ b/src/main/orca-profiles/cloud-auth/profile-cloud-sign-in-progress.ts @@ -1,4 +1,4 @@ -import type { OrcaCloudSignInProgress } from '../../shared/orca-profiles' +import type { OrcaCloudSignInProgress } from '../../../shared/orca-profiles' type ProgressListener = (progress: OrcaCloudSignInProgress | null) => void diff --git a/src/main/orca-profiles/profile-cloud-dev-org-members.ts b/src/main/orca-profiles/cloud-org/profile-cloud-dev-org-members.ts similarity index 99% rename from src/main/orca-profiles/profile-cloud-dev-org-members.ts rename to src/main/orca-profiles/cloud-org/profile-cloud-dev-org-members.ts index 5ca9d398089..87c0369f275 100644 --- a/src/main/orca-profiles/profile-cloud-dev-org-members.ts +++ b/src/main/orca-profiles/cloud-org/profile-cloud-dev-org-members.ts @@ -7,7 +7,7 @@ import type { OrcaProfileOrgMemberMutationResult, OrcaProfileOrgMemberRemoveArgs, OrcaProfileOrgInviteRevokeArgs -} from '../../shared/orca-profiles' +} from '../../../shared/orca-profiles' // With no dev-auth server, this roster mirrors real membership states and mutation results. type DevOrgRoster = { diff --git a/src/main/orca-profiles/profile-cloud-org-members-client.ts b/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts similarity index 95% rename from src/main/orca-profiles/profile-cloud-org-members-client.ts rename to src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts index 680ec507b01..25812395718 100644 --- a/src/main/orca-profiles/profile-cloud-org-members-client.ts +++ b/src/main/orca-profiles/cloud-org/profile-cloud-org-members-client.ts @@ -3,10 +3,10 @@ import type { OrcaOrgMembersRoster, OrcaOrgPendingInvite, OrcaOrgRole -} from '../../shared/orca-profiles' -import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' -import type { OrcaCloudSession } from './profile-cloud-session-store' -import { OrcaCloudRequestError } from './profile-cloud-client' +} from '../../../shared/orca-profiles' +import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config' +import type { OrcaCloudSession } from '../cloud-session/profile-cloud-session-store' +import { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client' const CLOUD_REQUEST_TIMEOUT_MS = 30_000 const ORG_ROLES: readonly OrcaOrgRole[] = ['owner', 'admin', 'member'] diff --git a/src/main/orca-profiles/profile-cloud-org-members-service.ts b/src/main/orca-profiles/cloud-org/profile-cloud-org-members-service.ts similarity index 91% rename from src/main/orca-profiles/profile-cloud-org-members-service.ts rename to src/main/orca-profiles/cloud-org/profile-cloud-org-members-service.ts index 20b16ebbeac..36ff5517c9c 100644 --- a/src/main/orca-profiles/profile-cloud-org-members-service.ts +++ b/src/main/orca-profiles/cloud-org/profile-cloud-org-members-service.ts @@ -5,14 +5,17 @@ import type { OrcaProfileOrgMemberMutationResult, OrcaProfileOrgMemberRemoveArgs, OrcaProfileOrgMembersListResult -} from '../../shared/orca-profiles' -import type { ActiveOrcaProfileState } from './profile-index-store' -import { ensureActiveOrcaProfile } from './profile-index-store' -import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' -import { getOrcaCloudAuthConfig, isOrcaCloudDevAuthEnabled } from './profile-cloud-auth-config' -import type { OrcaCloudSession } from './profile-cloud-session-store' -import { OrcaCloudRequestError } from './profile-cloud-client' -import { runWithFreshOrcaCloudSession } from './profile-cloud-session-refresh' +} from '../../../shared/orca-profiles' +import type { ActiveOrcaProfileState } from '../profile-index-store' +import { ensureActiveOrcaProfile } from '../profile-index-store' +import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config' +import { + getOrcaCloudAuthConfig, + isOrcaCloudDevAuthEnabled +} from '../cloud-auth/profile-cloud-auth-config' +import type { OrcaCloudSession } from '../cloud-session/profile-cloud-session-store' +import { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client' +import { runWithFreshOrcaCloudSession } from '../cloud-session/profile-cloud-session-refresh' import { changeOrcaCloudOrgMemberRole, inviteOrcaCloudOrgMember, diff --git a/src/main/orca-profiles/profile-cloud-org-selection.ts b/src/main/orca-profiles/cloud-org/profile-cloud-org-selection.ts similarity index 76% rename from src/main/orca-profiles/profile-cloud-org-selection.ts rename to src/main/orca-profiles/cloud-org/profile-cloud-org-selection.ts index 33adf841af6..bfd7a0514fc 100644 --- a/src/main/orca-profiles/profile-cloud-org-selection.ts +++ b/src/main/orca-profiles/cloud-org/profile-cloud-org-selection.ts @@ -1,13 +1,13 @@ -import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' -import { OrcaCloudRequestError, selectOrcaCloudOrg } from './profile-cloud-client' -import { forceRefreshOrcaCloudSession } from './profile-cloud-session-refresh' -import type { ActiveOrcaProfileState } from './profile-index-store' -import type { OrcaProfileListState } from '../../shared/orca-profiles' +import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config' +import { OrcaCloudRequestError, selectOrcaCloudOrg } from '../cloud-auth/profile-cloud-client' +import { forceRefreshOrcaCloudSession } from '../cloud-session/profile-cloud-session-refresh' +import type { ActiveOrcaProfileState } from '../profile-index-store' +import type { OrcaProfileListState } from '../../../shared/orca-profiles' import { beginCloudSessionRelink, commitCloudSessionRelink, readCloudSession -} from './profile-cloud-session-owner' +} from '../cloud-session/profile-cloud-session-owner' export async function selectCloudOrg(input: { config: OrcaCloudAuthConfig diff --git a/src/main/orca-profiles/profile-cloud-refresh-replay-guard.ts b/src/main/orca-profiles/cloud-session/profile-cloud-refresh-replay-guard.ts similarity index 100% rename from src/main/orca-profiles/profile-cloud-refresh-replay-guard.ts rename to src/main/orca-profiles/cloud-session/profile-cloud-refresh-replay-guard.ts diff --git a/src/main/orca-profiles/profile-cloud-session-exchange.ts b/src/main/orca-profiles/cloud-session/profile-cloud-session-exchange.ts similarity index 89% rename from src/main/orca-profiles/profile-cloud-session-exchange.ts rename to src/main/orca-profiles/cloud-session/profile-cloud-session-exchange.ts index d3dff43816f..f678e898eb7 100644 --- a/src/main/orca-profiles/profile-cloud-session-exchange.ts +++ b/src/main/orca-profiles/cloud-session/profile-cloud-session-exchange.ts @@ -2,7 +2,7 @@ import type { OrcaCloudCapabilities, OrcaCloudOrgSummary, OrcaProfileCloudSummary -} from '../../shared/orca-profiles' +} from '../../../shared/orca-profiles' export type OrcaCloudSessionExchangeResponse = { accessToken: string diff --git a/src/main/orca-profiles/profile-cloud-session-invalidation.ts b/src/main/orca-profiles/cloud-session/profile-cloud-session-invalidation.ts similarity index 100% rename from src/main/orca-profiles/profile-cloud-session-invalidation.ts rename to src/main/orca-profiles/cloud-session/profile-cloud-session-invalidation.ts diff --git a/src/main/orca-profiles/profile-cloud-session-owner.ts b/src/main/orca-profiles/cloud-session/profile-cloud-session-owner.ts similarity index 98% rename from src/main/orca-profiles/profile-cloud-session-owner.ts rename to src/main/orca-profiles/cloud-session/profile-cloud-session-owner.ts index 8bea1deac73..d7e573beba7 100644 --- a/src/main/orca-profiles/profile-cloud-session-owner.ts +++ b/src/main/orca-profiles/cloud-session/profile-cloud-session-owner.ts @@ -3,9 +3,9 @@ import type { OrcaCloudOrgSummary, OrcaProfileCloudSummary, OrcaProfileListState -} from '../../shared/orca-profiles' -import { linkOrcaProfileToCloud } from './profile-cloud-index' -import { getOrcaProfileListState, loadOrCreateProfileIndex } from './profile-index-store' +} from '../../../shared/orca-profiles' +import { linkOrcaProfileToCloud } from '../cloud-auth/profile-cloud-index' +import { getOrcaProfileListState, loadOrCreateProfileIndex } from '../profile-index-store' import type { OrcaCloudSessionExchangeResponse } from './profile-cloud-session-exchange' import { clearOrcaCloudSession, diff --git a/src/main/orca-profiles/profile-cloud-session-refresh-rotation.test.ts b/src/main/orca-profiles/cloud-session/profile-cloud-session-refresh-rotation.test.ts similarity index 89% rename from src/main/orca-profiles/profile-cloud-session-refresh-rotation.test.ts rename to src/main/orca-profiles/cloud-session/profile-cloud-session-refresh-rotation.test.ts index b0bd81ffeb4..4e7d81c8a0c 100644 --- a/src/main/orca-profiles/profile-cloud-session-refresh-rotation.test.ts +++ b/src/main/orca-profiles/cloud-session/profile-cloud-session-refresh-rotation.test.ts @@ -2,10 +2,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type * as ProfileCloudClient from './profile-cloud-client' -import type * as SecureFile from '../../shared/secure-storage/secure-file' +import type * as ProfileCloudClient from '../cloud-auth/profile-cloud-client' +import type * as SecureFile from '../../../shared/secure-storage/secure-file' import type * as Fs from 'node:fs' -import type * as ProfileIndexStore from './profile-index-store' +import type * as ProfileIndexStore from '../profile-index-store' const { refreshMock, selectOrgMock, linkMock, linked, writeFailure, removeFailure } = vi.hoisted( () => { @@ -47,7 +47,7 @@ vi.mock('electron', () => ({ } })) -vi.mock('../../shared/secure-storage/secure-file', async (importOriginal) => { +vi.mock('../../../shared/secure-storage/secure-file', async (importOriginal) => { const original = await importOriginal() return { ...original, @@ -65,7 +65,7 @@ vi.mock('../../shared/secure-storage/secure-file', async (importOriginal) => { } }) -vi.mock('./profile-cloud-client', async (importOriginal) => { +vi.mock('../cloud-auth/profile-cloud-client', async (importOriginal) => { const original = await importOriginal() return { ...original, @@ -74,9 +74,9 @@ vi.mock('./profile-cloud-client', async (importOriginal) => { } }) -vi.mock('./profile-cloud-index', () => ({ linkOrcaProfileToCloud: linkMock })) +vi.mock('../cloud-auth/profile-cloud-index', () => ({ linkOrcaProfileToCloud: linkMock })) -vi.mock('./profile-index-store', async (importOriginal) => ({ +vi.mock('../profile-index-store', async (importOriginal) => ({ ...(await importOriginal()), loadOrCreateProfileIndex: () => ({ profiles: [{ id: 'profile-1', cloud: linked.cloud }] }), getOrcaProfileListState: () => ({ activeProfileId: 'profile-1', profiles: [] }) diff --git a/src/main/orca-profiles/profile-cloud-session-refresh.test.ts b/src/main/orca-profiles/cloud-session/profile-cloud-session-refresh.test.ts similarity index 51% rename from src/main/orca-profiles/profile-cloud-session-refresh.test.ts rename to src/main/orca-profiles/cloud-session/profile-cloud-session-refresh.test.ts index 137b335b0da..6e32e91fee0 100644 --- a/src/main/orca-profiles/profile-cloud-session-refresh.test.ts +++ b/src/main/orca-profiles/cloud-session/profile-cloud-session-refresh.test.ts @@ -1,8 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' -import type { ActiveOrcaProfileState } from './profile-index-store' +import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config' +import type { ActiveOrcaProfileState } from '../profile-index-store' import type { OrcaCloudSession } from './profile-cloud-session-store' -import type { OrcaProfileSummary } from '../../shared/orca-profiles' +import type { OrcaProfileSummary } from '../../../shared/orca-profiles' const store = vi.hoisted(() => { const state: { session: OrcaCloudSession | null; signedOut: number } = { @@ -45,16 +45,10 @@ vi.mock('./profile-cloud-session-owner', () => ({ } })) -import { OrcaCloudRequestError } from './profile-cloud-client' -import { - readFreshOrcaCloudSession, - runWithFreshOrcaCloudSession -} from './profile-cloud-session-refresh' +import { OrcaCloudRequestError } from '../cloud-auth/profile-cloud-client' +import { runWithFreshOrcaCloudSession } from './profile-cloud-session-refresh' const HOUR_MS = 3_600_000 -const SERVER_ROTATION_GRACE_MS = 60_000 -const HTML_403 = '

403 Forbidden

' -const HTML_502 = '

502 Bad Gateway

' const AUTH = 'https://auth.example.test' const config: OrcaCloudAuthConfig = { @@ -128,12 +122,6 @@ function signedIn(expired = true): ActiveOrcaProfileState { } } -async function settle(promise: Promise): Promise { - const settled = promise.catch(() => 'threw') - await vi.advanceTimersByTimeAsync(5 * 60_000) - return settled -} - beforeEach(() => { // Response body streams schedule on real immediates; only the request clock is faked. vi.useFakeTimers({ now: 1_000_000, toFake: ['setTimeout', 'clearTimeout', 'Date'] }) @@ -164,83 +152,7 @@ afterEach(() => { vi.useRealTimers() }) -describe('refresh failures that must keep the sign-in', () => { - it.each([ - ['403 HTML from a proxy, CDN, WAF or IAM layer', () => reply(403, HTML_403, 'text/html')], - ['403 JSON', () => reply(403, '{"error":"forbidden"}')], - ['401 HTML from a proxy', () => reply(401, HTML_403, 'text/html')], - ['401 JSON without the refresh-token verdict', () => reply(401, '{"error":"invalid_token"}')], - [ - '401 JSON verdict served as HTML', - () => reply(401, '{"error":"invalid_refresh_token"}', 'text/html') - ], - ['429 rate limited', () => reply(429, '{"error":"rate_limited"}')], - ['502 HTML', () => reply(502, HTML_502, 'text/html')], - ['503 JSON', () => reply(503, '{"error":"unavailable"}')] - ])('%s', async (_name, response) => { - const active = signedIn() - answerRefresh = async () => response() - - await settle(readFreshOrcaCloudSession(config, active, '/user-data')) - - expect(store.signedOut).toBe(0) - expect(store.session).not.toBeNull() - }) -}) - -describe('refresh rejections that end the sign-in', () => { - it.each(['signed_out', 'revoked', 'expired', 'reused', undefined])( - '401 invalid_refresh_token, reason %s', - async (reason) => { - const active = signedIn() - answerRefresh = async () => - reply(401, JSON.stringify({ error: 'invalid_refresh_token', reason })) - - const result = await settle(readFreshOrcaCloudSession(config, active, '/user-data')) - - expect(result).toEqual({ status: 'reconnect-required' }) - expect(store.signedOut).toBe(1) - } - ) -}) - -describe('a refresh the server committed but answered too slowly', () => { - it('resolves inside the rotation grace instead of replaying the token after it', async () => { - const active = signedIn() - const rotations = new Map() - answerRefresh = async (refreshToken) => { - const prior = rotations.get(refreshToken) - if (prior) { - return Date.now() - prior.at < SERVER_ROTATION_GRACE_MS - ? sessionReply(prior.next) - : reply(401, '{"error":"invalid_refresh_token","reason":"reused"}') - } - rotations.set(refreshToken, { at: Date.now(), next: 'refresh-next' }) - return new Promise(() => undefined) - } - - const result = await settle(readFreshOrcaCloudSession(config, active, '/user-data')) - - expect(result).toMatchObject({ status: 'found', session: { refreshToken: 'refresh-next' } }) - expect(store.signedOut).toBe(0) - expect(refreshCalls).toBe(2) - }) -}) - describe('operations wrapped in a fresh session', () => { - it('keeps the sign-in when the operation still answers 401 after a successful refresh', async () => { - const active = signedIn(false) - answerRefresh = async () => sessionReply('refresh-next') - - const result = runWithFreshOrcaCloudSession(config, active, '/user-data', async () => { - throw new OrcaCloudRequestError(401) - }) - - await expect(result).rejects.toBeInstanceOf(OrcaCloudRequestError) - expect(store.signedOut).toBe(0) - expect(store.session?.refreshToken).toBe('refresh-next') - }) - it('does not rotate the token when the operation answers 403', async () => { const active = signedIn(false) answerRefresh = async () => sessionReply('refresh-next') @@ -252,24 +164,4 @@ describe('operations wrapped in a fresh session', () => { await expect(result).rejects.toMatchObject({ statusCode: 403 }) expect(refreshCalls).toBe(0) }) - - it('rotates once for concurrent and repeated 401s within the backoff window', async () => { - const active = signedIn(false) - let rotation = 0 - answerRefresh = async () => sessionReply(`refresh-next-${++rotation}`) - const rejectedCall = (): Promise => - runWithFreshOrcaCloudSession(config, active, '/user-data', async () => { - throw new OrcaCloudRequestError(401) - }).catch((error: unknown) => error) - - const concurrent = await Promise.all([rejectedCall(), rejectedCall(), rejectedCall()]) - await vi.advanceTimersByTimeAsync(60_000) - const repeated = [await rejectedCall(), await rejectedCall()] - - for (const error of [...concurrent, ...repeated]) { - expect(error).toMatchObject({ statusCode: 401 }) - } - expect(refreshCalls).toBe(1) - expect(store.signedOut).toBe(0) - }) }) diff --git a/src/main/orca-profiles/profile-cloud-session-refresh.ts b/src/main/orca-profiles/cloud-session/profile-cloud-session-refresh.ts similarity index 98% rename from src/main/orca-profiles/profile-cloud-session-refresh.ts rename to src/main/orca-profiles/cloud-session/profile-cloud-session-refresh.ts index 77b7cfa11de..f7e33cbb48d 100644 --- a/src/main/orca-profiles/profile-cloud-session-refresh.ts +++ b/src/main/orca-profiles/cloud-session/profile-cloud-session-refresh.ts @@ -1,11 +1,11 @@ -import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' -import type { ActiveOrcaProfileState } from './profile-index-store' +import type { OrcaCloudAuthConfig } from '../cloud-auth/profile-cloud-auth-config' +import type { ActiveOrcaProfileState } from '../profile-index-store' import { orcaCloudSessionKey, type OrcaCloudSession } from './profile-cloud-session-store' import { isAmbiguousCloudRequestFailure, OrcaCloudRequestError, refreshOrcaCloudSession -} from './profile-cloud-client' +} from '../cloud-auth/profile-cloud-client' import type { OrcaCloudSessionExchangeResponse } from './profile-cloud-session-exchange' import { AMBIGUOUS_REFRESH_REPLAY_DELAY_MS, diff --git a/src/main/orca-profiles/profile-cloud-session-store.ts b/src/main/orca-profiles/cloud-session/profile-cloud-session-store.ts similarity index 95% rename from src/main/orca-profiles/profile-cloud-session-store.ts rename to src/main/orca-profiles/cloud-session/profile-cloud-session-store.ts index 00d26cd9446..00772a2cccd 100644 --- a/src/main/orca-profiles/profile-cloud-session-store.ts +++ b/src/main/orca-profiles/cloud-session/profile-cloud-session-store.ts @@ -1,14 +1,14 @@ import { existsSync, readFileSync, rmSync } from 'node:fs' import { join } from 'node:path' -import { guardedSafeStorage as safeStorage } from '../host/safe-storage-availability' -import { isUnreadableError, writeSecureJsonFile } from '../../shared/secure-storage/secure-file' +import { guardedSafeStorage as safeStorage } from '../../host/safe-storage-availability' +import { isUnreadableError, writeSecureJsonFile } from '../../../shared/secure-storage/secure-file' import type { OrcaCloudCapabilities, OrcaCloudOrgSummary, OrcaCloudSessionPersistence -} from '../../shared/orca-profiles' -import { getOrcaProfileDirectory } from './profile-storage-paths' -import { allowsPlaintextOrcaCloudSession } from './profile-cloud-auth-config' +} from '../../../shared/orca-profiles' +import { getOrcaProfileDirectory } from '../profile-storage-paths' +import { allowsPlaintextOrcaCloudSession } from '../cloud-auth/profile-cloud-auth-config' export type OrcaCloudSession = { accessToken: string diff --git a/src/main/orca-profiles/new-profile-state.test.ts b/src/main/orca-profiles/new-profile-state.test.ts deleted file mode 100644 index 593ea8290ae..00000000000 --- a/src/main/orca-profiles/new-profile-state.test.ts +++ /dev/null @@ -1,192 +0,0 @@ -import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' -import { homedir, tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { removeTreeSync } from '../../shared/windows-transient-lock-removal' -import type { PersistedState } from '../../shared/persisted-state-types' -import { getRepoMainWorktreeId } from '../../shared/worktree/id' -import { worktreeWorkspaceKey } from '../../shared/workspace-scope' -import { - acquireProfileStateMaintenance, - acquireProfileStateRuntimeAdmission -} from '../persistence/profile-state/profile-state-access' -import * as database from '../persistence/profile-state/profile-state-database' -import { exportProfileStateJson } from '../persistence/profile-state/profile-state-documents' -import { createProfileStateStore } from '../persistence/profile-state/profile-state-store-factory' -import { getOrcaProfileDataFile, getOrcaProfileStateDatabaseFile } from './profile-index-store' -import { initializeNewOrcaProfileState } from './new-profile-state' - -const telemetry = { - optedIn: false, - installId: 'retained-install-id', - existedBeforeTelemetryRelease: true -} -let root: string -const profileId = 'new-profile' - -beforeEach(() => { - root = mkdtempSync(join(tmpdir(), 'orca-profile-consent-')) -}) - -afterEach(() => { - vi.restoreAllMocks() - removeTreeSync(root) -}) - -function readPublishedState(): PersistedState { - const opened = database.openProfileStateDatabaseReadOnly( - getOrcaProfileStateDatabaseFile(profileId, root), - profileId - ) - try { - const state: PersistedState = JSON.parse(exportProfileStateJson(opened.db)) - return state - } finally { - opened.db.close() - } -} - -describe('new desktop profile initialization', () => { - it.each([telemetry, undefined])( - 'publishes Home with fresh defaults and consent %j', - (inherited) => { - const runtime = acquireProfileStateRuntimeAdmission(root) - try { - initializeNewOrcaProfileState(profileId, inherited, root) - const published = readPublishedState() - const [home] = published.repos - expect(published.repos).toHaveLength(1) - expect(home).toMatchObject({ kind: 'folder', path: homedir() }) - expect(published.projects).toHaveLength(1) - expect(published.projectHostSetups).toHaveLength(1) - const worktreeId = getRepoMainWorktreeId(home) - expect(published.workspaceSession).toMatchObject({ - activeRepoId: home.id, - activeWorktreeId: worktreeId, - activeWorkspaceKey: worktreeWorkspaceKey(worktreeId), - activeWorkspaceExecutionHostId: 'local', - activeTabId: null - }) - expect(published.settings.telemetry).toEqual( - (inherited && { ...inherited, protectedMilestones: { installCohort: 'existing' } }) ?? - expect.objectContaining({ - existedBeforeTelemetryRelease: false, - optedIn: true, - installId: expect.any(String), - onboardingLanguageCohort: expect.stringMatching(/^(control|treatment)$/) - }) - ) - expect(published.settings.tabSwitchKeybindingSeed).toBe('done') - expect(published.chatUiLaunchTipAudience).toEqual({ - version: 1, - membership: 'excluded', - basis: 'new-profile' - }) - expect(published.ui).toMatchObject({ - projectOrderManualDefaultNoticeDismissed: true, - usagePercentageDisplayChangeNoticeDismissed: true, - statusBarCompactChangeNoticeDismissed: true - }) - const options = { - userDataPath: root, - dataFile: getOrcaProfileDataFile(profileId, root), - databaseFile: getOrcaProfileStateDatabaseFile(profileId, root), - profileId, - initializeHomeWorkspace: true - } - const first = createProfileStateStore(options).store - expect(first.getRepos()).toEqual([expect.objectContaining(home)]) - expect(first.getSettings().telemetry).toEqual(published.settings.telemetry) - expect(first.getWorkspaceSession().activeWorktreeId).toBe(worktreeId) - first.flushOrThrow() - first.freezeWrites() - - const reopened = createProfileStateStore(options).store - expect(reopened.getRepos()).toEqual([expect.objectContaining(home)]) - expect(reopened.getSettings().telemetry).toEqual(published.settings.telemetry) - reopened.removeProjectForHost({ id: home.id }) - reopened.flushOrThrow() - reopened.freezeWrites() - initializeNewOrcaProfileState(profileId, inherited, root) - const afterRemoval = createProfileStateStore(options).store - expect(afterRemoval.getRepos()).toEqual([]) - afterRemoval.freezeWrites() - expect(existsSync(getOrcaProfileDataFile(profileId, root))).toBe(false) - expect(() => runtime.assertActive()).not.toThrow() - } finally { - runtime.release() - } - const maintenance = acquireProfileStateMaintenance(root) - maintenance.release() - } - ) - - it('preserves established SQLite consent on a repeated seed', () => { - initializeNewOrcaProfileState(profileId, telemetry, root) - const original = readPublishedState() - initializeNewOrcaProfileState(profileId, { ...telemetry, installId: 'replacement' }, root) - expect(readPublishedState()).toEqual(original) - }) - - it('starts an inherited install with its own existing-profile milestone state', () => { - initializeNewOrcaProfileState( - profileId, - { - optedIn: true, - installId: 'retained-install-id', - existedBeforeTelemetryRelease: false, - protectedMilestones: { - installCohort: 'fresh', - firstAgentInteractionDay: 20_766, - meaningfulActivityDay: 20_766 - } - }, - root - ) - - expect(readPublishedState().settings.telemetry).toEqual({ - optedIn: true, - installId: 'retained-install-id', - existedBeforeTelemetryRelease: false, - protectedMilestones: { installCohort: 'existing' } - }) - }) - - it('preserves existing JSON as input for its later import', () => { - const path = getOrcaProfileDataFile(profileId, root) - const original = '{"settings":{"telemetry":{"installId":"older"}}}' - mkdirSync(dirname(path), { recursive: true }) - writeFileSync(path, original) - - initializeNewOrcaProfileState(profileId, telemetry, root) - - expect(readFileSync(path, 'utf8')).toBe(original) - expect(existsSync(getOrcaProfileStateDatabaseFile(profileId, root))).toBe(false) - }) - - it('refuses seeding while maintenance owns the root', () => { - const maintenance = acquireProfileStateMaintenance(root) - try { - expect(() => initializeNewOrcaProfileState(profileId, telemetry, root)).toThrow() - expect(existsSync(getOrcaProfileStateDatabaseFile(profileId, root))).toBe(false) - } finally { - maintenance.release() - } - }) - - it.each(['orca-data.json.bak.0', 'orca-data.json.sqlite-export.1.json', 'profile-state.db-wal'])( - 'retains missing-authority evidence in %s', - (name) => { - const directory = dirname(getOrcaProfileDataFile(profileId, root)) - mkdirSync(directory, { recursive: true }) - const evidence = join(directory, name) - writeFileSync(evidence, 'retained recovery evidence') - - expect(() => initializeNewOrcaProfileState(profileId, telemetry, root)).toThrow() - - expect(existsSync(getOrcaProfileDataFile(profileId, root))).toBe(false) - expect(existsSync(getOrcaProfileStateDatabaseFile(profileId, root))).toBe(false) - expect(readFileSync(evidence, 'utf8')).toBe('retained recovery evidence') - } - ) -}) diff --git a/src/main/orca-profiles/profile-active-transfer.test.ts b/src/main/orca-profiles/profile-active-transfer.test.ts deleted file mode 100644 index 4ea70f68606..00000000000 --- a/src/main/orca-profiles/profile-active-transfer.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDefaultPersistedState } from '../../shared/constants' -import { ORCA_PROFILE_INDEX_SCHEMA_VERSION } from '../../shared/orca-profiles' -import { openProfileStateDatabase } from '../persistence/profile-state/profile-state-database' -import { importProfileStateJson } from '../persistence/profile-state/profile-state-documents' -import { ProfileStateSqliteAuthority } from '../persistence/profile-state/profile-state-sqlite-authority' -import * as stateFiles from './profile-project-state-file' -import * as domainState from './profile-project-domain-state' -import * as moveIntents from './profile-project-move-intent' -import { transferActiveProfileProject } from './profile-active-transfer' - -vi.mock('electron', () => ({ - app: { - getPath: () => tmpdir(), - getName: () => 'orca-test', - getVersion: () => '0.0.0-test', - isPackaged: false, - on: () => {}, - whenReady: () => Promise.resolve() - }, - safeStorage: { isEncryptionAvailable: () => false }, - ipcMain: { on: () => {}, handle: () => {} }, - BrowserWindow: { getAllWindows: () => [] } -})) -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ - getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) -})) -vi.mock('../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: vi.fn(() => ({ hosts: [] })), - sshConfigHostsToTargets: vi.fn(() => []) -})) - -const { Store } = await import('../persistence/loading-store/store') -const stores: InstanceType[] = [] -let directory: string -const args = { - sourceProfileId: 'source', - targetProfileId: 'target', - repoId: 'repo-1', - mode: 'move' -} as const - -function snapshot(profileId: string) { - return stateFiles.readProfileStateWithRevision(profileId, directory) -} - -function openStore() { - const profileDirectory = join(directory, 'profiles', 'source') - const store = new Store({ - dataFile: join(profileDirectory, 'orca-data.json'), - profileStateAuthority: new ProfileStateSqliteAuthority( - join(profileDirectory, 'profile-state.db'), - 'source' - ) - }) - stores.push(store) - store.flushOrThrow() - return store -} - -function interruptSourceCommit() { - const originalWrite = domainState.writeProfileProjectDomainChanges - return vi - .spyOn(domainState, 'writeProfileProjectDomainChanges') - .mockImplementation((profileId, ...rest) => { - if (profileId === 'source') { - throw new Error('source commit interrupted') - } - return originalWrite(profileId, ...rest) - }) -} - -beforeEach(() => { - directory = mkdtempSync(join(tmpdir(), 'orca-active-profile-transfer-')) - vi.spyOn(ProfileStateSqliteAuthority.prototype, 'scheduleBackup').mockImplementation(() => {}) - writeFileSync( - join(directory, 'orca-profile-index.json'), - JSON.stringify({ - schemaVersion: ORCA_PROFILE_INDEX_SCHEMA_VERSION, - activeProfileId: 'source', - profiles: ['source', 'target'].map((id) => ({ - id, - name: id, - avatar: { kind: 'initials', initials: id[0], color: 'neutral' }, - kind: 'local', - createdAt: 1, - updatedAt: 1, - lastOpenedAt: 1 - })) - }) - ) - for (const profileId of ['source', 'target']) { - const profileDirectory = join(directory, 'profiles', profileId) - mkdirSync(profileDirectory, { recursive: true }) - const db = openProfileStateDatabase(join(profileDirectory, 'profile-state.db'), profileId).db - try { - importProfileStateJson( - db, - JSON.stringify({ - ...getDefaultPersistedState('/home/test'), - repos: - profileId === 'source' - ? [{ id: 'repo-1', path: '/projects/folder', kind: 'folder', addedAt: 1 }] - : [] - }) - ) - } finally { - db.close() - } - } -}) - -afterEach(() => { - for (const store of stores.splice(0)) { - store.freezeWrites() - } - vi.restoreAllMocks() - rmSync(directory, { recursive: true, force: true }) -}) - -describe('active profile transfer recovery', () => { - it('leaves an unchanged SQLite Store writable after validation fails', async () => { - const store = openStore() - const before = snapshot('source') - const reopen = vi.fn(async () => {}) - await expect( - transferActiveProfileProject({ ...args, repoId: 'missing' }, directory, store, reopen) - ).rejects.toThrow('unknown_source_repo') - expect(reopen).not.toHaveBeenCalled() - store.updateSettings({ theme: 'light' }) - store.flushOrThrow() - expect(snapshot('source').revision).toBe((before.revision ?? 0) + 1) - expect(snapshot('source').state.settings.theme).toBe('light') - }) - - it('keeps writes fenced when reopening after a partial transfer fails', async () => { - const store = openStore() - const before = snapshot('source') - const interrupted = interruptSourceCommit() - await expect( - transferActiveProfileProject(args, directory, store, async () => { - throw new Error('reopen failed') - }) - ).rejects.toThrow('reopen failed') - store.updateSettings({ theme: 'light' }) - expect(() => store.flushOrThrow()).toThrow('final persistence') - expect(snapshot('source')).toEqual(before) - interrupted.mockRestore() - expect(moveIntents.recoverPendingProfileProjectMoves(directory)).toBe(1) - }) - - it('keeps the Store frozen when an unreadable intent cannot identify its participants', async () => { - const store = openStore() - const before = snapshot('source') - const intentDirectory = join(directory, 'profile-move-intents') - mkdirSync(intentDirectory) - writeFileSync(join(intentDirectory, '11111111-1111-4111-8111-111111111111.json'), '{') - const reopen = vi.fn(async () => { - moveIntents.recoverPendingProfileProjectMoves(directory) - }) - await expect(transferActiveProfileProject(args, directory, store, reopen)).rejects.toThrow( - 'Profile move intent is unreadable' - ) - store.updateSettings({ theme: 'light' }) - expect(() => store.flushOrThrow()).toThrow('final persistence') - expect(snapshot('source')).toEqual(before) - expect(reopen).toHaveBeenCalledOnce() - }) -}) diff --git a/src/main/orca-profiles/profile-cloud-client.test.ts b/src/main/orca-profiles/profile-cloud-client.test.ts deleted file mode 100644 index bfd9ef8b54a..00000000000 --- a/src/main/orca-profiles/profile-cloud-client.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { OrcaCloudAuthConfig } from './profile-cloud-auth-config' -import { createOrcaCloudProfile, OrcaCloudRequestError } from './profile-cloud-client' -import type { OrcaCloudSession } from './profile-cloud-session-store' - -afterEach(() => { - vi.unstubAllGlobals() -}) - -describe('createOrcaCloudProfile', () => { - it('proves the sign-in with its refresh token alongside the access token', async () => { - const fetchImpl = vi.fn( - async () => new Response(null, { status: 403 }) - ) - vi.stubGlobal('fetch', fetchImpl) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the call reads only this endpoint. - const config = { - profileEndpoint: 'https://login.test/v1/desktop/auth/profile' - } as OrcaCloudAuthConfig - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the call reads only the two tokens. - const session = { accessToken: 'access-1', refreshToken: 'refresh-1' } as OrcaCloudSession - - await expect( - createOrcaCloudProfile(config, session, { orgId: 'org-1', name: 'Work' }) - ).rejects.toBeInstanceOf(OrcaCloudRequestError) - - const [url, init] = fetchImpl.mock.calls[0]! - expect(url).toBe('https://login.test/v1/desktop/auth/profile') - expect(new Headers(init?.headers).get('authorization')).toBe('Bearer access-1') - expect(JSON.parse(String(init?.body))).toEqual({ - orgId: 'org-1', - name: 'Work', - refreshToken: 'refresh-1' - }) - }) -}) diff --git a/src/main/orca-profiles/profile-cloud-session-store.test.ts b/src/main/orca-profiles/profile-cloud-session-store.test.ts deleted file mode 100644 index 7aaa0385326..00000000000 --- a/src/main/orca-profiles/profile-cloud-session-store.test.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { OrcaCloudSession } from './profile-cloud-session-store' - -const safeStorageMock = vi.hoisted(() => ({ - decryptString: vi.fn((value: Buffer) => value.toString('utf-8')), - encryptString: vi.fn((value: string) => Buffer.from(value, 'utf-8')), - isEncryptionAvailable: vi.fn(() => true) -})) - -let userDataPath = '' - -vi.mock('electron', () => ({ - app: { - getPath: () => userDataPath - }, - safeStorage: safeStorageMock -})) - -async function loadSessionStore() { - vi.resetModules() - return import('./profile-cloud-session-store') -} - -function makeSession(): OrcaCloudSession { - return { - accessToken: 'access-token', - refreshToken: 'refresh-token', - expiresAt: 9_999, - organizations: [ - { orgId: 'org-1', name: 'Acme', role: 'Admin' }, - { orgId: 'org-2', name: 'Personal' } - ], - capabilities: { - flags: { share: true }, - refreshedAt: 123 - } - } -} - -function writePlaintextSessionFile(profileId: string, session: OrcaCloudSession): void { - const profileDirectory = join(userDataPath, 'profiles', profileId) - mkdirSync(profileDirectory, { recursive: true }) - writeFileSync( - join(profileDirectory, 'account-session.json.enc'), - JSON.stringify( - { - version: 1, - format: 'dev-plaintext-v1', - savedAt: 1, - session - }, - null, - 2 - ), - 'utf-8' - ) -} - -describe('Orca cloud session store', () => { - beforeEach(() => { - userDataPath = mkdtempSync(join(tmpdir(), 'orca-cloud-session-')) - vi.unstubAllEnvs() - safeStorageMock.decryptString.mockClear() - safeStorageMock.encryptString.mockClear() - safeStorageMock.isEncryptionAvailable.mockClear() - safeStorageMock.isEncryptionAvailable.mockReturnValue(true) - }) - - afterEach(() => { - rmSync(userDataPath, { recursive: true, force: true }) - vi.unstubAllEnvs() - }) - - it('rejects dev plaintext files when the escape hatch is disabled', async () => { - safeStorageMock.isEncryptionAvailable.mockReturnValue(false) - writePlaintextSessionFile('profile-1', makeSession()) - const store = await loadSessionStore() - - expect(store.readOrcaCloudSession('profile-1', userDataPath)).toEqual({ - status: 'decrypt-failed', - persistence: 'none', - error: 'Unsafe session format.' - }) - }) -}) diff --git a/src/main/orca-profiles/profile-index-store.test.ts b/src/main/orca-profiles/profile-index-store.test.ts index aea3aed0c5d..d7cac25b9e1 100644 --- a/src/main/orca-profiles/profile-index-store.test.ts +++ b/src/main/orca-profiles/profile-index-store.test.ts @@ -134,7 +134,7 @@ describe('profile index store', () => { const posixIt = process.platform === 'win32' ? it.skip : it posixIt('writes a fresh profile index when umask removes owner-write permission', async () => { const store = await loadProfileIndexStore() - const indexPath = store.getOrcaProfileIndexPath() + const indexPath = (await import('./profile-storage-paths')).getOrcaProfileIndexPath() const profile = createDefaultLocalOrcaProfile(1) const index: OrcaProfileIndex = { schemaVersion: ORCA_PROFILE_INDEX_SCHEMA_VERSION, @@ -157,7 +157,7 @@ describe('profile index store', () => { store.ensureActiveOrcaProfile() const created = store.createLocalOrcaProfile({ name: 'Work' }) store.setActiveOrcaProfile(created.profile.id) - const indexPath = store.getOrcaProfileIndexPath() + const indexPath = (await import('./profile-storage-paths')).getOrcaProfileIndexPath() renameSync(indexPath, `${indexPath}.bak`) expect(store.loadOrCreateProfileIndex(testState.dir).activeProfileId).toBe(created.profile.id) @@ -165,35 +165,9 @@ describe('profile index store', () => { expect(readJson(indexPath)).toMatchObject({ activeProfileId: created.profile.id }) }) - it.each(['primary', 'backup', 'both'] as const)( - 'refuses an unreadable %s index without replacing it', - async (source) => { - const store = await loadProfileIndexStore() - const indexPath = store.getOrcaProfileIndexPath() - if (source !== 'backup') { - writeFileSync(indexPath, '{broken-primary') - } - if (source !== 'primary') { - writeFileSync(`${indexPath}.bak`, '{broken-backup') - } - - expect(() => store.loadOrCreateProfileIndex(testState.dir)).toThrow( - 'Could not read active profile index' - ) - expect(() => store.ensureActiveOrcaProfile()).toThrow('Could not read active profile index') - if (source !== 'backup') { - expect(readFileSync(indexPath, 'utf8')).toBe('{broken-primary') - } - if (source !== 'primary') { - expect(readFileSync(`${indexPath}.bak`, 'utf8')).toBe('{broken-backup') - } - expect(existsSync(join(testState.dir, 'profiles'))).toBe(false) - } - ) - it('rejects profile ids that are not safe path segments', async () => { const store = await loadProfileIndexStore() - const indexPath = store.getOrcaProfileIndexPath() + const indexPath = (await import('./profile-storage-paths')).getOrcaProfileIndexPath() const index: OrcaProfileIndex = { schemaVersion: ORCA_PROFILE_INDEX_SCHEMA_VERSION, activeProfileId: '../../escape', diff --git a/src/main/orca-profiles/profile-index-store.ts b/src/main/orca-profiles/profile-index-store.ts index 2c082b9a624..f69c060ce5e 100644 --- a/src/main/orca-profiles/profile-index-store.ts +++ b/src/main/orca-profiles/profile-index-store.ts @@ -31,22 +31,11 @@ import { hasOrcaProfileStateDatabase, getProfileUserDataPath } from './profile-storage-paths' -import { copyLegacyStateToProfile } from './profile-legacy-state-import' +import { copyLegacyStateToProfile } from './storage/profile-legacy-state-import' import { profileStateJsonExportPaths } from '../persistence/profile-state/legacy-json/profile-state-export-path' import { hasProfileStateAuthorityMarker } from '../persistence/profile-state/profile-state-authority-marker' import { profileStateDatabaseBackups } from '../persistence/profile-state/profile-state-backup-path' -export { - getOrcaProfileBrowserSessionMetaFile, - getOrcaProfileDataFile, - getOrcaProfileDirectory, - getOrcaProfileIndexPath, - getOrcaProfileStateDatabaseFile, - hasOrcaProfileStateDatabase, - getOrcaProfilesDirectory, - initOrcaProfilePaths -} from './profile-storage-paths' - export type ActiveOrcaProfileState = { index: OrcaProfileIndex profile: OrcaProfileSummary diff --git a/src/main/orca-profiles/profile-project-domain-transfer.test.ts b/src/main/orca-profiles/profile-project-domain-transfer.test.ts deleted file mode 100644 index b1fc06965da..00000000000 --- a/src/main/orca-profiles/profile-project-domain-transfer.test.ts +++ /dev/null @@ -1,211 +0,0 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' -import { buildSync } from 'esbuild' -import { ORCA_PROFILE_INDEX_SCHEMA_VERSION } from '../../shared/orca-profiles' -import type { Repo } from '../../shared/repo-types' -import { openProfileStateDatabase } from '../persistence/profile-state/profile-state-database' -import { - hashProfileStateJson, - importProfileStateJson, - readProfileStateSnapshot -} from '../persistence/profile-state/profile-state-documents' -import { transferOrcaProfileProject } from './profile-project-transfer' - -let root: string -let crashRoot: string -let crashBundle: string -let crashScript: string -const repo: Repo = { - id: 'repo-1', - path: '/project', - displayName: 'Project', - badgeColor: 'neutral', - addedAt: 1, - kind: 'git', - connectionId: null -} - -function dbPath(id: string): string { - return join(root, 'profiles', id, 'profile-state.db') -} - -function withDatabase( - id: string, - action: (db: ReturnType['db']) => T -): T { - const opened = openProfileStateDatabase(dbPath(id), id) - try { - return action(opened.db) - } finally { - opened.db.close() - } -} - -function seed(id: string, repos: Repo[] = []): void { - mkdirSync(join(root, 'profiles', id), { recursive: true }) - withDatabase(id, (db) => - importProfileStateJson( - db, - JSON.stringify({ - futureOpaque: { z: ['\ud800', null, id], a: 'x'.repeat(100_000) }, - ['']: { keep: true }, - ['__proto__']: { inert: true }, - settings: { opencodeSessionCookie: 'enc:v1:sealed-inactive', unknownSetting: [2, 1] }, - repos, - projects: null, - projectHostSetups: null, - workspaceSessionsByHostId: null, - automationRuns: [], - futureNull: null, - futureDelete: { remove: true } - }) - ) - ) -} - -function raw(id: string) { - return withDatabase(id, (db) => readProfileStateSnapshot(db)) -} - -function transfer(mode: 'copy' | 'move' = 'move') { - return transferOrcaProfileProject( - { sourceProfileId: 'source', targetProfileId: 'target', repoId: repo.id, mode }, - root - ) -} - -beforeAll(() => { - crashRoot = mkdtempSync(join(tmpdir(), 'orca-domain-move-crash-api-')) - crashBundle = join(crashRoot, 'api.cjs') - crashScript = join(crashRoot, 'crash.cjs') - buildSync({ - stdin: { - contents: - "export { transferOrcaProfileProject } from './src/main/orca-profiles/profile-project-transfer'", - loader: 'ts', - resolveDir: process.cwd() - }, - outfile: crashBundle, - bundle: true, - platform: 'node', - format: 'cjs', - packages: 'external' - }) - writeFileSync( - crashScript, - ` -const fs = require('node:fs') -const path = require('node:path') -const [bundle, root, stage] = process.argv.slice(2) -const barrier = label => { - if (label !== stage) return - fs.writeSync(1, label + '\\n') - process.kill(process.pid, 'SIGKILL') - throw new Error('SIGKILL returned') -} -const sqlite = require('node:sqlite') -const exec = sqlite.DatabaseSync.prototype.exec -const writers = new WeakSet() -sqlite.DatabaseSync.prototype.exec = function(sql) { - const writing = writers.has(this) - const participant = writing ? this.prepare("SELECT value FROM profile_state_meta WHERE key = 'profile_id'").get().value : '' - if (writing && sql === 'COMMIT') barrier(participant + '-before-commit') - const result = exec.call(this, sql) - if (sql === 'BEGIN IMMEDIATE') writers.add(this) - if (sql === 'COMMIT' || sql === 'ROLLBACK') writers.delete(this) - if (writing && sql === 'COMMIT') barrier(participant + '-committed') - return result -} -let published = false -let removed = false -const rename = fs.renameSync -fs.renameSync = (from, to) => { - const intent = path.dirname(to) === path.join(root, 'profile-move-intents') && to.endsWith('.json') - if (intent) barrier('intent-before-publish') - rename(from, to) - if (intent) { published = true; barrier('intent-published') } -} -const rm = fs.rmSync -fs.rmSync = (target, ...rest) => { - const intent = path.dirname(target) === path.join(root, 'profile-move-intents') && target.endsWith('.json') - if (intent) barrier('cleanup-before-remove') - rm(target, ...rest) - if (intent) { removed = true; barrier('cleanup-removed') } -} -const fsync = fs.fsyncSync -fs.fsyncSync = fd => { - fsync(fd) - if (fs.fstatSync(fd).isDirectory()) { - if (removed) barrier('cleanup-durable') - else if (published) barrier('intent-durable') - } -} -require(bundle).transferOrcaProfileProject({ sourceProfileId: 'source', targetProfileId: 'target', repoId: 'repo-1', mode: 'move' }, root) -throw new Error('Crash boundary not reached: ' + stage) -` - ) -}) - -afterAll(() => rmSync(crashRoot, { recursive: true, force: true })) - -beforeEach(() => { - root = mkdtempSync(join(tmpdir(), 'orca-domain-transfer-')) - writeFileSync( - join(root, 'orca-profile-index.json'), - JSON.stringify({ - schemaVersion: ORCA_PROFILE_INDEX_SCHEMA_VERSION, - activeProfileId: 'source', - profiles: ['source', 'target'].map((id) => ({ - id, - name: id, - avatar: { kind: 'initials', initials: id[0], color: 'neutral' }, - kind: 'local', - createdAt: 1, - updatedAt: 1, - lastOpenedAt: 1 - })) - }) - ) - seed('source', [repo]) - seed('target') -}) - -afterEach(() => { - vi.restoreAllMocks() - rmSync(root, { recursive: true, force: true }) -}) - -describe('profile domain transfers', () => { - it('moves a project without granting publishing permission to either older profile', () => { - expect(transfer()).toMatchObject({ status: 'transferred' }) - expect(JSON.parse(raw('source').json).settings).not.toHaveProperty('artifactSharingEnabled') - expect(JSON.parse(raw('target').json).settings).not.toHaveProperty('artifactSharingEnabled') - }) - - it('refuses independently hashed malformed unrelated data before a copy writes anything', () => { - const before = raw('target').json - withDatabase('source', (db) => - db - .prepare( - 'UPDATE profile_state_documents SET payload = ?, content_hash = ? WHERE domain = ?' - ) - .run('null,"extra":true', hashProfileStateJson('null,"extra":true'), 'futureNull') - ) - expect(() => transfer('copy')).toThrow(/JSON/) - expect(raw('target').json).toBe(before) - }) - void [ - 'intent-before-publish', - 'intent-published', - ...(process.platform === 'win32' ? [] : ['intent-durable']), - 'target-before-commit', - 'target-committed', - 'source-before-commit', - 'source-committed', - 'cleanup-before-remove', - 'cleanup-removed', - ...(process.platform === 'win32' ? [] : ['cleanup-durable']) - ] -}) diff --git a/src/main/orca-profiles/profile-active-transfer-worker.test.ts b/src/main/orca-profiles/project-transfer/profile-active-transfer-worker.test.ts similarity index 72% rename from src/main/orca-profiles/profile-active-transfer-worker.test.ts rename to src/main/orca-profiles/project-transfer/profile-active-transfer-worker.test.ts index ddb6daa43c5..88584f08e6c 100644 --- a/src/main/orca-profiles/profile-active-transfer-worker.test.ts +++ b/src/main/orca-profiles/project-transfer/profile-active-transfer-worker.test.ts @@ -2,23 +2,21 @@ import { mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' -import { getDefaultPersistedState } from '../../shared/constants' -import { ORCA_PROFILE_INDEX_SCHEMA_VERSION } from '../../shared/orca-profiles' -import { createWorkerMaintenanceFixture } from '../persistence/loading-store/profile-state-maintenance-fixture' -import { ProfileStateSqliteAuthority } from '../persistence/profile-state/profile-state-sqlite-authority' +import { getDefaultPersistedState } from '../../../shared/constants' +import { ORCA_PROFILE_INDEX_SCHEMA_VERSION } from '../../../shared/orca-profiles' +import { createWorkerMaintenanceFixture } from '../../persistence/loading-store/profile-state-maintenance-fixture' +import { ProfileStateSqliteAuthority } from '../../persistence/profile-state/profile-state-sqlite-authority' import { transferActiveProfileProject } from './profile-active-transfer' import * as domainState from './profile-project-domain-state' -import { - profileHasPendingProjectMove, - recoverPendingProfileProjectMoves -} from './profile-project-move-intent' +import { recoverPendingProfileProjectMoves } from './profile-project-move-intent' +import { profileHasPendingProjectMove } from './profile-project-move-record' import { readProfileStateWithRevision } from './profile-project-state-file' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) -vi.mock('../ssh/config/ssh-config-parser', () => ({ +vi.mock('../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) @@ -78,18 +76,6 @@ describe('active profile transfers with the live writer', () => { expect(read('source').state.settings.theme).toBe('dark') }) - it('keeps the source frozen after moving a remote project and its persisted state', async () => { - const { store, root, args, read } = await fixture() - const result = await transferActiveProfileProject(args, root, store, async () => {}) - expect(result.status).toBe('transferred') - expect(read('source').state.repos.some((repo) => repo.id === args.repoId)).toBe(false) - expect(read('target').state.repos.some((repo) => repo.id === args.repoId)).toBe(true) - const source = read('source') - store.updateSettings({ theme: 'dark' }) - await expect(store.flushPendingOrThrowAsync()).rejects.toThrow('finalized') - expect(read('source')).toEqual(source) - }) - it('leaves an interrupted move frozen until journal recovery runs with the writer closed', async () => { const { store, root, args, read } = await fixture() const original = domainState.writeProfileProjectDomainChanges diff --git a/src/main/orca-profiles/profile-active-transfer.ts b/src/main/orca-profiles/project-transfer/profile-active-transfer.ts similarity index 83% rename from src/main/orca-profiles/profile-active-transfer.ts rename to src/main/orca-profiles/project-transfer/profile-active-transfer.ts index 53ba8481da5..7734fe4a100 100644 --- a/src/main/orca-profiles/profile-active-transfer.ts +++ b/src/main/orca-profiles/project-transfer/profile-active-transfer.ts @@ -1,12 +1,13 @@ import type { TransferOrcaProfileProjectArgs, TransferOrcaProfileProjectResult -} from '../../shared/orca-profiles' -import type { Store } from '../persistence/loading-store/store' +} from '../../../shared/orca-profiles' +import type { Store } from '../../persistence/loading-store/store' import { transferOrcaProfileProject } from './profile-project-transfer' -import { hasOrcaProfileStateDatabase } from './profile-storage-paths' -import { profileHasPendingProjectMove } from './profile-project-move-intent' -import { flushActiveProfileBeforeFileMutation } from './profile-persistence-deadline' +import { hasOrcaProfileStateDatabase } from '../profile-storage-paths' +import './profile-project-move-intent' +import { profileHasPendingProjectMove } from './profile-project-move-record' +import { flushActiveProfileBeforeFileMutation } from '../storage/profile-persistence-deadline' /** Keep the active Store stopped until file mutation either succeeds or proves unchanged. */ export async function transferActiveProfileProject( diff --git a/src/main/orca-profiles/profile-project-domain-changes.ts b/src/main/orca-profiles/project-transfer/profile-project-domain-changes.ts similarity index 90% rename from src/main/orca-profiles/profile-project-domain-changes.ts rename to src/main/orca-profiles/project-transfer/profile-project-domain-changes.ts index 51fc3bc378c..93068f65f25 100644 --- a/src/main/orca-profiles/profile-project-domain-changes.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-domain-changes.ts @@ -1,11 +1,11 @@ -import { hashProfileStateJson } from '../persistence/profile-state/profile-state-documents' +import { hashProfileStateJson } from '../../persistence/profile-state/profile-state-documents' import { isRecord, type ProfileStateParsedDocument -} from '../persistence/profile-state/profile-state-document-validation' -import { prepareProfileStateDomainMutation } from '../persistence/profile-state/profile-state-domain-write-validation' -import type { ProfileStateDomainMutation } from '../persistence/profile-state/profile-state-domain-writes' -import type { PersistedState } from '../../shared/persisted-state-types' +} from '../../persistence/profile-state/profile-state-document-validation' +import { prepareProfileStateDomainMutation } from '../../persistence/profile-state/profile-state-domain-write-validation' +import type { ProfileStateDomainMutation } from '../../persistence/profile-state/profile-state-domain-writes' +import type { PersistedState } from '../../../shared/persisted-state-types' export type ProfileProjectDomainDigest = { domain: string; hash: string } diff --git a/src/main/orca-profiles/profile-project-domain-move-intent.ts b/src/main/orca-profiles/project-transfer/profile-project-domain-move-intent.ts similarity index 96% rename from src/main/orca-profiles/profile-project-domain-move-intent.ts rename to src/main/orca-profiles/project-transfer/profile-project-domain-move-intent.ts index 3441b2d8f3a..f4943afa8da 100644 --- a/src/main/orca-profiles/profile-project-domain-move-intent.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-domain-move-intent.ts @@ -1,6 +1,6 @@ import { randomUUID } from 'node:crypto' import type { ProfileProjectDomainMoveIntent } from './profile-project-move-record' -export type { ProfileProjectDomainMoveIntent } from './profile-project-move-record' + import { profileProjectDomainDigests, profileProjectDomainFingerprint, diff --git a/src/main/orca-profiles/profile-project-domain-state.ts b/src/main/orca-profiles/project-transfer/profile-project-domain-state.ts similarity index 72% rename from src/main/orca-profiles/profile-project-domain-state.ts rename to src/main/orca-profiles/project-transfer/profile-project-domain-state.ts index d691ee0e1f6..6661ac70aa2 100644 --- a/src/main/orca-profiles/profile-project-domain-state.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-domain-state.ts @@ -1,17 +1,16 @@ -import { ProfileStateLegacyDocumentRefresh } from '../persistence/profile-state/profile-state-legacy-document-refresh' +import { ProfileStateLegacyDocumentRefresh } from '../../persistence/profile-state/profile-state-legacy-document-refresh' import { openProfileStateDatabase, openProfileStateDatabaseReadOnly -} from '../persistence/profile-state/profile-state-database' -import { - readProfileStateDocuments, - readProfileStateRevision -} from '../persistence/profile-state/profile-state-documents' -import type { ProfileStateParsedDocument } from '../persistence/profile-state/profile-state-document-validation' -import { writeProfileStateDomains } from '../persistence/profile-state/profile-state-domain-writes' -import { withProfileStateReadSnapshot } from '../persistence/profile-state/profile-state-read-snapshot' -import { getOrcaProfileStateDatabaseFile } from './profile-storage-paths' -import { ensureProfileStateAuthorityMarker } from '../persistence/profile-state/profile-state-authority-marker' +} from '../../persistence/profile-state/profile-state-database' +import '../../persistence/profile-state/profile-state-documents' +import { readProfileStateDocuments } from '../../persistence/profile-state/profile-state-document-reader' +import { readProfileStateRevision } from '../../persistence/profile-state/profile-state-revision' +import type { ProfileStateParsedDocument } from '../../persistence/profile-state/profile-state-document-validation' +import { writeProfileStateDomains } from '../../persistence/profile-state/profile-state-domain-writes' +import { withProfileStateReadSnapshot } from '../../persistence/profile-state/profile-state-read-snapshot' +import { getOrcaProfileStateDatabaseFile } from '../profile-storage-paths' +import { ensureProfileStateAuthorityMarker } from '../../persistence/profile-state/profile-state-authority-marker' import { normalizeProfileProjectState, profileStateStorage, diff --git a/src/main/orca-profiles/profile-project-move-intent.ts b/src/main/orca-profiles/project-transfer/profile-project-move-intent.ts similarity index 91% rename from src/main/orca-profiles/profile-project-move-intent.ts rename to src/main/orca-profiles/project-transfer/profile-project-move-intent.ts index cdbd089f1ea..a9135467b7c 100644 --- a/src/main/orca-profiles/profile-project-move-intent.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-move-intent.ts @@ -3,14 +3,14 @@ import { mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs' import { bestEffortFsyncDirectorySync, fsyncFileSync -} from '../../shared/secure-storage/secure-file' -import { hashProfileStateJson } from '../persistence/profile-state/profile-state-documents' +} from '../../../shared/secure-storage/secure-file' +import { hashProfileStateJson } from '../../persistence/profile-state/profile-state-documents' import { readProfileStateWithRevision, writeSerializedProfileState, type ReadProfileStateResult } from './profile-project-state-file' -import { getOrcaProfileMoveIntentDirectory } from './profile-storage-paths' +import { getOrcaProfileMoveIntentDirectory } from '../profile-storage-paths' import { readProfileProjectDomainMoveState } from './profile-project-domain-move-intent' import { writeProfileProjectDomainChanges } from './profile-project-domain-state' import { @@ -20,11 +20,6 @@ import { type ProfileProjectMoveIntent, type ProfileProjectMoveIntentV1 } from './profile-project-move-record' -export { profileHasPendingProjectMove } from './profile-project-move-record' -export type { - ProfileProjectMoveIdentity, - ProfileProjectMoveIntent -} from './profile-project-move-record' export function persistProfileProjectMoveIntent( userDataPath: string, diff --git a/src/main/orca-profiles/profile-project-move-record.ts b/src/main/orca-profiles/project-transfer/profile-project-move-record.ts similarity index 94% rename from src/main/orca-profiles/profile-project-move-record.ts rename to src/main/orca-profiles/project-transfer/profile-project-move-record.ts index 68391cd117d..b2032d78177 100644 --- a/src/main/orca-profiles/profile-project-move-record.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-move-record.ts @@ -1,8 +1,8 @@ import { existsSync, readdirSync, readFileSync } from 'node:fs' import { basename, join } from 'node:path' -import { hashProfileStateJson } from '../persistence/profile-state/profile-state-documents' -import { isRecord } from '../persistence/profile-state/profile-state-document-validation' -import { getOrcaProfileMoveIntentDirectory } from './profile-storage-paths' +import { hashProfileStateJson } from '../../persistence/profile-state/profile-state-documents' +import { isRecord } from '../../persistence/profile-state/profile-state-document-validation' +import { getOrcaProfileMoveIntentDirectory } from '../profile-storage-paths' import { validateProfileProjectDomainChanges, type ProfileProjectDomainChanges diff --git a/src/main/orca-profiles/profile-project-retired-name-transfer.ts b/src/main/orca-profiles/project-transfer/profile-project-retired-name-transfer.ts similarity index 74% rename from src/main/orca-profiles/profile-project-retired-name-transfer.ts rename to src/main/orca-profiles/project-transfer/profile-project-retired-name-transfer.ts index 40722f20116..70bcc80756b 100644 --- a/src/main/orca-profiles/profile-project-retired-name-transfer.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-retired-name-transfer.ts @@ -1,14 +1,14 @@ -import type { Repo } from '../../shared/repo-types' +import type { Repo } from '../../../shared/repo-types' import { mergeRetiredNameRegistries, type RetiredNameRegistry -} from '../../shared/worktree/retired-name-registry' -import { getRemoteRetirementNamespaceKey } from '../workspaces/removal/retirement/worktree-name-retirement' -import { retirementNamespaceKeysToRead } from '../workspaces/removal/retirement/worktree-retirement-namespace' -import type { TransferProfileState } from './profile-project-state-file' +} from '../../../shared/worktree/retired-name-registry' +import { getRemoteRetirementNamespaceKey } from '../../workspaces/removal/retirement/worktree-name-retirement' +import { retirementNamespaceKeysToRead } from '../../workspaces/removal/retirement/worktree-retirement-namespace' +import type { PersistedState } from '../../../shared/persisted-state-types' export function extractRetiredNameRegistriesByNamespace( - sourceState: TransferProfileState, + sourceState: PersistedState, sourceRepo: Repo ): Record { const lookup = (targetId: string) => diff --git a/src/main/orca-profiles/profile-project-session-field-disposition.test.ts b/src/main/orca-profiles/project-transfer/profile-project-session-field-disposition.test.ts similarity index 94% rename from src/main/orca-profiles/profile-project-session-field-disposition.test.ts rename to src/main/orca-profiles/project-transfer/profile-project-session-field-disposition.test.ts index a5ef09ae4e4..5c69a96eefc 100644 --- a/src/main/orca-profiles/profile-project-session-field-disposition.test.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-session-field-disposition.test.ts @@ -1,11 +1,11 @@ import { describe, expect, it } from 'vitest' -import { getDefaultWorkspaceSession } from '../../shared/constants' +import { getDefaultWorkspaceSession } from '../../../shared/constants' import { CLIENT_HOSTED_BROWSER_PAGE_RECORD_VERSION, type PersistedClientHostedBrowserPage -} from '../../shared/workspace-session/client-hosted-browser-page-record' +} from '../../../shared/workspace-session/client-hosted-browser-page-record' -import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' +import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { removeRepoFromWorkspaceSession } from './profile-project-session-state' import { extractSessionForTransfer } from './profile-project-session-transfer' diff --git a/src/main/orca-profiles/profile-project-session-field-disposition.ts b/src/main/orca-profiles/project-transfer/profile-project-session-field-disposition.ts similarity index 98% rename from src/main/orca-profiles/profile-project-session-field-disposition.ts rename to src/main/orca-profiles/project-transfer/profile-project-session-field-disposition.ts index 392c4eda37c..4e6daf8dc4f 100644 --- a/src/main/orca-profiles/profile-project-session-field-disposition.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-session-field-disposition.ts @@ -1,4 +1,4 @@ -import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' +import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' export type SessionFieldRepoRemovalDisposition = /** Delete map keys belonging to the repo. */ diff --git a/src/main/orca-profiles/profile-project-session-state.test.ts b/src/main/orca-profiles/project-transfer/profile-project-session-state.test.ts similarity index 97% rename from src/main/orca-profiles/profile-project-session-state.test.ts rename to src/main/orca-profiles/project-transfer/profile-project-session-state.test.ts index 0a54730233d..9fb3ae2713f 100644 --- a/src/main/orca-profiles/profile-project-session-state.test.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-session-state.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { getDefaultWorkspaceSession } from '../../shared/constants' -import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' +import { getDefaultWorkspaceSession } from '../../../shared/constants' +import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { mergeWorkspaceSessions, removeRepoFromWorkspaceSession diff --git a/src/main/orca-profiles/profile-project-session-state.ts b/src/main/orca-profiles/project-transfer/profile-project-session-state.ts similarity index 96% rename from src/main/orca-profiles/profile-project-session-state.ts rename to src/main/orca-profiles/project-transfer/profile-project-session-state.ts index 699b3281b43..d69e50face4 100644 --- a/src/main/orca-profiles/profile-project-session-state.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-session-state.ts @@ -1,7 +1,7 @@ -import { getDefaultWorkspaceSession } from '../../shared/constants' -import type { ExecutionHostId } from '../../shared/execution-host' -import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' -import { parseWorkspaceKey } from '../../shared/workspace-scope' +import { getDefaultWorkspaceSession } from '../../../shared/constants' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import { parseWorkspaceKey } from '../../../shared/workspace-scope' import { SESSION_FIELDS_PRUNED_BY_OWNER_KEY } from './profile-project-session-field-disposition' import { markdownFileIdCandidates } from './profile-session-markdown-transfer' import { diff --git a/src/main/orca-profiles/profile-project-session-transfer.ts b/src/main/orca-profiles/project-transfer/profile-project-session-transfer.ts similarity index 87% rename from src/main/orca-profiles/profile-project-session-transfer.ts rename to src/main/orca-profiles/project-transfer/profile-project-session-transfer.ts index 97f6f501e8a..ad42ad9b7de 100644 --- a/src/main/orca-profiles/profile-project-session-transfer.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-session-transfer.ts @@ -1,5 +1,5 @@ -import type { ExecutionHostId } from '../../shared/execution-host' -import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { rekeyOwnerKey, rekeyWorktreeId } from './profile-project-worktree-identity' import { extractSessionOwnersForTransfer, diff --git a/src/main/orca-profiles/profile-project-source-removal.ts b/src/main/orca-profiles/project-transfer/profile-project-source-removal.ts similarity index 84% rename from src/main/orca-profiles/profile-project-source-removal.ts rename to src/main/orca-profiles/project-transfer/profile-project-source-removal.ts index 36a8db52d21..f18a84ac986 100644 --- a/src/main/orca-profiles/profile-project-source-removal.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-source-removal.ts @@ -1,19 +1,14 @@ -import { type WorkspaceKey, parseWorkspaceKey } from '../../shared/workspace-scope' -import { - rebuildRepoBackedProjectState, - type TransferProfileState -} from './profile-project-state-file' +import { type WorkspaceKey, parseWorkspaceKey } from '../../../shared/workspace-scope' +import { rebuildRepoBackedProjectState } from './profile-project-state-file' +import type { PersistedState } from '../../../shared/persisted-state-types' import { removeRepoFromHostWorkspaceSessions, removeRepoFromWorkspaceSession } from './profile-project-session-state' import { isRepoWorktreeId, removeRepoWorktreeRecord } from './profile-project-worktree-identity' -export function removeSourceRepo( - state: TransferProfileState, - repoId: string -): TransferProfileState { - const next: TransferProfileState = { +export function removeSourceRepo(state: PersistedState, repoId: string): PersistedState { + const next: PersistedState = { ...state, repos: state.repos.filter((repo) => repo.id !== repoId), sparsePresetsByRepo: { ...state.sparsePresetsByRepo }, @@ -47,7 +42,7 @@ export function removeSourceRepo( return rebuildRepoBackedProjectState(next) } -function removeRepoWorktreeMetadata(state: TransferProfileState, repoId: string): void { +function removeRepoWorktreeMetadata(state: PersistedState, repoId: string): void { for (const key of Object.keys(state.worktreeMeta)) { if (isRepoWorktreeId(repoId, key)) { delete state.worktreeMeta[key] diff --git a/src/main/orca-profiles/profile-project-state-file.ts b/src/main/orca-profiles/project-transfer/profile-project-state-file.ts similarity index 83% rename from src/main/orca-profiles/profile-project-state-file.ts rename to src/main/orca-profiles/project-transfer/profile-project-state-file.ts index e85b6ffc680..c4cb88ca3dc 100644 --- a/src/main/orca-profiles/profile-project-state-file.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-state-file.ts @@ -1,38 +1,37 @@ import { existsSync, readFileSync } from 'node:fs' import { homedir } from 'node:os' -import { getDefaultPersistedState, getDefaultWorkspaceSession } from '../../shared/constants' -import { projectHostSetupProjectionFromRepos } from '../../shared/project-host-setup-projection' +import { getDefaultPersistedState, getDefaultWorkspaceSession } from '../../../shared/constants' +import { projectHostSetupProjectionFromRepos } from '../../../shared/project-host-setup-projection' import { normalizeProjectHostSetupRows, normalizeProjectRows -} from '../../shared/project-catalog-row-normalization' -import { carryProjectStateThroughIdentityChange } from '../../shared/project-identity-succession' -import type { PersistedState } from '../../shared/persisted-state-types' -import type { Project, ProjectHostSetup } from '../../shared/project-types' -import type { Repo } from '../../shared/repo-types' -import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' -import type { SparsePreset } from '../../shared/worktree/create-types' -import type { RetiredNameRegistry } from '../../shared/worktree/retired-name-registry' -import { getOrcaProfileDataFile, getOrcaProfileStateDatabaseFile } from './profile-index-store' +} from '../../../shared/project-catalog-row-normalization' +import { carryProjectStateThroughIdentityChange } from '../../../shared/project-identity-succession' +import type { PersistedState } from '../../../shared/persisted-state-types' +import type { Project, ProjectHostSetup } from '../../../shared/project-types' +import type { Repo } from '../../../shared/repo-types' +import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import type { SparsePreset } from '../../../shared/worktree/create-types' +import type { RetiredNameRegistry } from '../../../shared/worktree/retired-name-registry' +import '../profile-index-store' +import { getOrcaProfileDataFile, getOrcaProfileStateDatabaseFile } from '../profile-storage-paths' import { importProfileStateJson, profileStateJsonMatchesAcceptance, - readProfileStateRevision, readProfileStateSnapshot -} from '../persistence/profile-state/profile-state-documents' +} from '../../persistence/profile-state/profile-state-documents' +import { readProfileStateRevision } from '../../persistence/profile-state/profile-state-revision' import { openProfileStateDatabase, openProfileStateDatabaseReadOnly -} from '../persistence/profile-state/profile-state-database' -import { parseProfileStateRoot } from '../persistence/profile-state/profile-state-document-validation' -import { assertProfileStateCanInitialize } from '../persistence/profile-state/profile-state-recovery-required' -import { hasProfileStateDatabaseFiles } from '../persistence/profile-state/profile-state-storage-classification' -import { ensureProfileStateAuthorityMarker } from '../persistence/profile-state/profile-state-authority-marker' - -export type TransferProfileState = PersistedState +} from '../../persistence/profile-state/profile-state-database' +import { parseProfileStateRoot } from '../../persistence/profile-state/profile-state-document-validation' +import { assertProfileStateCanInitialize } from '../../persistence/profile-state/profile-state-recovery-required' +import { hasProfileStateDatabaseFiles } from '../../persistence/profile-state/profile-state-storage-classification' +import { ensureProfileStateAuthorityMarker } from '../../persistence/profile-state/profile-state-authority-marker' export type ReadProfileStateResult = { - state: TransferProfileState + state: PersistedState /** Snapshot revision; absent for legacy JSON. */ revision?: number /** Exact compact snapshot JSON. */ @@ -107,16 +106,14 @@ export function readProfileStateWithRevision( } } -function parseProfileState(rawJson: string | undefined): TransferProfileState { +function parseProfileState(rawJson: string | undefined): PersistedState { if (rawJson === undefined) { return structuredClone(getDefaultPersistedState(homedir())) } return normalizeProfileProjectState(parseProfileStateRoot(rawJson)) } -export function normalizeProfileProjectState( - parsed: Partial -): TransferProfileState { +export function normalizeProfileProjectState(parsed: Partial): PersistedState { const defaults = getDefaultPersistedState(homedir()) const { uiLanguagePortugueseMigrationApplied: _migrationApplied, @@ -188,14 +185,14 @@ function recordOrEmpty(value: unknown): Record { return isRecord(value) ? value : {} } -export function readProfileState(profileId: string, userDataPath: string): TransferProfileState { +export function readProfileState(profileId: string, userDataPath: string): PersistedState { return readProfileStateWithRevision(profileId, userDataPath).state } export function writeProfileState( profileId: string, userDataPath: string, - state: TransferProfileState, + state: PersistedState, options: { expectedRevision?: number } = {} ): void { writeSerializedProfileState(profileId, userDataPath, JSON.stringify(state), options) @@ -230,7 +227,7 @@ function isRepoBackedProjectHostSetup( return Boolean(setup.repoId && currentRepoIds.has(setup.repoId)) } -export function rebuildRepoBackedProjectState(state: TransferProfileState): TransferProfileState { +export function rebuildRepoBackedProjectState(state: PersistedState): PersistedState { const projection = projectHostSetupProjectionFromRepos(state.repos) const succession = carryProjectStateThroughIdentityChange(projection.projects, state.projects) const currentRepoIds = new Set(state.repos.map((repo) => repo.id)) diff --git a/src/main/orca-profiles/profile-project-transfer-migration.test.ts b/src/main/orca-profiles/project-transfer/profile-project-transfer-migration.test.ts similarity index 91% rename from src/main/orca-profiles/profile-project-transfer-migration.test.ts rename to src/main/orca-profiles/project-transfer/profile-project-transfer-migration.test.ts index 2d6ece4429a..7a955edfd81 100644 --- a/src/main/orca-profiles/profile-project-transfer-migration.test.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-transfer-migration.test.ts @@ -10,23 +10,23 @@ import { import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDefaultPersistedState } from '../../shared/constants' -import { ORCA_PROFILE_INDEX_SCHEMA_VERSION } from '../../shared/orca-profiles' -import type { Repo } from '../../shared/repo-types' -import * as profileStateDocuments from '../persistence/profile-state/profile-state-documents' -import { openProfileStateDatabase } from '../persistence/profile-state/profile-state-database' -import { ProfileStateSqliteAuthority } from '../persistence/profile-state/profile-state-sqlite-authority' +import { getDefaultPersistedState } from '../../../shared/constants' +import { ORCA_PROFILE_INDEX_SCHEMA_VERSION } from '../../../shared/orca-profiles' +import type { Repo } from '../../../shared/repo-types' +import * as profileStateDocuments from '../../persistence/profile-state/profile-state-documents' +import { openProfileStateDatabase } from '../../persistence/profile-state/profile-state-database' +import { ProfileStateSqliteAuthority } from '../../persistence/profile-state/profile-state-sqlite-authority' import { createProfileStateDatabaseBackupId, profileStateDatabaseBackupPath -} from '../persistence/profile-state/profile-state-backup-path' +} from '../../persistence/profile-state/profile-state-backup-path' import { transferOrcaProfileProject } from './profile-project-transfer' import { readProfileStateWithRevision, writeSerializedProfileState } from './profile-project-state-file' -vi.mock('../persistence/loading-store/store', () => { +vi.mock('../../persistence/loading-store/store', () => { throw new Error('Profile transfers must not load inactive Stores') }) diff --git a/src/main/orca-profiles/profile-project-transfer-migration.ts b/src/main/orca-profiles/project-transfer/profile-project-transfer-migration.ts similarity index 87% rename from src/main/orca-profiles/profile-project-transfer-migration.ts rename to src/main/orca-profiles/project-transfer/profile-project-transfer-migration.ts index 1b380030c65..1945d29e77e 100644 --- a/src/main/orca-profiles/profile-project-transfer-migration.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-transfer-migration.ts @@ -1,5 +1,5 @@ -import { migrateProfileStateToSqlite } from '../persistence/profile-state/profile-state-migration' -import { getOrcaProfileDataFile, getOrcaProfileStateDatabaseFile } from './profile-storage-paths' +import { migrateProfileStateToSqlite } from '../../persistence/profile-state/profile-state-migration' +import { getOrcaProfileDataFile, getOrcaProfileStateDatabaseFile } from '../profile-storage-paths' import type { ReadProfileStateResult } from './profile-project-state-file' import { readProfileProjectTransferState, diff --git a/src/main/orca-profiles/profile-project-transfer-payload.ts b/src/main/orca-profiles/project-transfer/profile-project-transfer-payload.ts similarity index 88% rename from src/main/orca-profiles/profile-project-transfer-payload.ts rename to src/main/orca-profiles/project-transfer/profile-project-transfer-payload.ts index bad79a71920..8d48800ad20 100644 --- a/src/main/orca-profiles/profile-project-transfer-payload.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-transfer-payload.ts @@ -1,21 +1,18 @@ import { randomUUID } from 'node:crypto' -import { getRepoExecutionHostId, type ExecutionHostId } from '../../shared/execution-host' -import { projectHostSetupProjectionFromRepos } from '../../shared/project-host-setup-projection' -import type { SshTarget } from '../../shared/ssh-types' -import type { WorkspaceKey } from '../../shared/workspace-scope' -import type { PersistedState } from '../../shared/persisted-state-types' -import type { Repo } from '../../shared/repo-types' -import type { SparsePreset } from '../../shared/worktree/create-types' -import type { RetiredNameRegistry } from '../../shared/worktree/retired-name-registry' +import { getRepoExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' +import { projectHostSetupProjectionFromRepos } from '../../../shared/project-host-setup-projection' +import type { SshTarget } from '../../../shared/ssh-types' +import type { WorkspaceKey } from '../../../shared/workspace-scope' +import type { PersistedState } from '../../../shared/persisted-state-types' +import type { Repo } from '../../../shared/repo-types' +import type { SparsePreset } from '../../../shared/worktree/create-types' +import type { RetiredNameRegistry } from '../../../shared/worktree/retired-name-registry' import { extractRetiredNameRegistriesByNamespace, mergeRetiredNameRegistryMaps } from './profile-project-retired-name-transfer' -import { - type TransferProfileState, - rebuildRepoBackedProjectState -} from './profile-project-state-file' +import { rebuildRepoBackedProjectState } from './profile-project-state-file' import { mergeHostWorkspaceSessions, mergeWorkspaceSessions } from './profile-project-session-state' import { extractHostSessionsForTransfer, @@ -27,7 +24,7 @@ import { rekeyWorktreeId, rekeyWorkspaceKey } from './profile-project-worktree-identity' -import { assertNoCrossStoreLinkedWorkspaceInMove } from '../../shared/worktree/cross-store-lineage-move-refusal' +import { assertNoCrossStoreLinkedWorkspaceInMove } from '../../../shared/worktree/cross-store-lineage-move-refusal' export type TransferPayload = { repo: Repo @@ -46,7 +43,7 @@ export type TransferPayload = { export function createTargetRepo( sourceRepo: Repo, - targetState: TransferProfileState, + targetState: PersistedState, copy: boolean ): Repo { const targetRepoId = @@ -63,7 +60,7 @@ export function createTargetRepo( return repo } -function createUniqueRepoId(state: TransferProfileState): string { +function createUniqueRepoId(state: PersistedState): string { const existingRepoIds = new Set(state.repos.map((repo) => repo.id)) let candidate = randomUUID() while (existingRepoIds.has(candidate)) { @@ -131,7 +128,7 @@ function rekeyWorkspaceLineageRecord( } export function assertRepoHasNoCrossStoreLinkedWorkspace( - state: TransferProfileState, + state: PersistedState, repoId: string ): void { assertNoCrossStoreLinkedWorkspaceInMove(state, (childKey) => @@ -140,7 +137,7 @@ export function assertRepoHasNoCrossStoreLinkedWorkspace( } export function createTransferPayload(args: { - sourceState: TransferProfileState + sourceState: PersistedState sourceRepo: Repo targetRepo: Repo includeSessions: boolean @@ -209,10 +206,10 @@ export function createTransferPayload(args: { } export function applyPayloadToTarget( - targetState: TransferProfileState, + targetState: PersistedState, payload: TransferPayload -): TransferProfileState { - const next: TransferProfileState = { +): PersistedState { + const next: PersistedState = { ...targetState, repos: [...targetState.repos, payload.repo], sparsePresetsByRepo: { diff --git a/src/main/orca-profiles/profile-project-transfer-worktree-ids.ts b/src/main/orca-profiles/project-transfer/profile-project-transfer-worktree-ids.ts similarity index 89% rename from src/main/orca-profiles/profile-project-transfer-worktree-ids.ts rename to src/main/orca-profiles/project-transfer/profile-project-transfer-worktree-ids.ts index 6c17dd172e0..6848f8cce60 100644 --- a/src/main/orca-profiles/profile-project-transfer-worktree-ids.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-transfer-worktree-ids.ts @@ -1,17 +1,14 @@ -import type { PersistedState } from '../../shared/persisted-state-types' -import { parseWorkspaceKey } from '../../shared/workspace-scope' -import type { TransferProfileState } from './profile-project-state-file' +import type { PersistedState } from '../../../shared/persisted-state-types' +import { parseWorkspaceKey } from '../../../shared/workspace-scope' + import { isRepoWorktreeId } from './profile-project-worktree-identity' import { getWorktreeIdFromHostIdentity, isWorktreeHostIdentity -} from '../../shared/worktree/host-qualified-identity' +} from '../../../shared/worktree/host-qualified-identity' /** Include session/UI-only worktrees so transfer cannot strand their state. */ -export function collectTransferWorktreeIds( - state: TransferProfileState, - repoId: string -): Set { +export function collectTransferWorktreeIds(state: PersistedState, repoId: string): Set { const ids = new Set() const add = (value: string | null | undefined): void => { if (value && isRepoWorktreeId(repoId, value)) { diff --git a/src/main/orca-profiles/profile-project-transfer.test.ts b/src/main/orca-profiles/project-transfer/profile-project-transfer.test.ts similarity index 95% rename from src/main/orca-profiles/profile-project-transfer.test.ts rename to src/main/orca-profiles/project-transfer/profile-project-transfer.test.ts index 29e659b270b..e63958d6fc5 100644 --- a/src/main/orca-profiles/profile-project-transfer.test.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-transfer.test.ts @@ -2,24 +2,24 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import { tmpdir } from 'node:os' import { join } from 'node:path' import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest' -import { getDefaultPersistedState } from '../../shared/constants' +import { getDefaultPersistedState } from '../../../shared/constants' import { ORCA_PROFILE_INDEX_SCHEMA_VERSION, type OrcaProfileIndex -} from '../../shared/orca-profiles' -import type { PersistedState } from '../../shared/persisted-state-types' -import type { Repo } from '../../shared/repo-types' +} from '../../../shared/orca-profiles' +import type { PersistedState } from '../../../shared/persisted-state-types' +import type { Repo } from '../../../shared/repo-types' import { exportProfileStateJson, hashProfileStateJson, importProfileStateJson -} from '../persistence/profile-state/profile-state-documents' -import { openProfileStateDatabase } from '../persistence/profile-state/profile-state-database' +} from '../../persistence/profile-state/profile-state-documents' +import { openProfileStateDatabase } from '../../persistence/profile-state/profile-state-database' import { persistProfileProjectMoveIntent, - recoverPendingProfileProjectMoves, - type ProfileProjectMoveIntent + recoverPendingProfileProjectMoves } from './profile-project-move-intent' +import type { ProfileProjectMoveIntent } from './profile-project-move-record' import type { ReadProfileStateResult } from './profile-project-state-file' function createProfileProjectMoveIntent(args: { diff --git a/src/main/orca-profiles/profile-project-transfer.ts b/src/main/orca-profiles/project-transfer/profile-project-transfer.ts similarity index 94% rename from src/main/orca-profiles/profile-project-transfer.ts rename to src/main/orca-profiles/project-transfer/profile-project-transfer.ts index 20226c7e0c5..3e872ff2938 100644 --- a/src/main/orca-profiles/profile-project-transfer.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-transfer.ts @@ -1,12 +1,9 @@ import type { TransferOrcaProfileProjectArgs, TransferOrcaProfileProjectResult -} from '../../shared/orca-profiles' -import { - getOrcaProfileIndexPath, - getOrcaProfileListState, - readProfileIndex -} from './profile-index-store' +} from '../../../shared/orca-profiles' +import { getOrcaProfileListState, readProfileIndex } from '../profile-index-store' +import { getOrcaProfileIndexPath } from '../profile-storage-paths' import { readProfileProjectTransferState, writeProfileProjectDomainChanges @@ -28,9 +25,9 @@ import { migrateProfileProjectTransferParticipant } from './profile-project-tran import { persistProfileProjectMoveIntent, recoverPendingProfileProjectMoves, - removeProfileProjectMoveIntent, - type ProfileProjectMoveIntent + removeProfileProjectMoveIntent } from './profile-project-move-intent' +import type { ProfileProjectMoveIntent } from './profile-project-move-record' function assertKnownProfiles(args: TransferOrcaProfileProjectArgs, userDataPath: string): void { const profiles = getOrcaProfileListState(userDataPath).profiles diff --git a/src/main/orca-profiles/profile-project-worktree-identity.ts b/src/main/orca-profiles/project-transfer/profile-project-worktree-identity.ts similarity index 87% rename from src/main/orca-profiles/profile-project-worktree-identity.ts rename to src/main/orca-profiles/project-transfer/profile-project-worktree-identity.ts index 4ae58b136a8..604956bc91e 100644 --- a/src/main/orca-profiles/profile-project-worktree-identity.ts +++ b/src/main/orca-profiles/project-transfer/profile-project-worktree-identity.ts @@ -1,18 +1,18 @@ -import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' -import { getRepoExecutionHostId } from '../../shared/execution-host' +import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path' +import { getRepoExecutionHostId } from '../../../shared/execution-host' -import type { Repo } from '../../shared/repo-types' +import type { Repo } from '../../../shared/repo-types' import { type WorkspaceKey, parseWorkspaceKey, worktreeWorkspaceKey -} from '../../shared/workspace-scope' -import '../../shared/worktree/id' -import { WORKTREE_ID_SEPARATOR } from '../../shared/terminal/pty/lifecycle/pty-session-id-format' +} from '../../../shared/workspace-scope' +import '../../../shared/worktree/id' +import { WORKTREE_ID_SEPARATOR } from '../../../shared/terminal/pty/lifecycle/pty-session-id-format' import { getWorktreeIdFromHostIdentity, isWorktreeHostIdentity -} from '../../shared/worktree/host-qualified-identity' +} from '../../../shared/worktree/host-qualified-identity' export function repoPhysicalKey( repo: Pick diff --git a/src/main/orca-profiles/profile-session-markdown-transfer.ts b/src/main/orca-profiles/project-transfer/profile-session-markdown-transfer.ts similarity index 92% rename from src/main/orca-profiles/profile-session-markdown-transfer.ts rename to src/main/orca-profiles/project-transfer/profile-session-markdown-transfer.ts index eeb38e98725..76c98ff1d34 100644 --- a/src/main/orca-profiles/profile-session-markdown-transfer.ts +++ b/src/main/orca-profiles/project-transfer/profile-session-markdown-transfer.ts @@ -1,5 +1,5 @@ -import type { WorkspaceSessionState } from '../../shared/workspace-session/workspace-session-state-types' -import { ownedEditorFileId } from '../../shared/workspace-session/workspace-session-pane-ownership' +import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' +import { ownedEditorFileId } from '../../../shared/workspace-session/workspace-session-pane-ownership' type OwnerProjection = { mapOwnerKey: (ownerKey: string) => string | null diff --git a/src/main/orca-profiles/profile-session-owner-transfer.ts b/src/main/orca-profiles/project-transfer/profile-session-owner-transfer.ts similarity index 91% rename from src/main/orca-profiles/profile-session-owner-transfer.ts rename to src/main/orca-profiles/project-transfer/profile-session-owner-transfer.ts index 90c285f6d53..c1505597a6d 100644 --- a/src/main/orca-profiles/profile-session-owner-transfer.ts +++ b/src/main/orca-profiles/project-transfer/profile-session-owner-transfer.ts @@ -1,22 +1,18 @@ -import { getDefaultWorkspaceSession } from '../../shared/constants' -import type { SleepingAgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-resume' -import type { BrowserPage, BrowserWorkspace } from '../../shared/browser-workspace-types' -import { remapBrowserPageDocLocation } from '../../shared/browser-page-doc-location' -import type { Tab, TabGroup } from '../../shared/tab-types' -import type { TerminalTab } from '../../shared/workspace-layout/terminal-tab-types' +import { getDefaultWorkspaceSession } from '../../../shared/constants' +import type { SleepingAgentSessionRecord } from '../../../shared/agent-session/lifecycle/agent-session-resume' +import type { BrowserPage, BrowserWorkspace } from '../../../shared/browser-workspace-types' +import { remapBrowserPageDocLocation } from '../../../shared/browser-page-doc-location' +import type { Tab, TabGroup } from '../../../shared/tab-types' +import type { TerminalTab } from '../../../shared/workspace-layout/terminal-tab-types' import type { PersistedOpenFile, WorkspaceSessionState -} from '../../shared/workspace-session/workspace-session-state-types' -import { isWorkspaceKey } from '../../shared/workspace-scope' +} from '../../../shared/workspace-session/workspace-session-state-types' +import { isWorkspaceKey } from '../../../shared/workspace-scope' import { SESSION_FIELDS_COPIED_BY_OWNER_KEY } from './profile-project-session-field-disposition' import { mapMarkdownFrontmatterVisible } from './profile-session-markdown-transfer' -export { - buildMarkdownFrontmatterIdMap, - markdownFileIdCandidates -} from './profile-session-markdown-transfer' -import { paneBelongsToTabs } from '../../shared/workspace-session/workspace-session-pane-ownership' +import { paneBelongsToTabs } from '../../../shared/workspace-session/workspace-session-pane-ownership' export type SessionOwnerProjection = { mapOwnerKey: (ownerKey: string) => string | null diff --git a/src/main/orca-profiles/storage/new-profile-state.test.ts b/src/main/orca-profiles/storage/new-profile-state.test.ts new file mode 100644 index 00000000000..42ae15f51f3 --- /dev/null +++ b/src/main/orca-profiles/storage/new-profile-state.test.ts @@ -0,0 +1,83 @@ +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { removeTreeSync } from '../../../shared/windows-transient-lock-removal' +import type { PersistedState } from '../../../shared/persisted-state-types' +import '../../../shared/worktree/id' +import '../../../shared/workspace-scope' +import '../../persistence/profile-state/profile-state-access' +import * as database from '../../persistence/profile-state/profile-state-database' +import { exportProfileStateJson } from '../../persistence/profile-state/profile-state-documents' +import '../../persistence/profile-state/profile-state-store-factory' +import '../profile-index-store' +import { getOrcaProfileDataFile, getOrcaProfileStateDatabaseFile } from '../profile-storage-paths' +import { initializeNewOrcaProfileState } from './new-profile-state' + +const telemetry = { + optedIn: false, + installId: 'retained-install-id', + existedBeforeTelemetryRelease: true +} +let root: string +const profileId = 'new-profile' + +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'orca-profile-consent-')) +}) + +afterEach(() => { + vi.restoreAllMocks() + removeTreeSync(root) +}) + +function readPublishedState(): PersistedState { + const opened = database.openProfileStateDatabaseReadOnly( + getOrcaProfileStateDatabaseFile(profileId, root), + profileId + ) + try { + const state: PersistedState = JSON.parse(exportProfileStateJson(opened.db)) + return state + } finally { + opened.db.close() + } +} + +describe('new desktop profile initialization', () => { + it('starts an inherited install with its own existing-profile milestone state', () => { + initializeNewOrcaProfileState( + profileId, + { + optedIn: true, + installId: 'retained-install-id', + existedBeforeTelemetryRelease: false, + protectedMilestones: { + installCohort: 'fresh', + firstAgentInteractionDay: 20_766, + meaningfulActivityDay: 20_766 + } + }, + root + ) + + expect(readPublishedState().settings.telemetry).toEqual({ + optedIn: true, + installId: 'retained-install-id', + existedBeforeTelemetryRelease: false, + protectedMilestones: { installCohort: 'existing' } + }) + }) + + it('preserves existing JSON as input for its later import', () => { + const path = getOrcaProfileDataFile(profileId, root) + const original = '{"settings":{"telemetry":{"installId":"older"}}}' + mkdirSync(dirname(path), { recursive: true }) + writeFileSync(path, original) + + initializeNewOrcaProfileState(profileId, telemetry, root) + + expect(readFileSync(path, 'utf8')).toBe(original) + expect(existsSync(getOrcaProfileStateDatabaseFile(profileId, root))).toBe(false) + }) +}) diff --git a/src/main/orca-profiles/new-profile-state.ts b/src/main/orca-profiles/storage/new-profile-state.ts similarity index 70% rename from src/main/orca-profiles/new-profile-state.ts rename to src/main/orca-profiles/storage/new-profile-state.ts index d4d27a6de73..2b1d588efbf 100644 --- a/src/main/orca-profiles/new-profile-state.ts +++ b/src/main/orca-profiles/storage/new-profile-state.ts @@ -1,24 +1,25 @@ import { existsSync } from 'node:fs' import { homedir } from 'node:os' -import { getDefaultPersistedState } from '../../shared/constants' -import type { GlobalSettings } from '../../shared/global-settings-types' -import { createInitialHomeWorkspaceState } from '../persistence/loading-store/initial-home-workspace' -import { LoadedCohortMigrationOperations } from '../persistence/loading-store/loaded-cohort-migrations' -import { acquireProfileStateRuntimeAdmission } from '../persistence/profile-state/profile-state-access' -import { isProfileStateSqliteAvailable } from '../persistence/profile-state/profile-state-database' -import { migrateProfileStateToSqlite } from '../persistence/profile-state/profile-state-migration' +import { getDefaultPersistedState } from '../../../shared/constants' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import { createInitialHomeWorkspaceState } from '../../persistence/loading-store/initial-home-workspace' +import { LoadedCohortMigrationOperations } from '../../persistence/loading-store/loaded-cohort-migrations' +import { acquireProfileStateRuntimeAdmission } from '../../persistence/profile-state/profile-state-access' +import '../../persistence/profile-state/profile-state-database' +import { isSqliteAvailable } from '../../sqlite/sync-database' +import { migrateProfileStateToSqlite } from '../../persistence/profile-state/profile-state-migration' import { getOrcaProfileDataFile, getOrcaProfileStateDatabaseFile, getProfileUserDataPath -} from './profile-storage-paths' +} from '../profile-storage-paths' export function initializeNewOrcaProfileState( profileId: string, telemetry: GlobalSettings['telemetry'], userDataPath = getProfileUserDataPath() ): void { - if (!isProfileStateSqliteAvailable()) { + if (!isSqliteAvailable()) { throw new Error('Creating profile state requires the bundled Orca runtime.') } const admission = acquireProfileStateRuntimeAdmission(userDataPath) diff --git a/src/main/orca-profiles/profile-legacy-state-import.ts b/src/main/orca-profiles/storage/profile-legacy-state-import.ts similarity index 97% rename from src/main/orca-profiles/profile-legacy-state-import.ts rename to src/main/orca-profiles/storage/profile-legacy-state-import.ts index b08c4bd2123..6bbfcae22de 100644 --- a/src/main/orca-profiles/profile-legacy-state-import.ts +++ b/src/main/orca-profiles/storage/profile-legacy-state-import.ts @@ -8,7 +8,7 @@ import { legacyBrowserSessionMetaPath, legacyDataFilePath, profileBackupPath -} from './profile-storage-paths' +} from '../profile-storage-paths' function copyIfPresent(source: string, target: string): void { if (!existsSync(source) || existsSync(target)) { diff --git a/src/main/orca-profiles/profile-persistence-deadline.ts b/src/main/orca-profiles/storage/profile-persistence-deadline.ts similarity index 83% rename from src/main/orca-profiles/profile-persistence-deadline.ts rename to src/main/orca-profiles/storage/profile-persistence-deadline.ts index 316b7871235..113e89fd443 100644 --- a/src/main/orca-profiles/profile-persistence-deadline.ts +++ b/src/main/orca-profiles/storage/profile-persistence-deadline.ts @@ -1,6 +1,6 @@ -import type { Store } from '../persistence/loading-store/store' -import type { ProfileStateMaintenance } from '../persistence/loading-store/profile-state-authority' -import type { ProfileStateMaintenanceOptions } from '../persistence/loading-store/profile-state-maintenance' +import type { Store } from '../../persistence/loading-store/store' +import type { ProfileStateMaintenance } from '../../persistence/loading-store/profile-state-authority' +import type { ProfileStateMaintenanceOptions } from '../../persistence/loading-store/profile-state-maintenance' const PROFILE_PERSISTENCE_TIMEOUT_MS = 60_000 diff --git a/src/main/orcad/orcad-host-account-launch-env-store.test.ts b/src/main/orcad/orcad-host-account-launch-env-store.test.ts deleted file mode 100644 index 3edda96aaee..00000000000 --- a/src/main/orcad/orcad-host-account-launch-env-store.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { - readOrcadHostAccountLaunchEnv, - restoreOrcadHostAccountLaunchEnv -} from './orcad-host-account-launch-env-store' -import { RuntimeAccountController } from '../runtime/agent-session/environment/runtime-account-controller' - -const dirs: string[] = [] -function userData(): string { - const dir = mkdtempSync(join(tmpdir(), 'orcad-host-accounts-')) - dirs.push(dir) - return dir -} - -afterEach(() => { - for (const dir of dirs.splice(0)) { - rmSync(dir, { recursive: true, force: true }) - } -}) - -describe('orcad host account launch env store', () => { - it('reads nothing from a missing, corrupt or unsafe file', () => { - const dir = userData() - expect(readOrcadHostAccountLaunchEnv(dir)).toBeNull() - writeFileSync(join(dir, 'host-account-launch-env.json'), '{not json') - expect(readOrcadHostAccountLaunchEnv(dir)).toBeNull() - writeFileSync( - join(dir, 'host-account-launch-env.json'), - JSON.stringify({ wslDistro: 'Ubuntu', claude: { PATH: '/evil' }, terminal: {} }) - ) - expect(readOrcadHostAccountLaunchEnv(dir)).toBeNull() - }) - - it("holds a fresh WSL host's first agent launch for the desktop's push, and nowhere else", async () => { - for (const isWslHost of [true, false]) { - const accounts = new RuntimeAccountController() - restoreOrcadHostAccountLaunchEnv( - { restoreHostAccountLaunchEnv: accounts.restoreHostLaunchEnv.bind(accounts) }, - userData(), - () => isWslHost - ) - let launched = false - void accounts.prepareHostAgentLaunch(null).then(() => { - launched = true - }) - await Promise.resolve() - await Promise.resolve() - expect(launched).toBe(!isWslHost) - accounts.setHostLaunchEnv({ wslDistro: 'Ubuntu', claude: {}, terminal: {} }) - } - }) -}) diff --git a/src/main/orcad/orcad-profile-state-startup.ts b/src/main/orcad/orcad-profile-state-startup.ts index 5cbcd3be895..8188609c452 100644 --- a/src/main/orcad/orcad-profile-state-startup.ts +++ b/src/main/orcad/orcad-profile-state-startup.ts @@ -1,6 +1,7 @@ import { createProfileStateStoreForStartup } from '../persistence/profile-state/profile-state-startup-authority' import type { ProfileStateStoreFactoryResult } from '../persistence/profile-state/profile-state-store-factory' -import { ensureActiveOrcaProfile, initOrcaProfilePaths } from '../orca-profiles/profile-index-store' +import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' +import { initOrcaProfilePaths } from '../orca-profiles/profile-storage-paths' import { initSshHostKeyStoreFile } from '../ssh/host-keys/ssh-host-key-store' import { initOrcadHeldFenceTokenFile } from '../managed-server/activation/orcad-held-fence-tokens' import { emitOrcadProfileStateAuthoritySelected } from './orcad-profile-state-telemetry' diff --git a/src/main/persistence/loading-store/profile-state-checkpoints.test.ts b/src/main/persistence/loading-store/profile-state-checkpoints.test.ts index 97764f71c7d..7774b07cfe6 100644 --- a/src/main/persistence/loading-store/profile-state-checkpoints.test.ts +++ b/src/main/persistence/loading-store/profile-state-checkpoints.test.ts @@ -8,7 +8,6 @@ import { parseProfileStateRoot } from '../profile-state/profile-state-document-v import { readProfileStateSnapshot } from '../profile-state/profile-state-documents' import { ProfileStateSqliteAuthority } from '../profile-state/profile-state-sqlite-authority' import { Store } from './store' -import { scheduleSave } from './write-scheduling' vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) vi.mock('../../telemetry/cohort-classifier', () => ({ @@ -72,29 +71,6 @@ const EXPECTED_CHECKPOINT = { } describe('complete profile state checkpoints', () => { - it.each(['sync', 'async'] as const)( - 'rejects a stale %s checkpoint even when the local hash is unchanged', - async (mode) => { - const { store, directory, readState } = fixture() - const other = new ProfileStateSqliteAuthority(join(directory, 'profile-state.db'), PROFILE_ID) - try { - other.readSerializedState() - other.writeSerializedDomains([{ domain: 'futureDomain', payload: '{"external":true}' }]) - scheduleSave(store, ['ui']) - if (mode === 'sync') { - expect(() => store.flushOrThrow()).toThrow(/Profile state revision changed/) - } else { - await expect(store.flushPendingOrThrowAsync()).rejects.toThrow( - /Profile state revision changed/ - ) - } - expect(readState()).toMatchObject({ futureDomain: { external: true } }) - } finally { - other.close() - } - } - ) - it('takes the final checkpoint after an earlier queued writer clears its dirty domains', async () => { const { store, backup, readState } = fixture() store.updateSettings({ theme: 'light' }) @@ -111,18 +87,4 @@ describe('complete profile state checkpoints', () => { expect(readState()).toMatchObject(EXPECTED_CHECKPOINT) }) - - it('does not write a frozen profile when final persistence requests a checkpoint', async () => { - const { store, authority, readState } = fixture() - const before = readState() - const fullWrite = vi.spyOn(authority, 'writeSerializedState') - mutateThroughGetters(store) - store.updateSettings({ theme: 'dark' }) - store.freezeWrites() - - await store.flushAsync() - - expect(fullWrite).not.toHaveBeenCalled() - expect(readState()).toEqual(before) - }) }) diff --git a/src/main/persistence/loading-store/profile-state-store-backups.test.ts b/src/main/persistence/loading-store/profile-state-store-backups.test.ts deleted file mode 100644 index f7d6fbedfed..00000000000 --- a/src/main/persistence/loading-store/profile-state-store-backups.test.ts +++ /dev/null @@ -1,176 +0,0 @@ -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { flushActiveProfileBeforeFileMutation } from '../../orca-profiles/profile-persistence-deadline' -import { openProfileStateDatabaseReadOnly } from '../profile-state/profile-state-database' -import { readProfileStateSnapshot } from '../profile-state/profile-state-documents' -import { profileStateDatabaseBackups } from '../profile-state/profile-state-backup-path' -import * as backupExecution from '../profile-state/profile-state-backup-worker' -import { ProfileStateSqliteAuthority } from '../profile-state/profile-state-sqlite-authority' -import { Store } from './store' - -vi.mock('electron', () => ({ - app: { - getPath: () => tmpdir(), - getName: () => 'orca-test', - getVersion: () => '0.0.0-test', - isPackaged: false, - on: () => {}, - whenReady: () => Promise.resolve() - }, - safeStorage: { - isEncryptionAvailable: () => true, - encryptString: (value: string) => Buffer.from(`encrypted:${value}`), - decryptString: (value: Buffer) => value.toString().slice('encrypted:'.length) - }, - ipcMain: { on: () => {}, handle: () => {} }, - BrowserWindow: { getAllWindows: () => [] } -})) -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../../telemetry/cohort-classifier', () => ({ - getCohortAtEmit: () => ({ nth_repo_added: 2 }) -})) -vi.mock('../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: () => ({ hosts: [] }), - sshConfigHostsToTargets: () => [] -})) - -const PROFILE_ID = 'store-backup-test' -const HOUR = 60 * 60 * 1000 -const fixtures: { directory: string; store: Store; authority: ProfileStateSqliteAuthority }[] = [] -const releases: (() => void)[] = [] - -beforeEach(() => { - vi.spyOn(backupExecution, 'runProfileStateBackup') -}) - -afterEach(async () => { - for (const release of releases.splice(0)) { - release() - } - for (const fixture of fixtures.splice(0)) { - await fixture.authority.drainBackups() - fixture.store.freezeWrites() - await fixture.store.flushAsync() - rmSync(fixture.directory, { recursive: true, force: true }) - } - vi.restoreAllMocks() -}) - -async function fixture() { - const directory = mkdtempSync(join(tmpdir(), 'orca-store-backup-')) - const databasePath = join(directory, 'profile-state.db') - const dataFile = join(directory, 'orca-data.json') - const legacyBytes = '{"settings":{"theme":"system"},"legacy":"retained"}' - writeFileSync(dataFile, legacyBytes) - const beginning = Date.now() - const clock = vi.spyOn(Date, 'now').mockReturnValue(beginning) - const authority = new ProfileStateSqliteAuthority(databasePath, PROFILE_ID) - const store = new Store({ dataFile, profileStateAuthority: authority }) - fixtures.push({ directory, store, authority }) - store.updateSettings({ theme: 'light' }) - store.flushOrThrow() - await authority.drainBackups() - const retained = profileStateDatabaseBackups(databasePath) - expect(retained).toHaveLength(1) - const retainedBytes = readFileSync(retained[0].path) - clock.mockReturnValue(beginning + HOUR + 1) - return { - directory, - databasePath, - dataFile, - legacyBytes, - store, - authority, - retained, - retainedBytes - } -} - -function readSnapshot(path: string) { - const opened = openProfileStateDatabaseReadOnly(path, PROFILE_ID) - try { - const snapshot = readProfileStateSnapshot(opened.db) - return { revision: snapshot.revision, state: JSON.parse(snapshot.json) } - } finally { - opened.db.close() - } -} - -describe('Store automatic SQLite recovery snapshots', () => { - it('acknowledges a routine flush while the previous recovery backup is still running', async () => { - const state = await fixture() - const realSnapshot = backupExecution.runProfileStateBackup - const started = Promise.withResolvers() - const gate = Promise.withResolvers() - releases.push(gate.resolve) - vi.spyOn(backupExecution, 'runProfileStateBackup').mockImplementationOnce(async (job) => { - started.resolve() - await gate.promise - await realSnapshot(job) - }) - state.store.updateSettings({ theme: 'dark' }) - state.store.flushOrThrow() - await started.promise - state.store.patchWorkspaceSession({ activeWorktreeId: 'newer-than-backup' }) - let settled = false - const flush = state.store.flushPendingOrThrowAsync().then(() => { - settled = true - }) - await vi.waitFor(() => expect(settled).toBe(true)) - expect(readSnapshot(state.databasePath).state.workspaceSession.activeWorktreeId).toBe( - 'newer-than-backup' - ) - expect(profileStateDatabaseBackups(state.databasePath)).toHaveLength(1) - gate.resolve() - await Promise.all([flush, state.authority.drainBackups()]) - }) - - it.each(['quit', 'profile mutation'] as const)( - '%s waits for its owned backup across Store close', - async (kind) => { - const state = await fixture() - const realSnapshot = backupExecution.runProfileStateBackup - let begin: () => void = () => {} - let release: () => void = () => {} - const started = new Promise((resolve) => { - begin = resolve - }) - const gate = new Promise((resolve) => { - release = resolve - }) - releases.push(release) - vi.spyOn(backupExecution, 'runProfileStateBackup').mockImplementationOnce(async (job) => { - begin() - await gate - await realSnapshot(job) - }) - state.store.updateSettings({ theme: 'dark' }) - state.store.flushOrThrow() - await started - const drain = vi.spyOn(state.authority, 'drainBackups') - let settled = false - const barrier = ( - kind === 'quit' - ? state.store.flushAsync() - : flushActiveProfileBeforeFileMutation(state.store) - ).then(() => { - settled = true - }) - await vi.waitFor(() => expect(drain).toHaveBeenCalled()) - expect(settled).toBe(false) - state.store.freezeWrites() - expect(profileStateDatabaseBackups(state.databasePath)).toHaveLength(1) - release() - await barrier - - expect(settled).toBe(true) - const backups = profileStateDatabaseBackups(state.databasePath) - expect(backups).toHaveLength(2) - expect(readSnapshot(backups[0].path).state.settings.theme).toBe('dark') - expect(readFileSync(state.retained[0].path).equals(state.retainedBytes)).toBe(true) - expect(readFileSync(state.dataFile, 'utf8')).toBe(state.legacyBytes) - } - ) -}) diff --git a/src/main/persistence/loading-store/repo-lifecycle-operations.ts b/src/main/persistence/loading-store/repo-lifecycle-operations.ts index 98a791a0316..58c1b0c6408 100644 --- a/src/main/persistence/loading-store/repo-lifecycle-operations.ts +++ b/src/main/persistence/loading-store/repo-lifecycle-operations.ts @@ -7,7 +7,7 @@ import type { GhAccountBinding } from '../../../shared/github/account-binding' import { removeRepoFromHostWorkspaceSessions, removeRepoFromWorkspaceSession -} from '../../orca-profiles/profile-project-session-state' +} from '../../orca-profiles/project-transfer/profile-project-session-state' import { getRepoExecutionHostId, parseExecutionHostId, diff --git a/src/main/persistence/loading-store/state-serialization-secret-handling.test.ts b/src/main/persistence/loading-store/state-serialization-secret-handling.test.ts deleted file mode 100644 index b36b4d4f4fe..00000000000 --- a/src/main/persistence/loading-store/state-serialization-secret-handling.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { describe, it, expect, vi } from 'vitest' -import { getDefaultPersistedState } from '../../../shared/constants' -import { folderWorkspaceKey } from '../../../shared/workspace-scope' -import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import { ProtectedSecretPersistence } from '../../credentials/protected-secret-persistence' -import { StateSerializationSecretHandlingOperations } from './state-serialization-secret-handling' - -vi.mock('electron', () => ({ - safeStorage: { - isEncryptionAvailable: () => true, - encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'), - decryptString: (ciphertext: Buffer) => ciphertext.toString('utf-8').slice('encrypted:'.length) - } -})) - -describe('profile save serialization', () => { - it('saves every named domain exactly as a whole save does', () => { - const state = getDefaultPersistedState('/home/user') - state.settings.httpProxyUrl = 'http://proxy.example:8080' - state.ui.browserKagiSessionLink = 'https://kagi.example/session' - state.folderWorkspaces = [ - { - id: 'fw-1', - projectGroupId: 'group-1', - name: 'Refund fix', - folderPath: '/workspace/platform', - linkedTask: null, - comment: '', - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 1, - createdAt: 1, - updatedAt: 1, - diffComments: [ - { - id: 'note-1', - worktreeId: folderWorkspaceKey('fw-1'), - filePath: 'README.md', - source: 'markdown', - lineNumber: 1, - body: 'Review this', - createdAt: 100, - side: 'modified' - } - ] - } - ] - const row: WorktreeMeta = { - instanceId: 'instance-1', - hostId: 'local', - displayName: 'wt-1', - comment: 'pinned', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 1 - } - state.worktreeMeta = { 'repo-1::/work/wt-1': row } - state.worktreeMetaByIdentity = { 'wt2:local:instance-1': row } - state.worktreeIdentityAliases = { 'local::repo-1::/work/wt-1': ['wt2:local:instance-1'] } - state.sshPtyConsumerRecoveries = [ - { - targetId: 'ssh-1', - clientInstanceId: 'client-1', - serverBuildId: 'server-1', - clientGeneration: 1, - ownerGeneration: 1, - ownerLease: 'lease-secret' - } - ] - const serialization = new StateSerializationSecretHandlingOperations({ - protectedSecrets: new ProtectedSecretPersistence(), - state - }) - - const whole = serialization.buildStateToSave(true).domains! - const named = serialization.buildStateDomainsToSave(new Set(whole.map(({ domain }) => domain))) - - expect(named).toBeDefined() - expect(new Map(named!.replacements.map(({ domain, payload }) => [domain, payload]))).toEqual( - new Map(whole.map(({ domain, payload }) => [domain, payload])) - ) - }) -}) diff --git a/src/main/persistence/migrating-orcad-catalog/orcad-destination-workspace-session.ts b/src/main/persistence/migrating-orcad-catalog/orcad-destination-workspace-session.ts index c6dc57019d4..4e2ebaed427 100644 --- a/src/main/persistence/migrating-orcad-catalog/orcad-destination-workspace-session.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-destination-workspace-session.ts @@ -3,7 +3,7 @@ import { isRecord } from '../../../shared/orcad-migration/orcad-migration-manife import type { PersistedState } from '../../../shared/persisted-state-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { SESSION_FOCUS_FIELDS } from '../../../shared/workspace-session/workspace-session-host-field-ownership' -import { mergeWorkspaceSessions } from '../../orca-profiles/profile-project-session-state' +import { mergeWorkspaceSessions } from '../../orca-profiles/project-transfer/profile-project-session-state' import { collectLayoutLeafIdsInOrder } from '../restoring-sessions/terminal-layout-normalization' const MERGED_SESSION_RECORD_FIELDS = [ diff --git a/src/main/persistence/migrating-orcad-catalog/orcad-source-scope.ts b/src/main/persistence/migrating-orcad-catalog/orcad-source-scope.ts index 82b6e5f5083..761fe7255c9 100644 --- a/src/main/persistence/migrating-orcad-catalog/orcad-source-scope.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-source-scope.ts @@ -22,7 +22,7 @@ import { isWorktreeHostIdentity } from '../../../shared/worktree/host-qualified-identity' import type { Repo } from '../../../shared/repo-types' -import { ownerKeyBelongsToRepo } from '../../orca-profiles/profile-project-worktree-identity' +import { ownerKeyBelongsToRepo } from '../../orca-profiles/project-transfer/profile-project-worktree-identity' import { repoBelongsToOrcadSource } from './orcad-source-ownership' type OrcadMigrationScopeRows = { diff --git a/src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session-fragments.ts b/src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session-fragments.ts index 8ed1d2eaeb0..cba3916d4b6 100644 --- a/src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session-fragments.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session-fragments.ts @@ -1,7 +1,7 @@ import { serializeOrcadMigrationValue } from '../../../shared/orcad-migration/orcad-migration-manifest' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { mergeWorkspaceSessions } from '../../orca-profiles/profile-project-session-state' -import { SESSION_FIELDS_PRUNED_BY_OWNER_KEY } from '../../orca-profiles/profile-project-session-field-disposition' +import { mergeWorkspaceSessions } from '../../orca-profiles/project-transfer/profile-project-session-state' +import { SESSION_FIELDS_PRUNED_BY_OWNER_KEY } from '../../orca-profiles/project-transfer/profile-project-session-field-disposition' import { withRequiredWorkspaceSessionMaps } from '../loading-store/session-host-partitions' export function sessionPartitions( diff --git a/src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session-subtraction.ts b/src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session-subtraction.ts index a3a6c4f6e38..307e5860f5c 100644 --- a/src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session-subtraction.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session-subtraction.ts @@ -1,5 +1,5 @@ import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { markdownFileIdCandidates } from '../../orca-profiles/profile-session-markdown-transfer' +import { markdownFileIdCandidates } from '../../orca-profiles/project-transfer/profile-session-markdown-transfer' import { removeWorkspaceSessionOwners } from '../restoring-sessions/session-owner-removal' import { createOrcadMigrationSourceScope, diff --git a/src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session.ts b/src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session.ts index e282f8e4d08..474b50d1943 100644 --- a/src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session.ts +++ b/src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session.ts @@ -8,7 +8,7 @@ import type { OrcadMigrationTerminalScrollbackSnapshot } from '../../../shared/o import { extractSessionOwnersForTransfer, hasTransferredSessionState -} from '../../orca-profiles/profile-session-owner-transfer' +} from '../../orca-profiles/project-transfer/profile-session-owner-transfer' import type { TerminalScrollbackSnapshotStorage } from '../../pty/scrollback/terminal-scrollback-snapshots' import { createOrcadMigrationExportScope, diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-restore-hints.test.ts b/src/main/persistence/moving-wsl-projects/wsl-move-restore-hints.test.ts deleted file mode 100644 index b270346fb1f..00000000000 --- a/src/main/persistence/moving-wsl-projects/wsl-move-restore-hints.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { ColdRestoreDetection } from '../../daemon/history/restoration/terminal-history-cold-restore-info' -import { captureWslMoveRestoreHints } from './wsl-move-restore-hints' - -const restored = ( - cwd: string, - hasUnreadableRecovery = false, - cwdFromSpawn = false -): ColdRestoreDetection => ({ - status: 'restored', - sessionId: 's', - hasUnreadableRecovery, - ...(cwdFromSpawn ? { cwdFromSpawn: true as const } : {}), - restoreInfo: { - snapshotAnsi: '', - scrollbackAnsi: '', - rehydrateSequences: '', - cwd, - cols: 80, - rows: 24, - modes: { - bracketedPaste: false, - mouseTracking: false, - applicationCursor: false, - alternateScreen: false - } - } -}) - -describe('captureWslMoveRestoreHints', () => { - // Bash on the bridge reports no folder, so an open pane's checkpoint kept its - // spawn folder and `cd deep/er` reopened at the project root. - it('prefers the folder the shell was in before Sleep over the spawn folder', async () => { - const capture = await captureWslMoveRestoreHints( - { - detectColdRestoreState: async () => - restored('\\\\wsl.localhost\\Ubuntu\\home\\dev\\app', false, true) - }, - [{ paneKey: 't:a', sessionId: 'wt@@a', shellCwd: '/home/dev/app/deep/er' }], - 'Ubuntu' - ) - expect(capture.hints).toEqual([{ paneKey: 't:a', cwd: '/home/dev/app/deep/er' }]) - expect(capture.staleCwdPaneKeys).toEqual([]) - }) -}) diff --git a/src/main/persistence/persistence-async-write-syscalls.test.ts b/src/main/persistence/persistence-async-write-syscalls.test.ts index 8cbb7a85024..d14046c8f4f 100644 --- a/src/main/persistence/persistence-async-write-syscalls.test.ts +++ b/src/main/persistence/persistence-async-write-syscalls.test.ts @@ -1,63 +1,10 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -import type * as NodeFs from 'node:fs' -import type * as NodeFsPromises from 'node:fs/promises' +import { describe, it, expect, vi } from 'vitest' + import { createWorkerMaintenanceFixture, maintenanceBarrier } from './loading-store/profile-state-maintenance-fixture' import type { ProfileStateWorkerAuthority } from './profile-state/profile-state-worker-authority' - -type FilesystemCalls = { - directory: string - recording: boolean - sync: string[] - waitAsync: ((name: string, path: string) => Promise | undefined) | undefined -} - -const fsCalls = vi.hoisted((): FilesystemCalls => ({ - directory: '', - recording: false, - sync: [], - waitAsync: undefined -})) - -vi.mock('node:fs', async (importOriginal) => { - function isSynchronousFilesystemCall( - name: string, - value: unknown - ): value is (...args: unknown[]) => unknown { - return name.endsWith('Sync') && typeof value === 'function' - } - - const actual = await importOriginal() - const patched: Record = { ...actual } - for (const [name, original] of Object.entries(actual)) { - if (!isSynchronousFilesystemCall(name, original)) { - continue - } - patched[name] = Object.assign((...args: unknown[]) => { - const path = args[0] - if (fsCalls.recording && typeof path === 'string' && path.startsWith(fsCalls.directory)) { - fsCalls.sync.push(`${name}:${path}`) - } - return original(...args) - }, original) - } - return { ...patched, default: patched } -}) - -vi.mock('node:fs/promises', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - rename: async (...args: Parameters) => { - if (typeof args[0] === 'string') { - await fsCalls.waitAsync?.('rename', args[0]) - } - return actual.rename(...args) - } - } -}) vi.mock('../telemetry/client', () => ({ track: vi.fn() })) vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) @@ -67,16 +14,6 @@ vi.mock('../ssh/config/ssh-config-parser', () => ({ sshConfigHostsToTargets: () => [] })) -beforeEach(() => { - fsCalls.recording = false - fsCalls.directory = '' - fsCalls.sync = [] - fsCalls.waitAsync = undefined -}) -afterEach(() => { - fsCalls.recording = false -}) - function pauseCommit(authority: ProfileStateWorkerAuthority) { const started = maintenanceBarrier() const finish = maintenanceBarrier() @@ -96,32 +33,6 @@ function pauseCommit(authority: ProfileStateWorkerAuthority) { } describe('worker persistence avoids synchronous profile filesystem calls', () => { - it('drains a newer mutation before resolving a stable-generation barrier', async () => { - const { store, authority, readState } = await createWorkerMaintenanceFixture() - const gate = pauseCommit(authority) - store.updateUI({ sidebarWidth: 601 }) - const barrier = store.flushPendingOrThrowAsync() - await gate.started - store.updateUI({ sidebarWidth: 602 }) - gate.release() - await barrier - expect(readState().ui.sidebarWidth).toBe(602) - }) - - it('bounds a best-effort flush to its captured generation and retains later dirtiness', async () => { - const { store, authority, readState } = await createWorkerMaintenanceFixture() - const gate = pauseCommit(authority) - store.updateUI({ sidebarWidth: 621 }) - const pending = store.flushPendingAsync() - await gate.started - store.updateUI({ sidebarWidth: 622 }) - gate.release() - await pending - expect(readState().ui.sidebarWidth).toBe(621) - await store.flushPendingOrThrowAsync() - expect(readState().ui.sidebarWidth).toBe(622) - }) - it('rewrites an earlier value after a captured stale generation commits', async () => { const { store, authority, readState } = await createWorkerMaintenanceFixture() store.updateUI({ sidebarWidth: 641 }) @@ -137,34 +48,4 @@ describe('worker persistence avoids synchronous profile filesystem calls', () => await store.flushPendingOrThrowAsync({ drainToStableGeneration: false }) expect(readState().ui.sidebarWidth).toBe(641) }) - - it('retains dirty state when a SQL commit fails and persists an explicit retry', async () => { - const { store, authority, readState } = await createWorkerMaintenanceFixture() - vi.spyOn(console, 'error').mockImplementation(() => {}) - // A UI change saves only the ui domain. - vi.spyOn(authority, 'writeSerializedDomains').mockRejectedValueOnce(new Error('disk refused')) - const original = readState().ui.sidebarWidth - store.updateUI({ sidebarWidth: 511 }) - await store.flushPendingAsync() - expect(readState().ui.sidebarWidth).toBe(original) - await store.flushPendingOrThrowAsync() - expect(readState().ui.sidebarWidth).toBe(511) - }) - - it('serializes queued durable mutations and refuses a synchronous live flush', async () => { - const { store, authority, readState } = await createWorkerMaintenanceFixture() - const gate = pauseCommit(authority) - const first = store.updateSettingsAndFlush({ terminalFontSize: 17 }) - await gate.started - expect(() => store.flushOrThrow()).toThrow('awaited flush') - const second = store.updateSettingsAndFlush({ terminalFontSize: 18 }) - await Promise.resolve() - expect( - vi.mocked(authority.writeSerializedDomains).mock.calls.length + - vi.mocked(authority.writeCompleteSerializedDomains).mock.calls.length - ).toBe(1) - gate.release() - await Promise.all([first, second]) - expect(readState().settings.terminalFontSize).toBe(18) - }) }) diff --git a/src/main/persistence/profile-state/profile-state-authority-marker-writes.test.ts b/src/main/persistence/profile-state/profile-state-authority-marker-writes.test.ts index 130e3800ab5..167264b8ed1 100644 --- a/src/main/persistence/profile-state/profile-state-authority-marker-writes.test.ts +++ b/src/main/persistence/profile-state/profile-state-authority-marker-writes.test.ts @@ -1,14 +1,14 @@ -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import * as durableFileWrite from '../../filesystem/durable-file-write' -import { prepareProfileProjectDomainChanges } from '../../orca-profiles/profile-project-domain-changes' +import { prepareProfileProjectDomainChanges } from '../../orca-profiles/project-transfer/profile-project-domain-changes' import { readProfileProjectTransferState, writeProfileProjectDomainChanges -} from '../../orca-profiles/profile-project-domain-state' -import { writeSerializedProfileState } from '../../orca-profiles/profile-project-state-file' +} from '../../orca-profiles/project-transfer/profile-project-domain-state' +import { writeSerializedProfileState } from '../../orca-profiles/project-transfer/profile-project-state-file' import { hasProfileStateAuthorityMarker, profileStateAuthorityMarkerPath @@ -19,7 +19,7 @@ import { } from './profile-state-database' import { importProfileStateJson, readProfileStateSnapshot } from './profile-state-documents' import { updateAgentHookSettingsFromProfileState } from './profile-state-offline-settings' -import { profileStateDatabaseFiles } from './profile-state-storage-classification' +import './profile-state-storage-classification' const roots: string[] = [] const before = JSON.stringify({ @@ -106,21 +106,4 @@ describe.each(['hooks', 'domains', 'replay'] as const)('%s direct canonical writ expect(committed.revision).toBe(2) expect(JSON.parse(committed.json).settings.agentStatusHooksEnabled).toBe(false) }) - - it.each([false, true])('refuses lost SQL with stale JSON present=%s', (hasJson) => { - const { location, write } = fixture() - write[route]() - for (const path of profileStateDatabaseFiles(location.databaseFile)) { - rmSync(path, { force: true }) - } - if (hasJson) { - writeFileSync(location.dataFile, before) - } - expect(write[route]).toThrow() - expect(existsSync(location.databaseFile)).toBe(false) - expect(existsSync(location.dataFile)).toBe(hasJson) - if (hasJson) { - expect(readFileSync(location.dataFile, 'utf8')).toBe(before) - } - }) }) diff --git a/src/main/persistence/profile-state/profile-state-domain-writes.test.ts b/src/main/persistence/profile-state/profile-state-domain-writes.test.ts index 49040ffecb9..e0eaf2dd862 100644 --- a/src/main/persistence/profile-state/profile-state-domain-writes.test.ts +++ b/src/main/persistence/profile-state/profile-state-domain-writes.test.ts @@ -8,11 +8,7 @@ import { readProfileStateRevision } from './profile-state-documents' import { openProfileStateDatabase, profileStateDatabaseFile } from './profile-state-database' -import { - ProfileStateRevisionConflictError, - writeProfileStateDomain, - writeProfileStateDomains -} from './profile-state-domain-writes' +import { writeProfileStateDomains } from './profile-state-domain-writes' import { buildProfileStateCutoverFixture } from '../profile-state-cutover-fixture' const temporaryDirectories: string[] = [] @@ -71,32 +67,6 @@ describe('profile state dirty-domain writes', () => { } }) - it('saves a run list per-run rows cannot hold as one replacement row', () => { - const db = openTestDatabase() - try { - const fixtureRun = buildProfileStateCutoverFixture().automationRuns[0] - if (!fixtureRun) { - throw new Error('Expected automation run fixture') - } - importProfileStateJson(db, JSON.stringify({ automationRuns: [fixtureRun] }), { - now: () => 100 - }) - // Legacy histories can keep duplicate run ids, which the per-run rows refuse. - const duplicated = [fixtureRun, { ...fixtureRun, title: 'Duplicate id' }] - - expect( - writeProfileStateDomains(db, { - expectedRevision: 1, - replacements: [], - automationRunsAfter: duplicated - }) - ).toMatchObject({ changed: true, revision: 2 }) - expect(JSON.parse(exportProfileStateJson(db)).automationRuns).toEqual(duplicated) - } finally { - db.close() - } - }) - it('rolls back every domain when a later mutation fails', () => { const db = openTestDatabase() try { @@ -137,33 +107,4 @@ describe('profile state dirty-domain writes', () => { db.close() } }) - - it('fences two independently opened database writers with the shared revision', () => { - const directory = mkdtempSync(join(tmpdir(), 'orca-profile-state-domain-writer-fence-')) - temporaryDirectories.push(directory) - const databasePath = profileStateDatabaseFile(directory) - const first = openProfileStateDatabase(databasePath, 'profile-a').db - const second = openProfileStateDatabase(databasePath, 'profile-a').db - try { - importProfileStateJson(first, JSON.stringify({ automationRuns: [{ id: 'run-1' }] })) - expect(readProfileStateRevision(second)).toBe(1) - writeProfileStateDomain(first, { - domain: 'automationRuns', - payload: JSON.stringify([{ id: 'run-1', status: 'completed' }]), - expectedRevision: 1 - }) - - expect(() => - writeProfileStateDomain(second, { - domain: 'automationRuns', - payload: JSON.stringify([{ id: 'run-1', status: 'failed' }]), - expectedRevision: 1 - }) - ).toThrowError(ProfileStateRevisionConflictError) - expect(readProfileStateRevision(second)).toBe(2) - } finally { - first.close() - second.close() - } - }) }) diff --git a/src/main/persistence/profile-state/profile-state-recovery-command.ts b/src/main/persistence/profile-state/profile-state-recovery-command.ts index 1912ff7ddc4..806b8005b01 100644 --- a/src/main/persistence/profile-state/profile-state-recovery-command.ts +++ b/src/main/persistence/profile-state/profile-state-recovery-command.ts @@ -29,7 +29,7 @@ import { writeVersionedProfileStateExport } from './legacy-json/profile-state-ve import { readProfileStateDomain } from './profile-state-domain-reader' import { repairProfileStateSections } from './profile-state-section-repair' import { isRecord } from './profile-state-document-validation' -import { profileHasPendingProjectMove } from '../../orca-profiles/profile-project-move-record' +import { profileHasPendingProjectMove } from '../../orca-profiles/project-transfer/profile-project-move-record' import { invalidateHttp1CompatibilityMarker, writeHttp1CompatibilityMarker diff --git a/src/main/persistence/profile-state/profile-state-recovery-crash-boundaries.test.ts b/src/main/persistence/profile-state/profile-state-recovery-crash-boundaries.test.ts index 0acc49d27ea..bf3b44efb93 100644 --- a/src/main/persistence/profile-state/profile-state-recovery-crash-boundaries.test.ts +++ b/src/main/persistence/profile-state/profile-state-recovery-crash-boundaries.test.ts @@ -12,11 +12,8 @@ import { tmpdir } from 'node:os' import { basename, dirname, join, relative } from 'node:path' import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import { setSecretStore } from '../../../shared/secret-store' -import { profileStateStorage } from '../../orca-profiles/profile-project-state-file' -import { - acquireProfileStateMaintenance, - acquireProfileStateRuntimeAdmission -} from './profile-state-access' +import { profileStateStorage } from '../../orca-profiles/project-transfer/profile-project-state-file' +import { acquireProfileStateRuntimeAdmission } from './profile-state-access' import { openProfileStateDatabase, openProfileStateDatabaseReadOnly @@ -26,22 +23,17 @@ import { importProfileStateJson, readProfileStateSnapshot } from './profile-state-documents' -import { - profileStateJsonExportPath, - profileStateJsonExportPaths -} from './legacy-json/profile-state-export-path' +import { profileStateJsonExportPath } from './legacy-json/profile-state-export-path' import { createProfileStateDatabaseBackupId, - profileStateDatabaseBackupPath, - profileStateDatabaseBackups + profileStateDatabaseBackupPath } from './profile-state-backup-path' import { writeProfileStateDatabaseSnapshotAsync } from './profile-state-database-snapshot' import { createProfileStateStore } from './profile-state-store-factory' -import { restoreProfileStateJsonExport } from './legacy-json/profile-state-recovery' -import { restoreProfileStateDatabaseBackup } from './profile-state-database-recovery' +import './legacy-json/profile-state-recovery' +import './profile-state-database-recovery' import { ensureProfileStateAuthorityMarker, - hasProfileStateAuthorityMarker, profileStateAuthorityMarkerPath } from './profile-state-authority-marker' import { @@ -298,158 +290,7 @@ function assertRestart(profile: Fixture, expected: 'old' | 'selected' | 'refused } } -function retry(profile: Fixture): void { - const maintenance = acquireProfileStateMaintenance(profile.root) - try { - if (profile.kind === 'json') { - expect(profileStateJsonExportPaths(profile.dataFile)).toContain(profile.exportPath) - restoreProfileStateJsonExport({ ...profile, maintenance }) - } else { - expect( - profileStateDatabaseBackups(profile.databasePath).some( - (backup) => backup.path === profile.backupPath - ) - ).toBe(true) - restoreProfileStateDatabaseBackup({ ...profile, maintenance }) - } - } finally { - maintenance.release() - } - assertRestart(profile, 'selected') -} - -const JSON_BOUNDARIES = [ - 'marker-invalidated', - 'json-publish:before', - 'json-publish:after', - 'primary', - 'wal', - 'shm', - 'journal', - 'other-export', - 'first-export', - 'backup', - 'authority-marker', - 'selected-export', - 'restore-returned', - 'marker-publish:before', - 'marker-publish:after', - 'marker-refreshed' -] as const - -function stage(profile: Fixture, name: string): string { - const paths: Record = { - primary: profile.databasePath, - wal: `${profile.databasePath}-wal`, - shm: `${profile.databasePath}-shm`, - journal: `${profile.databasePath}-journal`, - 'other-export': profileStateJsonExportPath(profile.dataFile, 2), - 'first-export': profileStateJsonExportPath(profile.dataFile, 1), - 'marker-invalidated': profile.markerPath, - backup: profile.backupPath, - 'authority-marker': profileStateAuthorityMarkerPath(profile.databasePath), - 'selected-export': profile.exportPath, - json: profile.dataFile - } - const target = paths[name] - return target === undefined ? name : `removed:${target}` -} - -describe.each([false, true])('JSON recovery process death, accepted prior JSON=%s', (accepted) => { - it.each(JSON_BOUNDARIES)( - 'preserves a complete authority or exact retry at %s', - async (boundary) => { - const profile = await fixture('json', accepted) - await killRecoveryAt(bundle, profile, stage(profile, boundary)) - assertQuarantine(profile) - const finished = [ - 'selected-export', - 'restore-returned', - 'marker-publish:before', - 'marker-publish:after', - 'marker-refreshed' - ].includes(boundary) - const expected = finished - ? 'selected' - : ['marker-invalidated', 'json-publish:before'].includes(boundary) || - (boundary === 'json-publish:after' && accepted) - ? 'old' - : 'refused' - if (finished) { - expect(hasProfileStateAuthorityMarker(profile.databasePath)).toBe(false) - expect(readFileSync(profile.dataFile, 'utf8')).toBe(selectedJson) - expect(profileStateJsonExportPaths(profile.dataFile)).toEqual([]) - expect(profileStateDatabaseBackups(profile.databasePath)).toEqual([]) - } - assertRestart(profile, expected) - if (!finished) { - expect(readFileSync(profile.exportPath, 'utf8')).toBe(selectedJson) - retry(profile) - } - } - ) -}) - describe('SQLite recovery process death', () => { - it.each(['before', 'after'] as const)( - 'preserves the original family through authority-marker publication %s rename', - async (boundary) => { - const profile = await fixture('sqlite', true) - rmSync(profileStateAuthorityMarkerPath(profile.databasePath)) - await killRecoveryAt(bundle, profile, `authority-publish:${boundary}`) - assertQuarantine(profile, false) - expect(hasProfileStateAuthorityMarker(profile.databasePath)).toBe(boundary === 'after') - for (const [suffix, bytes] of profile.originalFamily) { - expect(readFileSync(`${profile.databasePath}${suffix}`)).toEqual(bytes) - } - assertRestart(profile, 'old') - retry(profile) - } - ) - - it.each([ - 'marker-invalidated', - 'selected-export', - 'other-export', - 'first-export', - 'primary', - 'wal', - 'shm', - 'journal', - 'json', - 'sqlite-publish:before', - 'sqlite-publish:after', - 'restore-returned', - 'marker-publish:before', - 'marker-publish:after', - 'marker-refreshed' - ])('preserves full state and its immutable retry backup at %s', async (boundary) => { - const profile = await fixture('sqlite', true) - await killRecoveryAt(bundle, profile, stage(profile, boundary)) - expect(hasProfileStateAuthorityMarker(profile.databasePath)).toBe(true) - assertQuarantine(profile) - expect(readFileSync(profile.backupPath).equals(profile.backupBytes)).toBe(true) - const expected = [ - 'marker-invalidated', - 'selected-export', - 'other-export', - 'first-export' - ].includes(boundary) - ? 'old' - : [ - 'sqlite-publish:after', - 'restore-returned', - 'marker-publish:before', - 'marker-publish:after', - 'marker-refreshed' - ].includes(boundary) - ? 'selected' - : 'refused' - assertRestart(profile, expected) - retry(profile) - expect(readFileSync(profile.backupPath).equals(profile.backupBytes)).toBe(true) - }) - it.skipIf(process.platform === 'win32')( 'allows clean JSON startup after final artifact cleanup is directory-synced', async () => { @@ -460,26 +301,3 @@ describe('SQLite recovery process death', () => { } ) }) - -it.each(['first-export', 'authority-marker'] as const)( - 'keeps current-JSON rollback safe through %s removal', - async (boundary) => { - const seeded = await fixture('json', true) - const profile = { ...seeded, exportPath: seeded.dataFile } - await killRecoveryAt(bundle, profile, stage(profile, boundary)) - assertQuarantine(profile) - expect(profileStateJsonExportPaths(profile.dataFile)).toEqual([]) - expect(profileStateDatabaseBackups(profile.databasePath)).toEqual([]) - expect(hasProfileStateAuthorityMarker(profile.databasePath)).toBe(boundary === 'first-export') - assertRestart(profile, boundary === 'first-export' ? 'refused' : 'selected') - if (boundary === 'first-export') { - const maintenance = acquireProfileStateMaintenance(profile.root) - try { - restoreProfileStateJsonExport({ ...profile, maintenance }) - } finally { - maintenance.release() - } - assertRestart(profile, 'selected') - } - } -) diff --git a/src/main/persistence/profile-state/profile-state-section-repair.ts b/src/main/persistence/profile-state/profile-state-section-repair.ts index 344f1c78baa..eaefbb7edb7 100644 --- a/src/main/persistence/profile-state/profile-state-section-repair.ts +++ b/src/main/persistence/profile-state/profile-state-section-repair.ts @@ -7,7 +7,7 @@ import { type ProfileStateRecoveryRepairSection } from '../../../shared/profile-state-recovery-command' import type { ProfileStateMaintenance } from './profile-state-access' -import { profileHasPendingProjectMove } from '../../orca-profiles/profile-project-move-record' +import { profileHasPendingProjectMove } from '../../orca-profiles/project-transfer/profile-project-move-record' import { readProfileStateAutomationRunsDocument } from './profile-state-automation-runs' import { profileStateDatabaseBackups } from './profile-state-backup-path' import { diff --git a/src/main/persistence/restoring-sessions/session-owner-fields.ts b/src/main/persistence/restoring-sessions/session-owner-fields.ts index 49d0bc1de9d..96922d1d07b 100644 --- a/src/main/persistence/restoring-sessions/session-owner-fields.ts +++ b/src/main/persistence/restoring-sessions/session-owner-fields.ts @@ -6,7 +6,7 @@ import { isWorktreeHostIdentity } from '../../../shared/worktree/host-qualified-identity' import { worktreeWorkspaceKey } from '../../../shared/workspace-scope' -import { SESSION_FIELDS_PRUNED_BY_OWNER_KEY } from '../../orca-profiles/profile-project-session-field-disposition' +import { SESSION_FIELDS_PRUNED_BY_OWNER_KEY } from '../../orca-profiles/project-transfer/profile-project-session-field-disposition' // Repo-keyed topology revisions advance rather than delete; host-qualified recency keys need a scan. export const OWNER_KEYED_SESSION_FIELDS_DELETED_WITH_THEIR_OWNER = diff --git a/src/main/persistence/tracking-repos/deregistered-repo-residue.ts b/src/main/persistence/tracking-repos/deregistered-repo-residue.ts index 7fa5d13e4e6..fd6723f89e4 100644 --- a/src/main/persistence/tracking-repos/deregistered-repo-residue.ts +++ b/src/main/persistence/tracking-repos/deregistered-repo-residue.ts @@ -7,8 +7,8 @@ import { parseExecutionHostId } from '../../../shared/execution-host' import { addWorkspaceSessionWorktreeOwners } from '../restoring-sessions/session-worktree-ownership' import { splitWorktreeId } from '../../../shared/worktree/id' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' -import { SESSION_FIELDS_PRUNED_BY_OWNER_KEY } from '../../orca-profiles/profile-project-session-field-disposition' -import { ownerKeyWorktreeIds } from '../../orca-profiles/profile-project-worktree-identity' +import { SESSION_FIELDS_PRUNED_BY_OWNER_KEY } from '../../orca-profiles/project-transfer/profile-project-session-field-disposition' +import { ownerKeyWorktreeIds } from '../../orca-profiles/project-transfer/profile-project-worktree-identity' /** Paired-host catalogs live on the remote host. */ const isPairedHost = (hostId: string | null | undefined): boolean => diff --git a/src/main/persistence/tracking-repos/persistence-folder-workspace-notes.test.ts b/src/main/persistence/tracking-repos/persistence-folder-workspace-notes.test.ts index bedd559e19f..d19204a2b50 100644 --- a/src/main/persistence/tracking-repos/persistence-folder-workspace-notes.test.ts +++ b/src/main/persistence/tracking-repos/persistence-folder-workspace-notes.test.ts @@ -11,7 +11,6 @@ import { join } from 'node:path' import { tmpdir } from 'node:os' import type { PersistedState } from '../../../shared/persisted-state-types' import { folderWorkspaceKey } from '../../../shared/workspace-scope' -import { folderWorkspaceToWorktree } from '../../../shared/folder-workspaces/folder-workspace-worktree' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ loadUserSshConfigMock: vi.fn(), @@ -100,8 +99,6 @@ describe('Store', () => { function writeFolderWorkspaceProfile(options: { workspaces: Record[] diffCommentsMap?: unknown - connectionId?: string | null - extraTopLevel?: Record }): void { writeDataFile({ schemaVersion: 1, @@ -116,7 +113,7 @@ describe('Store', () => { name: 'Platform', parentPath: '/workspace/platform', parentGroupId: null, - connectionId: options.connectionId ?? null, + connectionId: null, createdFrom: 'folder-scan', tabOrder: 0, isCollapsed: false, @@ -128,175 +125,10 @@ describe('Store', () => { folderWorkspaces: options.workspaces, ...('diffCommentsMap' in options ? { folderWorkspaceDiffComments: options.diffCommentsMap } - : {}), - ...options.extraTopLevel + : {}) }) } - // v1.4.179–v1.4.181 ignore the top-level notes map and reserialize it while normalizing folder records. - function simulatePreviousBuildLoadAndFlush(onDisk: PersistedState): PersistedState { - return { - ...onDisk, - folderWorkspaces: onDisk.folderWorkspaces.map( - ({ diffComments: _droppedByOldNormalizer, ...rest }) => rest - ) - } - } - - it('keeps folder-workspace review notes across a previous-build rollback and re-upgrade', async () => { - const store = await createStore() - const group = store.createProjectGroup({ - name: 'Platform', - parentPath: '/workspace/platform', - createdFrom: 'folder-scan' - }) - const workspace = store.createFolderWorkspace({ - projectGroupId: group.id, - name: 'Refund fix' - }) - const note = makeFolderNote('note-1', 'Review this paragraph', workspace.id) - store.updateFolderWorkspace(workspace.id, { diffComments: [note] }) - store.flush() - - const persisted = readDataFile() as PersistedState - expect(persisted.folderWorkspaceDiffComments?.[workspace.id]).toEqual([note]) - expect(persisted.folderWorkspaces[0]).not.toHaveProperty('diffComments') - expect(store.getFolderWorkspace(workspace.id)?.diffComments).toEqual([note]) - expect(folderWorkspaceToWorktree(store.getFolderWorkspace(workspace.id)!).diffComments).toEqual( - [note] - ) - - writeDataFile(simulatePreviousBuildLoadAndFlush(persisted)) - - const restored = await createStore() - expect(restored.getFolderWorkspace(workspace.id)?.diffComments).toEqual([note]) - restored.flush() - expect((readDataFile() as PersistedState).folderWorkspaceDiffComments?.[workspace.id]).toEqual([ - note - ]) - }) - - it('round-trips unknown top-level state keys through load and flush', async () => { - writeFolderWorkspaceProfile({ - workspaces: [folderWorkspaceRecord({ unknownNestedField: 'from-a-newer-build' })], - extraTopLevel: { unknownTopLevelKey: { kept: 'verbatim' } } - }) - - const store = await createStore() - store.updateFolderWorkspace('fw-1', { comment: 'touch' }) - store.flush() - - const persisted = readDataFile() as PersistedState & { unknownTopLevelKey?: unknown } - expect( - persisted.unknownTopLevelKey, - 'Unknown top-level keys must survive load + flush. Note preservation relies on this: converting the ' + - '`{ ...defaults, ...parsed }` load spread or the omit-style getDurableState() into an ' + - 'allowlist re-opens folder-workspace note loss for the then-previous build.' - ).toEqual({ kept: 'verbatim' }) - expect( - persisted.folderWorkspaces[0], - 'Documents existing behavior, not a guarantee: normalizeFolderWorkspaces rebuilds each ' + - 'record field-by-field, so nested unknown fields are dropped. That is why notes moved ' + - 'to a top-level key.' - ).not.toHaveProperty('unknownNestedField') - }) - - it('keeps notes across a rollback when the session never edits anything', async () => { - const note = makeFolderNote('note-1', 'Legacy inline note') - writeFolderWorkspaceProfile({ workspaces: [folderWorkspaceRecord({ diffComments: [note] })] }) - - // Simulate an upgrade launch and quit with no user mutation to make relocation durable. - const upgraded = await createStore() - upgraded.flush() - - writeDataFile(simulatePreviousBuildLoadAndFlush(readDataFile() as PersistedState)) - - const restored = await createStore() - expect(restored.getFolderWorkspace('fw-1')?.diffComments).toEqual([note]) - }) - - it('keeps notes authored inline on a rolled-back #14112 build over a staler map entry', async () => { - const mapped = makeFolderNote('note-mapped', 'Note from the fixed build') - const authored = makeFolderNote('note-inline', 'Note authored while rolled back') - - writeFolderWorkspaceProfile({ - workspaces: [folderWorkspaceRecord()], - diffCommentsMap: { 'fw-1': [mapped] } - }) - // The older build writes notes inline while preserving a stale map; inline is therefore newer (#14112). - const rolledBack = readDataFile() as PersistedState - writeDataFile({ - ...rolledBack, - folderWorkspaces: rolledBack.folderWorkspaces.map((workspace) => ({ - ...workspace, - diffComments: [authored] - })) - }) - - const store = await createStore() - expect(store.getFolderWorkspace('fw-1')?.diffComments).toEqual([authored]) - store.flush() - expect((readDataFile() as PersistedState).folderWorkspaceDiffComments).toEqual({ - 'fw-1': [authored] - }) - }) - - it('never lets an empty or unrelated map entry delete inline notes', async () => { - const inline = makeFolderNote('note-inline', 'Inline note') - const mapped = makeFolderNote('note-mapped', 'Mapped note') - - writeFolderWorkspaceProfile({ - workspaces: [folderWorkspaceRecord({ diffComments: [inline] })], - diffCommentsMap: { 'fw-1': [] } - }) - expect((await createStore()).getFolderWorkspace('fw-1')?.diffComments).toEqual([inline]) - - writeFolderWorkspaceProfile({ - workspaces: [folderWorkspaceRecord({ diffComments: [inline] })], - diffCommentsMap: { other: [mapped] } - }) - const store = await createStore() - expect(store.getFolderWorkspace('fw-1')?.diffComments).toEqual([inline]) - store.flush() - expect((readDataFile() as PersistedState).folderWorkspaceDiffComments).toEqual({ - 'fw-1': [inline] - }) - }) - - it('passes note members through verbatim on load and re-write', async () => { - // Preserve unknown note fields so validation cannot discard user-authored prose. - const noteWithExtras = { ...makeFolderNote('note-1', 'Body'), unknownNoteField: 'kept' } - writeFolderWorkspaceProfile({ - workspaces: [folderWorkspaceRecord(), folderWorkspaceRecord({ id: 'fw-2', name: 'Second' })], - diffCommentsMap: { 'fw-1': [7], 'fw-2': [noteWithExtras] } - }) - - const store = await createStore() - store.flush() - - const persisted = readDataFile() as PersistedState - expect(persisted.folderWorkspaceDiffComments).toEqual({ - 'fw-1': [7], - 'fw-2': [noteWithExtras] - }) - }) - - it('derives the written note map from live workspaces, never a stale loaded copy', async () => { - const loadedNote = makeFolderNote('note-loaded', 'Loaded note') - const editedNote = makeFolderNote('note-edited', 'Edited note') - writeFolderWorkspaceProfile({ - workspaces: [folderWorkspaceRecord()], - diffCommentsMap: { 'fw-1': [loadedNote] } - }) - - const store = await createStore() - store.updateFolderWorkspace('fw-1', { diffComments: [editedNote] }) - store.flush() - - expect((readDataFile() as PersistedState).folderWorkspaceDiffComments).toEqual({ - 'fw-1': [editedNote] - }) - }) it('drops the saved note map when the last note is cleared', async () => { writeFolderWorkspaceProfile({ workspaces: [folderWorkspaceRecord()], diff --git a/src/main/persistence/tracking-repos/persistence-repo-lifecycle.test.ts b/src/main/persistence/tracking-repos/persistence-repo-lifecycle.test.ts deleted file mode 100644 index d0b4fd71541..00000000000 --- a/src/main/persistence/tracking-repos/persistence-repo-lifecycle.test.ts +++ /dev/null @@ -1,335 +0,0 @@ -import { - closeTestStores, - testState, - createStore, - readDataFile, - makeRepo -} from '../persistence-test-harness' -import { makeTerminalTab } from '../persistence-session-fixtures' -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -import { rmSync, mkdtempSync } from 'node:fs' -import { join } from 'node:path' -import { tmpdir } from 'node:os' -import type { PersistedState } from '../../../shared/persisted-state-types' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import { _getLocalWorktreeScanGenerationCacheSize } from '../../workspaces/catalog/local-worktree-scan-generation' -import { hostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' -import { _pendingWslStoppedWorktreeRescanCount } from '../../wsl/discovery/wsl-stopped-worktree-rescan-registry' -import type { ExecutionHostId } from '../../../shared/execution-host' - -const at = (id: string, hostId: ExecutionHostId) => hostWorktreeTarget({ id, hostId }) -const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ - loadUserSshConfigMock: vi.fn(), - sshConfigHostsToTargetsMock: vi.fn() -})) - -vi.mock('../../ssh/config/ssh-config-parser', () => ({ - loadUserSshConfig: loadUserSshConfigMock, - sshConfigHostsToTargets: sshConfigHostsToTargetsMock -})) -const { trackMock, getCohortAtEmitMock } = vi.hoisted(() => ({ - trackMock: vi.fn(), - getCohortAtEmitMock: vi.fn() -})) - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.dir - }, - safeStorage: { - isEncryptionAvailable: () => true, - encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'), - decryptString: (ciphertext: Buffer) => { - const decoded = ciphertext.toString('utf-8') - if (!decoded.startsWith('encrypted:')) { - throw new Error('invalid ciphertext') - } - return decoded.slice('encrypted:'.length) - } - } -})) - -vi.mock('../../telemetry/client', () => ({ - track: trackMock -})) - -vi.mock('../../telemetry/cohort-classifier', () => ({ - getCohortAtEmit: getCohortAtEmitMock -})) - -describe('Store', () => { - beforeEach(() => { - testState.dir = mkdtempSync(join(tmpdir(), 'orca-test-')) - trackMock.mockReset() - getCohortAtEmitMock.mockReset() - getCohortAtEmitMock.mockReturnValue({ nth_repo_added: 2 }) - }) - - afterEach(async () => { - await closeTestStores() - rmSync(testState.dir, { recursive: true, force: true }) - }) - - it('removeProjectForHost removes only the target host row for a shared repo id', async () => { - const store = await createStore() - store.addRepo(makeRepo({ id: 'shared', path: '/local/repo' })) - store.addRepo( - makeRepo({ - id: 'shared', - path: '/remote/repo', - connectionId: 'ssh-old', - executionHostId: 'ssh:ssh-old' - }) - ) - store.setWorktreeMeta(at('shared::/local/repo/wt', 'local'), { displayName: 'local-wt' }) - store.setWorktreeMeta(at('shared::/remote/repo/wt', 'ssh:ssh-old'), { - displayName: 'remote-wt' - }) - - store.removeProjectForHost({ id: 'shared', executionHostId: 'ssh:ssh-old' }) - - const remaining = store.getRepos().filter((r) => r.id === 'shared') - expect(remaining).toHaveLength(1) - expect(remaining[0].path).toBe('/local/repo') - expect(store.getWorktreeMeta('shared::/local/repo/wt')).toBeDefined() - expect(store.getWorktreeMeta('shared::/remote/repo/wt')).toBeUndefined() - store.flush() - const persisted = readDataFile() as PersistedState - const identityMetadata = Object.values(persisted.worktreeMetaByIdentity ?? {}) - expect(identityMetadata).toEqual([ - expect.objectContaining({ hostId: 'local', displayName: 'local-wt' }) - ]) - }) - - it('removing a project saves the repo, metadata and session removal with only those domains dirty', async () => { - const store = await createStore() - store.addRepo(makeRepo({ id: 'r1', path: '/repo' })) - store.setWorktreeMeta(at('r1::/repo/wt', 'local'), { displayName: 'wt' }) - store.setWorkspaceSession({ - ...getDefaultWorkspaceSession(), - lastVisitedAtByWorktreeId: { 'r1::/repo/wt': 111 } - }) - // Drain earlier saves so the removal's own save is the one under test. - store.flush() - - store.removeProjectForHost({ id: 'r1', executionHostId: 'local' }) - store.flush() - - const reloaded = await createStore() - expect(reloaded.getRepos()).toEqual([]) - expect(reloaded.getWorktreeMeta('r1::/repo/wt')).toBeUndefined() - expect( - reloaded.getWorkspaceSession().lastVisitedAtByWorktreeId?.['r1::/repo/wt'] - ).toBeUndefined() - }) - - it('removeProjectForHost on the local host keeps a surviving SSH host session', async () => { - const store = await createStore() - store.addRepo(makeRepo({ id: 'shared', path: '/repo' })) - store.addRepo( - makeRepo({ - id: 'shared', - path: '/repo', - connectionId: 'ssh-a', - executionHostId: 'ssh:ssh-a' - }) - ) - store.setWorktreeMeta(at('shared::/repo', 'local'), { displayName: 'local' }) - - store.setWorkspaceSession({ - ...getDefaultWorkspaceSession(), - lastVisitedAtByWorktreeId: { 'shared::/repo': 111 } - }) - store.setWorkspaceSession( - { - ...getDefaultWorkspaceSession(), - lastVisitedAtByWorktreeId: { 'shared::/repo': 222 } - }, - 'ssh:ssh-a' - ) - - store.removeProjectForHost({ id: 'shared', executionHostId: 'local' }) - - expect(store.getWorkspaceSession().lastVisitedAtByWorktreeId?.['shared::/repo']).toBeUndefined() - expect( - store.getWorkspaceSession('ssh:ssh-a').lastVisitedAtByWorktreeId?.['shared::/repo'] - ).toBe(222) - }) - - it('removeProjectForHost prunes only the removed host when a third host also shares the owner key', async () => { - const store = await createStore() - // Three hosts share the same worktree ID; removing one must preserve both survivors. - store.addRepo(makeRepo({ id: 'shared', path: '/repo' })) - store.addRepo( - makeRepo({ - id: 'shared', - path: '/repo', - connectionId: 'ssh-a', - executionHostId: 'ssh:ssh-a' - }) - ) - store.addRepo( - makeRepo({ - id: 'shared', - path: '/repo', - connectionId: 'ssh-b', - executionHostId: 'ssh:ssh-b' - }) - ) - store.setWorktreeMeta(at('shared::/repo', 'local'), { displayName: 'local' }) - - store.setWorkspaceSession({ - ...getDefaultWorkspaceSession(), - lastVisitedAtByWorktreeId: { 'shared::/repo': 111 } - }) - store.setWorkspaceSession( - { - ...getDefaultWorkspaceSession(), - lastVisitedAtByWorktreeId: { 'shared::/repo': 222 } - }, - 'ssh:ssh-a' - ) - store.setWorkspaceSession( - { - ...getDefaultWorkspaceSession(), - lastVisitedAtByWorktreeId: { 'shared::/repo': 333 } - }, - 'ssh:ssh-b' - ) - - store.removeProjectForHost({ id: 'shared', executionHostId: 'ssh:ssh-a' }) - - expect( - store.getWorkspaceSession('ssh:ssh-a').lastVisitedAtByWorktreeId?.['shared::/repo'] - ).toBeUndefined() - expect(store.getWorkspaceSession().lastVisitedAtByWorktreeId?.['shared::/repo']).toBe(111) - expect( - store.getWorkspaceSession('ssh:ssh-b').lastVisitedAtByWorktreeId?.['shared::/repo'] - ).toBe(333) - }) - - it('reorderReposForHost independently reorders local and SSH rows with shared ids', async () => { - const store = await createStore() - store.addRepo(makeRepo({ id: 'shared', path: '/local/shared' })) - store.addRepo( - makeRepo({ - id: 'shared', - path: '/ssh/shared', - connectionId: 'target' - }) - ) - store.addRepo(makeRepo({ id: 'local-two', path: '/local/two' })) - store.addRepo( - makeRepo({ - id: 'ssh-two', - path: '/ssh/two', - connectionId: 'target' - }) - ) - - expect(store.reorderReposForHost(['local-two', 'shared'], 'local')).toBe(true) - expect(store.getRepos().map((repo) => repo.path)).toEqual([ - '/local/two', - '/ssh/shared', - '/local/shared', - '/ssh/two' - ]) - - expect(store.reorderReposForHost(['ssh-two', 'shared'], 'ssh:target')).toBe(true) - expect(store.getRepos().map((repo) => repo.path)).toEqual([ - '/local/two', - '/ssh/two', - '/local/shared', - '/ssh/shared' - ]) - }) - - it('reassignSshTargetId persists a worktree-meta-only re-point (no matching repo)', async () => { - const store = await createStore() - // Register the repo locally so orphan cleanup cannot mask metadata-only remote re-adoption. - store.addRepo(makeRepo({ id: 'r1', path: '/r1' })) - store.setWorktreeMeta(at('r1::/remote/wt', 'ssh:ssh-old'), { displayName: 'wt' }) - - const repoIds = store.reassignSshTargetId('ssh-old', 'ssh-new') - expect(repoIds).toEqual([]) - store.flush() - - const reloaded = await createStore() - expect(reloaded.getWorktreeMeta('r1::/remote/wt')?.hostId).toBe('ssh:ssh-new') - }) - - it('reassignSshTargetId re-keys a session partition stored under the old ssh host id', async () => { - const store = await createStore() - store.addRepo(makeRepo({ id: 'r1', path: '/r1' })) - store.setWorkspaceSession( - { - activeRepoId: null, - activeWorktreeId: null, - activeTabId: null, - tabsByWorktree: { - 'r1::/wt': [makeTerminalTab({ id: 'tab1', ptyId: 'ssh:ssh-old@@pty-9' })] - }, - terminalLayoutsByTabId: {} - }, - 'ssh:ssh-old' - ) - - store.reassignSshTargetId('ssh-old', 'ssh-new') - store.flush() - - const reloaded = await createStore() - expect(reloaded.getWorkspaceSession('ssh:ssh-old').tabsByWorktree).toEqual({}) - expect(reloaded.getWorkspaceSession('ssh:ssh-new').tabsByWorktree['r1::/wt'][0].ptyId).toBe( - 'ssh:ssh-new@@pty-9' - ) - }) - - it('reassignSshTargetId keeps the live partition when both host keys exist', async () => { - const store = await createStore() - const baseSession = { - activeRepoId: null, - activeWorktreeId: null, - activeTabId: null, - terminalLayoutsByTabId: {} - } - store.setWorkspaceSession( - { ...baseSession, tabsByWorktree: { 'r1::/dead': [] } }, - 'ssh:ssh-old' - ) - store.setWorkspaceSession( - { ...baseSession, tabsByWorktree: { 'r1::/live': [] } }, - 'ssh:ssh-new' - ) - - store.reassignSshTargetId('ssh-old', 'ssh-new') - - expect(store.getWorkspaceSession('ssh:ssh-old').tabsByWorktree).toEqual({}) - expect(store.getWorkspaceSession('ssh:ssh-new').tabsByWorktree).toEqual({ 'r1::/live': [] }) - }) - - it('reassignSshTargetId drops a stale setup when the new host already has one', async () => { - const store = await createStore() - store.addRepo({ - ...makeRepo({ id: 'r1', displayName: 'Cloud Project' }), - upstream: { owner: 'stablyai', repo: 'cloud-project' } - }) - store.createProjectHostSetup({ - projectId: 'github:stablyai/cloud-project', - hostId: 'ssh:ssh-old', - setupId: 'setup-old', - setupMethod: 'provisioned' - }) - store.createProjectHostSetup({ - projectId: 'github:stablyai/cloud-project', - hostId: 'ssh:ssh-new', - setupId: 'setup-new', - setupMethod: 'provisioned' - }) - - store.reassignSshTargetId('ssh-old', 'ssh-new') - - const setups = store.getProjectHostSetups() - expect(setups.find((entry) => entry.id === 'setup-old')).toBeUndefined() - expect(setups.find((entry) => entry.id === 'setup-new')?.hostId).toBe('ssh:ssh-new') - }) -}) diff --git a/src/main/plugins/plugin-runtime-binding.test.ts b/src/main/plugins/plugin-runtime-binding.test.ts index 9bf34c08122..101c0b4696d 100644 --- a/src/main/plugins/plugin-runtime-binding.test.ts +++ b/src/main/plugins/plugin-runtime-binding.test.ts @@ -1,10 +1,6 @@ import { describe, expect, it, vi } from 'vitest' -import { - createPluginAgentStatusForwarder, - pluginRuntimeDelegate, - watchPluginWorkspaceContext -} from './plugin-runtime-binding' -import { projectPluginWorkspaceAgents } from './workers/plugin-workspace-projection' +import { createPluginAgentStatusForwarder, pluginRuntimeDelegate } from './plugin-runtime-binding' + import { PluginPanelBridge } from './panels/plugin-panel-bridge' import type { ValidDiscoveredPlugin } from './plugin-discovery' @@ -31,146 +27,6 @@ function runtime(terminals: { handle: string; title: string | null; paneTitle?: } describe('agent.status.changed for plugins', () => { - it('names the terminal and its title, in arrival order, only while someone listens', async () => { - const delegate = pluginRuntimeDelegate( - runtime([ - { handle: 'term_a', title: 'zsh' }, - { handle: 'term_b', title: 'codex', paneTitle: 'Reviewer' } - ]), - () => [] - ) - const events = { wantsEvent: vi.fn(() => true), emitEvent: vi.fn() } - const forward = createPluginAgentStatusForwarder(delegate, events) - const base = { workspaceId: 'repo::/w', state: 'working' as const, receivedAt: 1 } - forward({ ...base, paneKey: `tab1:${LEAF}` }) - forward({ ...base, paneKey: 'tab9:unknown', state: 'done' }) - await vi.waitFor(() => expect(events.emitEvent).toHaveBeenCalledTimes(2)) - expect(events.emitEvent.mock.calls).toEqual([ - [ - 'agent.status.changed', - { ...base, paneKey: `tab1:${LEAF}`, terminalId: 'term_b', title: 'Reviewer' } - ], - ['agent.status.changed', { ...base, paneKey: 'tab9:unknown', state: 'done' }] - ]) - events.wantsEvent.mockReturnValue(false) - forward({ ...base, paneKey: `tab0:${LEAF}` }) - await Promise.resolve() - expect(events.emitEvent).toHaveBeenCalledTimes(2) - }) - - it('stops listing terminals for queued events once the last listener goes away', async () => { - const source = runtime([{ handle: 'term_a', title: 'zsh' }]) - const listing = Promise.withResolvers<{ terminals: [] }>() - source.listTerminals.mockReturnValueOnce(listing.promise) - const delegate = pluginRuntimeDelegate(source, () => []) - const events = { wantsEvent: vi.fn(() => true), emitEvent: vi.fn() } - const forward = createPluginAgentStatusForwarder(delegate, events) - const base = { state: 'working' as const, receivedAt: 1, paneKey: `tab0:${LEAF}` } - forward({ ...base, workspaceId: 'repo::/a' }) - await vi.waitFor(() => expect(source.listTerminals).toHaveBeenCalledOnce()) - forward({ ...base, workspaceId: 'repo::/b' }) - forward({ ...base, workspaceId: 'repo::/c' }) - // The panel closes while the first lookup is still running. - events.wantsEvent.mockReturnValue(false) - listing.resolve({ terminals: [] }) - await new Promise((resolve) => setTimeout(resolve, 0)) - expect(source.listTerminals).toHaveBeenCalledOnce() - expect(events.emitEvent).toHaveBeenCalledOnce() - }) - - it('shares one terminal listing per workspace among events queued behind a lookup', async () => { - const source = runtime([{ handle: 'term_a', title: 'zsh' }]) - let releaseFirst: () => void = () => undefined - const first = source.listTerminals.getMockImplementation()! - source.listTerminals.mockImplementationOnce(async () => { - await new Promise((resolve) => (releaseFirst = resolve)) - return first() - }) - const delegate = pluginRuntimeDelegate(source, () => []) - const events = { wantsEvent: vi.fn(() => true), emitEvent: vi.fn() } - const forward = createPluginAgentStatusForwarder(delegate, events) - const base = { workspaceId: 'repo::/w', receivedAt: 1, paneKey: `tab0:${LEAF}` } - forward({ ...base, state: 'working' }) - await vi.waitFor(() => expect(source.listTerminals).toHaveBeenCalledOnce()) - forward({ ...base, state: 'waiting' }) - forward({ ...base, state: 'done' }) - forward({ ...base, workspaceId: 'repo::/other', state: 'done' }) - releaseFirst() - await vi.waitFor(() => expect(events.emitEvent).toHaveBeenCalledTimes(4)) - expect(source.listTerminals).toHaveBeenCalledTimes(3) - expect(events.emitEvent.mock.calls.map(([, payload]) => payload)).toEqual([ - { ...base, state: 'working', terminalId: 'term_a', title: 'zsh' }, - { ...base, state: 'waiting', terminalId: 'term_a', title: 'zsh' }, - { ...base, state: 'done', terminalId: 'term_a', title: 'zsh' }, - { ...base, workspaceId: 'repo::/other', state: 'done', terminalId: 'term_a', title: 'zsh' } - ]) - }) - - it('keeps delivering, in order, past a failed listing or a throwing delivery', async () => { - const source = runtime([{ handle: 'term_a', title: 'zsh' }]) - source.listTerminals.mockRejectedValueOnce(new Error('pty host gone')) - const delegate = pluginRuntimeDelegate(source, () => []) - const emitted: string[] = [] - const events = { - wantsEvent: vi.fn(() => true), - emitEvent: vi.fn((_event: string, payload: { state: string; terminalId?: string }) => { - const { state, terminalId } = payload - emitted.push(`${state}:${terminalId ?? '-'}`) - if (state === 'waiting') { - throw new Error('renderer gone') - } - }) - } - const forward = createPluginAgentStatusForwarder(delegate, events) - const base = { workspaceId: 'repo::/w', receivedAt: 1, paneKey: `tab0:${LEAF}` } - forward({ ...base, state: 'working' }) - await vi.waitFor(() => expect(emitted).toEqual(['working:-'])) - forward({ ...base, state: 'waiting' }) - forward({ ...base, state: 'done' }) - await vi.waitFor(() => expect(emitted).toEqual(['working:-', 'waiting:term_a', 'done:term_a'])) - // The queue is not wedged: a later event still goes out. - forward({ ...base, state: 'working' }) - await vi.waitFor(() => expect(emitted).toHaveLength(4)) - expect(emitted[3]).toBe('working:term_a') - }) - - it('lists terminals once for a storm of events, and delivers all of them in order', async () => { - const source = runtime([{ handle: 'term_a', title: 'zsh' }]) - const delegate = pluginRuntimeDelegate(source, () => []) - const events = { wantsEvent: vi.fn(() => true), emitEvent: vi.fn() } - const forward = createPluginAgentStatusForwarder(delegate, events) - for (let index = 0; index < 1000; index += 1) { - forward({ workspaceId: 'repo::/w', state: 'working', receivedAt: index, paneKey: 'p' }) - } - await vi.waitFor(() => expect(events.emitEvent).toHaveBeenCalledTimes(1000)) - expect(source.listTerminals).toHaveBeenCalledOnce() - expect(events.emitEvent.mock.calls.map(([, payload]) => payload)).toEqual( - [...Array(1000).keys()].map((receivedAt) => expect.objectContaining({ receivedAt })) - ) - }) - - it('delivers the backlog to a panel that reopened before the lookup finished', async () => { - const source = runtime([{ handle: 'term_a', title: 'zsh' }]) - const listing = Promise.withResolvers<{ terminals: [] }>() - source.listTerminals.mockReturnValueOnce(listing.promise) - const delegate = pluginRuntimeDelegate(source, () => []) - const events = { wantsEvent: vi.fn(() => true), emitEvent: vi.fn() } - const forward = createPluginAgentStatusForwarder(delegate, events) - const base = { state: 'working' as const, receivedAt: 1, paneKey: `tab0:${LEAF}` } - forward({ ...base, workspaceId: 'repo::/a' }) - await vi.waitFor(() => expect(source.listTerminals).toHaveBeenCalledOnce()) - forward({ ...base, workspaceId: 'repo::/b' }) - // The panel closes and reopens while the first lookup runs: only interest at lookup time counts. - events.wantsEvent.mockReturnValue(false) - events.wantsEvent.mockReturnValue(true) - listing.resolve({ terminals: [] }) - await vi.waitFor(() => expect(events.emitEvent).toHaveBeenCalledTimes(2)) - expect(events.emitEvent.mock.calls.map(([, payload]) => payload)).toEqual([ - expect.objectContaining({ workspaceId: 'repo::/a' }), - expect.objectContaining({ workspaceId: 'repo::/b' }) - ]) - }) - it('serves several open panels, and stops looking up only when the last one closes', async () => { const plugin = { pluginKey: 'acme.board', manifest: {} } const bridge = new PluginPanelBridge({ @@ -223,114 +79,3 @@ describe('agent.status.changed for plugins', () => { expect(panels[1]).toHaveBeenCalledTimes(2) }) }) - -describe('agents.list projection', () => { - it("lists the focused workspace's agents with their terminal, newest first", () => { - const terminals = [{ id: 'term_a', title: 'codex', paneKey: `tab0:${LEAF}` }] - expect( - projectPluginWorkspaceAgents('w1', terminals, [ - { - paneKey: `tab0:${LEAF}`, - worktreeId: 'w1', - state: 'working', - stateStartedAt: 5, - agentType: 'codex' - }, - { paneKey: 'gone', worktreeId: 'w1', state: 'done', stateStartedAt: 9 }, - { paneKey: 'x', worktreeId: 'w2', state: 'done', stateStartedAt: 7 }, - { - paneKey: 'y', - worktreeId: 'w1', - state: 'done', - stateStartedAt: 8, - providerSessionOnly: true - } - ]) - ).toEqual([ - { terminalId: null, title: null, agent: null, state: 'done', stateStartedAt: 9 }, - { terminalId: 'term_a', title: 'codex', agent: 'codex', state: 'working', stateStartedAt: 5 } - ]) - }) -}) - -describe('workspace.changed', () => { - it('re-reads the context after session writes settle and emits only real changes', async () => { - vi.useFakeTimers() - try { - const source = runtime([{ handle: 'term_a', title: 'zsh' }]) - const delegate = pluginRuntimeDelegate(source, () => []) - const events = { wantsEvent: vi.fn(() => true), emitEvent: vi.fn() } - let written: () => void = () => undefined - const stop = watchPluginWorkspaceContext({ - delegate, - events, - onSessionWritten: (listener) => { - written = listener - return () => undefined - }, - onStateWritten: () => () => undefined, - delayMs: 10 - }) - written() - written() - await vi.advanceTimersByTimeAsync(20) - expect(events.emitEvent).toHaveBeenCalledWith('workspace.changed', { - context: { branch: 'main', displayName: 'w', terminals: [{ id: 'term_a', title: 'zsh' }] } - }) - written() - await vi.advanceTimersByTimeAsync(20) - expect(events.emitEvent).toHaveBeenCalledOnce() - source.listTerminals.mockResolvedValueOnce({ terminals: [] }) - written() - await vi.advanceTimersByTimeAsync(20) - expect(events.emitEvent).toHaveBeenLastCalledWith('workspace.changed', { - context: { branch: 'main', displayName: 'w', terminals: [] } - }) - // Same projected payload, different focused workspace: still a change. - source.resolveActiveWorktreeContext.mockResolvedValueOnce({ - worktreeId: 'repo::/other', - path: '/w', - branch: 'refs/heads/main', - displayName: 'w' - }) - source.listTerminals.mockResolvedValueOnce({ terminals: [] }) - written() - await vi.advanceTimersByTimeAsync(20) - expect(events.emitEvent).toHaveBeenCalledTimes(3) - stop() - } finally { - vi.useRealTimers() - } - }) - - it('re-reads the context after a catalog save such as a folder rename, not a UI save', async () => { - vi.useFakeTimers() - try { - const delegate = pluginRuntimeDelegate( - runtime([{ handle: 'term_a', title: 'zsh' }]), - () => [] - ) - const events = { wantsEvent: vi.fn(() => true), emitEvent: vi.fn() } - let saved: (domains: readonly string[] | undefined) => void = () => undefined - const stop = watchPluginWorkspaceContext({ - delegate, - events, - onSessionWritten: () => () => undefined, - onStateWritten: (listener) => { - saved = listener - return () => undefined - }, - delayMs: 10 - }) - saved(['ui']) - await vi.advanceTimersByTimeAsync(20) - expect(events.emitEvent).not.toHaveBeenCalled() - saved(['folderWorkspaces']) - await vi.advanceTimersByTimeAsync(20) - expect(events.emitEvent).toHaveBeenCalledWith('workspace.changed', expect.anything()) - stop() - } finally { - vi.useRealTimers() - } - }) -}) diff --git a/src/main/pty/history/terminal-history-async-delete.test.ts b/src/main/pty/history/terminal-history-async-delete.test.ts deleted file mode 100644 index d748f795e11..00000000000 --- a/src/main/pty/history/terminal-history-async-delete.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { installFakeAppEnvironment } from '../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' - -let userDataDir: string - -import { hashWorktreeId } from './terminal-history-id' -import { - deleteWorktreeHistoryDir, - flushPendingWorktreeHistoryDeletions -} from './terminal-history-deletion' - -describe('deleteWorktreeHistoryDir main-thread safety', () => { - beforeEach(() => { - userDataDir = mkdtempSync(join(tmpdir(), 'orca-history-async-')) - installFakeAppEnvironment({ getPath: () => userDataDir }) - }) - - afterEach(async () => { - await flushPendingWorktreeHistoryDeletions() - rmSync(userDataDir, { recursive: true, force: true }) - }) - - it('tombstones without blocking the event loop, then removes via async rm', async () => { - const worktreeId = 'repo-1::/path/heavy-wt' - const hash = hashWorktreeId(worktreeId) - const historyDir = join(userDataDir, 'terminal-history', hash) - mkdirSync(historyDir, { recursive: true }) - for (let i = 0; i < 3_000; i++) { - writeFileSync(join(historyDir, `file-${i}.txt`), `payload-${i}`) - } - - // Measure the sync delete call; later async-rm timer gaps depend on CI scheduling. - const criticalPathStartedAt = performance.now() - deleteWorktreeHistoryDir(worktreeId) - const criticalPathMs = performance.now() - criticalPathStartedAt - - // AV/shared runners can delay rename; structural assertions below establish tombstoning. - expect(criticalPathMs).toBeLessThan( - process.env.CI || process.platform === 'win32' ? 1_000 : 100 - ) - expect(readdirSync(join(userDataDir, 'terminal-history'))).not.toContain(hash) - expect( - readdirSync(join(userDataDir, 'terminal-history', '.pending-delete')).length - ).toBeGreaterThan(0) - - await flushPendingWorktreeHistoryDeletions() - expect(readdirSync(join(userDataDir, 'terminal-history', '.pending-delete'))).toHaveLength(0) - }) -}) diff --git a/src/main/rate-limits/providers/minimax/minimax-request-context.test.ts b/src/main/rate-limits/providers/minimax/minimax-request-context.test.ts index 68fc9ef7b35..5d31ddaed9e 100644 --- a/src/main/rate-limits/providers/minimax/minimax-request-context.test.ts +++ b/src/main/rate-limits/providers/minimax/minimax-request-context.test.ts @@ -2,13 +2,6 @@ import { describe, expect, it } from 'vitest' import { redactMiniMaxSecret } from './minimax-request-context' describe('redactMiniMaxSecret', () => { - it('redacts _token values in header and quoted syntax', () => { - const redacted = redactMiniMaxSecret('cookie _token=eyJhABCDEF and _token:"x.y"') - expect(redacted).toContain('_token=[REDACTED]') - expect(redacted).not.toContain('eyJhABCDEF') - expect(redacted).not.toContain('x.y') - }) - it('redacts quoted values with whitespace around the colon', () => { const redacted = redactMiniMaxSecret('_token : "spaced.secret"') expect(redacted).not.toContain('spaced.secret') diff --git a/src/main/ripgrep/synchronous-spawn-failure.test.ts b/src/main/ripgrep/synchronous-spawn-failure.test.ts deleted file mode 100644 index f69606ec97d..00000000000 --- a/src/main/ripgrep/synchronous-spawn-failure.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { spawn } from 'node:child_process' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { classifySynchronousRipgrepSpawnFailure } from '../../shared/ripgrep/ripgrep-process-availability' - -const dirs: string[] = [] - -afterEach(() => { - for (const dir of dirs.splice(0)) { - rmSync(dir, { recursive: true, force: true }) - } -}) - -function fileAsSearchRoot(): string { - const dir = mkdtempSync(join(tmpdir(), 'rg-sync-')) - dirs.push(dir) - const path = join(dir, 'not-a-directory') - writeFileSync(path, '') - return path -} - -describe('synchronous ripgrep spawn failures', () => { - it.skipIf(process.platform === 'win32')( - 'names the unreachable root instead of surfacing a raw spawn errno', - async () => { - const root = fileAsSearchRoot() - let thrown: unknown - try { - spawn(process.execPath, ['-e', ''], { cwd: root, stdio: 'ignore' }) - } catch (error) { - thrown = error - } - - const verdict = await classifySynchronousRipgrepSpawnFailure(thrown, root) - - expect(verdict.message).toBe(`Search root is not reachable: ${root}`) - } - ) -}) diff --git a/src/main/runtime/__fixtures__/claude-2-1-316-startup-api-key.meta.json b/src/main/runtime/__fixtures__/claude-2-1-316-startup-api-key.meta.json new file mode 100644 index 00000000000..c54e023c80d --- /dev/null +++ b/src/main/runtime/__fixtures__/claude-2-1-316-startup-api-key.meta.json @@ -0,0 +1,12 @@ +{ + "capturedAt": "2026-11-02T00:00:00.000Z", + "platform": "darwin", + "command": ["claude"], + "env": { + "TERM": "xterm-256color" + }, + "cols": 100, + "rows": 30, + "note": "Claude Code 2.1.316; real PTY with a throwaway CLAUDE_CONFIG_DIR and HOME in an already-trusted scratch git repo; ANTHROPIC_API_KEY set to a fake key never seen before. No keys sent; capture ends with the startup menu owning the screen. Fake API key and scratch paths scrubbed with same-length replacements.", + "exitCode": -9 +} diff --git a/src/main/runtime/__fixtures__/claude-2-1-316-startup-api-key.txt b/src/main/runtime/__fixtures__/claude-2-1-316-startup-api-key.txt new file mode 100644 index 00000000000..0a626ce7d0c --- /dev/null +++ b/src/main/runtime/__fixtures__/claude-2-1-316-startup-api-key.txt @@ -0,0 +1,13 @@ +78[?25h[?25l[?2004h[?2031h[?1004h +──────────────────────────────────────────────────────────────────────────────────────────────────── +DetectedacustomAPIkeyinyourenvironment + +ANTHROPIC_API_KEY:xx-xxx-...000000000000000000AA + +DoyouwanttousethisAPIkey? + +Yes +❯No(recommended) + +Entertoconfirm·Esctocancel +[>0q[?u]7501;? \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/claude-2-1-316-startup-bypass-permissions.meta.json b/src/main/runtime/__fixtures__/claude-2-1-316-startup-bypass-permissions.meta.json new file mode 100644 index 00000000000..adb7b8a8101 --- /dev/null +++ b/src/main/runtime/__fixtures__/claude-2-1-316-startup-bypass-permissions.meta.json @@ -0,0 +1,12 @@ +{ + "capturedAt": "2026-11-02T00:00:00.000Z", + "platform": "darwin", + "command": ["claude", "--dangerously-skip-permissions"], + "env": { + "TERM": "xterm-256color" + }, + "cols": 100, + "rows": 30, + "note": "Claude Code 2.1.316; real PTY with a throwaway CLAUDE_CONFIG_DIR and HOME in an already-trusted scratch git repo; bypass-permissions mode not yet accepted. No keys sent; capture ends with the startup menu owning the screen. Fake API key and scratch paths scrubbed with same-length replacements.", + "exitCode": -9 +} diff --git a/src/main/runtime/__fixtures__/claude-2-1-316-startup-bypass-permissions.txt b/src/main/runtime/__fixtures__/claude-2-1-316-startup-bypass-permissions.txt new file mode 100644 index 00000000000..51cada7f353 --- /dev/null +++ b/src/main/runtime/__fixtures__/claude-2-1-316-startup-bypass-permissions.txt @@ -0,0 +1,19 @@ +78[?25h[?25l[?2004h[?2031h[?1004h +──────────────────────────────────────────────────────────────────────────────────────────────────── +WARNING:ClaudeCoderunninginBypassPermissionsmode + +InBypassPermissionsmode,ClaudeCodewillnotaskforyourapprovalbeforerunning +potentiallydangerouscommands. +Thismodeshouldonlybeusedinasandboxedcontainer/VMthathasrestrictedinternetaccess +andcaneasilyberestoredifdamaged. + +Byproceeding,youacceptallresponsibilityforactionstakenwhilerunninginBypass +Permissionsmode. + +]8;id=zaxmda;https://code.claude.com/docs/en/securityhttps://code.claude.com/docs/en/security]8;; + +❯No,exit +Yes,Iaccept + +Entertoconfirm·Esctocancel +[>0q[?u]7501;? \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/claude-2-1-316-startup-external-imports.meta.json b/src/main/runtime/__fixtures__/claude-2-1-316-startup-external-imports.meta.json new file mode 100644 index 00000000000..a040d9b4d9a --- /dev/null +++ b/src/main/runtime/__fixtures__/claude-2-1-316-startup-external-imports.meta.json @@ -0,0 +1,12 @@ +{ + "capturedAt": "2026-11-02T00:00:00.000Z", + "platform": "darwin", + "command": ["claude"], + "env": { + "TERM": "xterm-256color" + }, + "cols": 100, + "rows": 30, + "note": "Claude Code 2.1.316; real PTY with a throwaway CLAUDE_CONFIG_DIR and HOME in an already-trusted scratch git repo; the project CLAUDE.md imports a file outside the working directory. No keys sent; capture ends with the startup menu owning the screen. Scratch paths scrubbed with same-length replacements.", + "exitCode": -9 +} diff --git a/src/main/runtime/__fixtures__/claude-2-1-316-startup-external-imports.txt b/src/main/runtime/__fixtures__/claude-2-1-316-startup-external-imports.txt new file mode 100644 index 00000000000..6177b450a7b --- /dev/null +++ b/src/main/runtime/__fixtures__/claude-2-1-316-startup-external-imports.txt @@ -0,0 +1,18 @@ +78[?25h[?25l[?2004h[?2031h[?1004h +──────────────────────────────────────────────────────────────────────────────────────────────────── +AllowexternalCLAUDE.mdfileimports? + +Thisproject'sCLAUDE.mdor.claude/rulesimportsfilesoutsidethecurrentworkingdirectory. +Neverallowthisforthird-partyrepositories. + +Externalimports: + /private/tmp/xxxxxxxxxx/xxxxxxxxxxxxxxxxxxxxxx…xxxxxxxxxxxxxxxxxxx/xxxxxxxxxx/outside/notes.md + +Important:OnlyuseClaudeCodewithfilesyoutrust.Accessinguntrustedfilesmaypose +securityrisks]8;id=zaxmda;https://code.claude.com/docs/en/securityhttps://code.claude.com/docs/en/security]8;; + +❯No,disableexternalimports +Yes,allowexternalimports + +Entertoconfirm·Esctocancel +[>0q[?u]7501;? \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server-narrow.meta.json b/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server-narrow.meta.json new file mode 100644 index 00000000000..e9e4c01b9c0 --- /dev/null +++ b/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server-narrow.meta.json @@ -0,0 +1,12 @@ +{ + "capturedAt": "2026-11-02T00:00:00.000Z", + "platform": "darwin", + "command": ["claude"], + "env": { + "TERM": "xterm-256color" + }, + "cols": 60, + "rows": 30, + "note": "Claude Code 2.1.316; real PTY with a throwaway CLAUDE_CONFIG_DIR and HOME in an already-trusted scratch git repo; a project .mcp.json declares one new server; 60 columns. No keys sent; capture ends with the startup menu owning the screen. Fake API key and scratch paths scrubbed with same-length replacements.", + "exitCode": -9 +} diff --git a/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server-narrow.txt b/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server-narrow.txt new file mode 100644 index 00000000000..135ffe4f033 --- /dev/null +++ b/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server-narrow.txt @@ -0,0 +1,14 @@ +78[?25h[?25l[?2004h[?2031h[?1004h +──────────────────────────────────────────────────────────── +NewMCPserverfoundinthisproject:scratch-echo + +MCPserversmayexecutecodeoraccesssystemresources. +Alltoolcallsrequireapproval.Learnmoreinthe]8;id=c415zw;https://code.claude.com/docs/en/mcpMCP ]8;; +]8;id=c415zw;https://code.claude.com/docs/en/mcpdocumentation]8;;. + +UsethisMCPserver +UsethisandallfutureMCPserversinthisproject +❯ContinuewithoutusingthisMCPserver + +Entertoconfirm·Esctocancel +[>0q[?u]7501;? \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server-wrapped.meta.json b/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server-wrapped.meta.json new file mode 100644 index 00000000000..6c442d3ce1a --- /dev/null +++ b/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server-wrapped.meta.json @@ -0,0 +1,12 @@ +{ + "capturedAt": "2026-11-02T00:00:00.000Z", + "platform": "darwin", + "command": ["claude"], + "env": { + "TERM": "xterm-256color" + }, + "cols": 44, + "rows": 30, + "note": "Claude Code 2.1.316; real PTY with a throwaway CLAUDE_CONFIG_DIR and HOME in an already-trusted scratch git repo; a project .mcp.json declares one new server; 44 columns, so the second choice wraps onto an indented continuation row. No keys sent; capture ends with the startup menu owning the screen. Fake API key and scratch paths scrubbed with same-length replacements.", + "exitCode": -9 +} diff --git a/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server-wrapped.txt b/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server-wrapped.txt new file mode 100644 index 00000000000..1d141719a58 --- /dev/null +++ b/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server-wrapped.txt @@ -0,0 +1,17 @@ +78[?25h[?25l[?2004h[?2031h[?1004h +──────────────────────────────────────────── +NewMCPserverfoundinthisproject: +scratch-echo + +MCPserversmayexecutecodeoraccess +systemresources.Alltoolcallsrequire +approval.Learnmoreinthe]8;id=c415zw;https://code.claude.com/docs/en/mcpMCP ]8;; +]8;id=c415zw;https://code.claude.com/docs/en/mcpdocumentation]8;;. + +UsethisMCPserver +UsethisandallfutureMCPserversin +thisproject +❯ContinuewithoutusingthisMCPserver + +Entertoconfirm·Esctocancel +[>0q[?u]7501;? \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server.meta.json b/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server.meta.json new file mode 100644 index 00000000000..38ce07e7fa2 --- /dev/null +++ b/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server.meta.json @@ -0,0 +1,12 @@ +{ + "capturedAt": "2026-11-02T00:00:00.000Z", + "platform": "darwin", + "command": ["claude"], + "env": { + "TERM": "xterm-256color" + }, + "cols": 100, + "rows": 30, + "note": "Claude Code 2.1.316; real PTY with a throwaway CLAUDE_CONFIG_DIR and HOME in an already-trusted scratch git repo; a project .mcp.json declares one new server. No keys sent; capture ends with the startup menu owning the screen. Fake API key and scratch paths scrubbed with same-length replacements.", + "exitCode": -9 +} diff --git a/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server.txt b/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server.txt new file mode 100644 index 00000000000..89da945dd9b --- /dev/null +++ b/src/main/runtime/__fixtures__/claude-2-1-316-startup-mcp-server.txt @@ -0,0 +1,13 @@ +78[?25h[?25l[?2004h[?2031h[?1004h +──────────────────────────────────────────────────────────────────────────────────────────────────── +NewMCPserverfoundinthisproject:scratch-echo + +MCPserversmayexecutecodeoraccesssystemresources.Alltoolcallsrequireapproval.Learn +moreinthe]8;id=c415zw;https://code.claude.com/docs/en/mcpMCP documentation]8;;. + +UsethisMCPserver +UsethisandallfutureMCPserversinthisproject +❯ContinuewithoutusingthisMCPserver + +Entertoconfirm·Esctocancel +[>0q[?u]7501;? \ No newline at end of file diff --git a/src/main/runtime/agent-session/agent-session-death-evidence-persistence.test.ts b/src/main/runtime/agent-session/agent-session-death-evidence-persistence.test.ts deleted file mode 100644 index 89fc9fb42b9..00000000000 --- a/src/main/runtime/agent-session/agent-session-death-evidence-persistence.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { closeTestJournalHostDatabases } from '../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import type { AgentSessionDeathEvidence } from '../../../shared/agent-session/lifecycle/agent-session-death-evidence' -import { - agentSessionLeaseFixture, - agentSessionRecordFixture -} from '../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' -import type { AgentSessionRecordStore } from './records/agent-session-record-store' -import { - openTestAgentSessionRecordStore, - seedTestAgentSessionRecordStore -} from './records/agent-session-record-store-test-harness' - -const SESSION = 'session-alpha-1' -const LAST_RENEWED_AT = 30_000 - -let directory: string - -async function seed(deathEvidence: AgentSessionDeathEvidence | null): Promise { - const lease = - deathEvidence === null - ? agentSessionLeaseFixture() - : agentSessionLeaseFixture({ - ownerProcess: null, - reservedSpawnToken: null, - claimStatus: 'released', - deathEvidence - }) - await seedTestAgentSessionRecordStore(directory, { records: [agentSessionRecordFixture(lease)] }) -} - -function open(): Promise { - return openTestAgentSessionRecordStore(directory) -} - -beforeEach(async () => { - directory = await mkdtemp(join(tmpdir(), 'orca-death-evidence-')) -}) - -afterEach(async () => { - await closeTestJournalHostDatabases() - await rm(directory, { recursive: true, force: true }) -}) - -describe('death evidence on disk', () => { - it('records the last renewal before the crash and reads it back after another restart', async () => { - await seed(null) - const crashed = await open() - await crashed.reconcileOnRestart({ - probe: async () => ({ outcome: 'pid-absent' }), - now: 90_000 - }) - const evidence = { - kind: 'pid-absent', - detail: 'recorded pid absent on host', - observedAt: 90_000, - ownerFence: 7, - lastProvenAliveAt: LAST_RENEWED_AT - } - expect(crashed.getRecord(SESSION)?.lease.deathEvidence).toEqual(evidence) - expect((await open()).getRecord(SESSION)?.lease.deathEvidence).toEqual(evidence) - }) -}) diff --git a/src/main/runtime/agent-session/lifecycle/structured-agent-session-tab-authority.test.ts b/src/main/runtime/agent-session/lifecycle/structured-agent-session-tab-authority.test.ts deleted file mode 100644 index 73b39984375..00000000000 --- a/src/main/runtime/agent-session/lifecycle/structured-agent-session-tab-authority.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { beforeEach, expect, it, vi } from 'vitest' -import { folderWorkspaceKey } from '../../../../shared/workspace-scope' -import { - root, - B, - authorityProfile, - openAuthorityRuntime -} from './structured-agent-session-tab-authority.test-support' -import { closeStructuredAgentSessionChild } from '../structured-agent-session-close' - -// CLI capability probing is outside tab authority and must not start a real CLI in this fixture. -vi.mock('../../../claude/claude-cli-flag-prewarm', () => ({ - prewarmClaudeCliFlags: async () => undefined -})) - -const layoutOwner = vi.hoisted(() => ({ main: false })) -vi.mock('../../../../shared/layout-owner-switch', () => ({ - get ORCA_LAYOUT_OWNER_IS_MAIN() { - return layoutOwner.main - } -})) -beforeEach(() => { - layoutOwner.main = false -}) - -it('captured close retires only its qualified workspace and preserves unrelated mirrors', async () => { - const rig = await openAuthorityRuntime(await authorityProfile()) - await rig.host.setSessionTabVisibility(B, true) - rig.runtime.projectStructuredAgentSessionTab({ - workspaceId: rig.workspace, - sessionId: B, - agent: 'codex', - activate: true - }) - const original = rig.runtime.mobileSessionTabsByWorktree.get(rig.workspace)! - const duplicate = rig.profile.createFolderWorkspace({ - projectGroupId: rig.groupId, - folderPath: `${root}/duplicate`, - name: 'Duplicate' - }) - const mirror = rig.profile.createFolderWorkspace({ - projectGroupId: rig.groupId, - folderPath: `${root}/mirror`, - name: 'Mirror', - connectionId: 'foreign' - }) - const duplicateKey = folderWorkspaceKey(duplicate.id), - mirrorKey = folderWorkspaceKey(mirror.id) - rig.runtime.storeMobileSessionSnapshot(duplicateKey, { ...original, worktree: duplicateKey }) - const foreign = rig.runtime.storeMobileSessionSnapshot(mirrorKey, { - ...original, - worktree: mirrorKey - }) - await closeStructuredAgentSessionChild(B, { runtime: rig.runtime }) - expect(rig.runtime.mobileSessionTabsByWorktree.get(rig.workspace)?.tabs).toEqual([]) - expect(rig.runtime.mobileSessionTabsByWorktree.get(duplicateKey)?.tabs).toEqual(original.tabs) - expect(rig.runtime.mobileSessionTabsByWorktree.get(mirrorKey)).toBe(foreign) - expect(rig.runtime.retireStructuredAgentSessionTabFromSnapshot(B)).toBe(false) - expect(rig.runtime.mobileSessionTabsByWorktree.get(mirrorKey)).toBe(foreign) -}) diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts deleted file mode 100644 index f920c23997f..00000000000 --- a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts +++ /dev/null @@ -1,749 +0,0 @@ -import { ClaudeProfileRouter } from '../../../claude-accounts/claude-profile-router' -import { - acquired, - fakeClaude, - identityFor, - recordingJournalSink, - PROVIDER_SESSION_ID -} from '../../../claude/structured/claude-structured-session-test-support' -import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' -import type { Query } from '@anthropic-ai/claude-agent-sdk' -import { createClaudeControlSurface } from '../../../claude/claude-agent-sdk-control-requests' -import { - createStructuredChatNamingHandler, - type StructuredChatNamingDeps -} from '../../../native-chat/structured-chat-naming' -import { compareAndSetAgentSessionRecordName } from '../records/agent-session-record-conversation-name' -import { rm } from 'node:fs/promises' -import { installClaudeProfileRouter } from '../../../claude-accounts/claude-profile-installed-router' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { getDefaultSettings } from '../../../../shared/constants' -import { agentSessionRecordFixture } from '../../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' -import { normalizeSourceControlAiSettings } from '../../../../shared/source-control/ai/settings/source-control-ai-settings' -import { structuredChatNamingDeps } from './structured-chat-naming-runtime' -import type { AgentJournalSnapshot } from '../../../../shared/agent-session/journal/agent-session-journal-types' -import type * as TextGeneration from '../../../text-generation/commit-message-text-generation' -import * as shellEnvironment from '../environment/structured-agent-shell-environment' -import { resolveHostStructuredAgentLaunchEnvironment } from '../launch/structured-agent-launch-support' -import type { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' -import { - createQueuedMessageTestRig, - QUEUED_RIG_CALLER -} from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig.test-fixture' -import { holdDelivery } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-delivery-hold.test-fixture' -import { holdUnsentSends } from '../../../native-chat/agent-session-journal/queued-messages/journal-unsent-send-hold' -import { AgentSessionAcquisitionRootExitObservedError } from '../../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors' -import { AgentSessionStartFailure } from '../../../native-chat/agent-session-wire/startup/structured-agent-session-start-failure' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session/journal/agent-session-journal-types' -import { - HOST_TEST_SESSION, - hostTestOperationId -} from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data' - -const mocks = vi.hoisted(() => ({ - account: vi.fn((_provider: string, id: string) => ({ - XDG_DATA_HOME: `/profiles/${id}/data`, - XDG_STATE_HOME: `/profiles/${id}/state` - })), - native: vi.fn(async () => 'Native title'), - titleOwner: vi.fn(), - host: vi.fn<() => StructuredAgentSessionHost | undefined>(), - record: vi.fn(), - generate: vi.fn(async () => ({ - success: true as const, - name: 'Login repair' - })), - target: vi.fn(async (cwd: string) => ({ kind: 'local' as const, cwd })), - publishConversationName: vi.fn<(sessionId: string) => void>(), - journalCurrentRead: vi.fn<(sessionId: string) => Promise>() -})) - -vi.mock('../../../text-generation/commit-message-text-generation', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, generateConversationNameFromContext: mocks.generate } -}) -vi.mock('../../../agent-hooks/first-work/first-work-generation-target', () => ({ - resolveGenerationTarget: mocks.target -})) -vi.mock('../../../native-chat/agent-session-wire/host/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => - mocks.host() ?? { - deps: { - store: { getRecord: mocks.record }, - adapter: { generateText: mocks.native, captureConversationTitleOwner: mocks.titleOwner } - }, - publishConversationName: mocks.publishConversationName, - journalCurrentRead: mocks.journalCurrentRead - } -})) - -vi.mock('../../../managed-data-accounts/service', () => ({ - getManagedDataAccountService: () => ({ - restoreOriginalEnvironment: () => {}, - environmentForAccount: mocks.account - }) -})) -const roots: string[] = [] -afterEach(async () => { - vi.restoreAllMocks() - vi.useRealTimers() - installClaudeProfileRouter(undefined) - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) -beforeEach(() => { - vi.clearAllMocks() - mocks.titleOwner.mockReset() - mocks.host.mockReset() - mocks.record.mockReset() -}) - -function rig() { - const settings = getDefaultSettings('/isolated') - const settingsListeners = new Set<() => void>() - settings.defaultTuiAgent = 'codex' - settings.sourceControlAi = normalizeSourceControlAiSettings(settings.sourceControlAi) - const runtime = { - resolveWorkspace: vi.fn(async () => ({ - path: '/workspace/folder', - executionHostId: 'local' as const - })), - resolveNamingEnvironment: vi.fn(async (): Promise> => ({ - PATH: '/usr/bin' - })), - getAgentEnvResolvers: vi.fn(() => undefined), - workerTaskTitle: vi.fn(() => null), - retitleOpenTab: vi.fn() - } - const logger = { warn: vi.fn(), error: vi.fn() } - return { - settings, - settingsChanged: () => settingsListeners.forEach((changed) => changed()), - runtime, - logger, - deps: structuredChatNamingDeps( - () => ({ - getSettings: () => settings, - onSettingsChanged: (changed) => { - settingsListeners.add(changed) - return () => { - settingsListeners.delete(changed) - } - } - }), - runtime, - logger - ) - } -} - -describe('structured chat naming runtime', () => { - it('resolves Claude naming inheritance before the deliberate agent launch environment', async () => { - const inherited = { - CLAUDE_CODE_MESSAGING_SOCKET: 'parent-socket', - CLAUDE_CODE_ENTRYPOINT: 'parent-client', - CLAUDE_EFFORT: 'parent-effort', - CLAUDE_CODE_HTTP_PROXY: 'http://user-proxy' - } - vi.spyOn(shellEnvironment, 'resolveHostAgentBaseEnvironment').mockResolvedValue(inherited) - const settings = getDefaultSettings('/isolated') - settings.agentDefaultEnv = { claude: { CLAUDE_EFFORT: 'chosen-effort' } } - const env = await resolveHostStructuredAgentLaunchEnvironment('claude', settings) - expect(env).toMatchObject({ - CLAUDE_EFFORT: 'chosen-effort', - CLAUDE_CODE_HTTP_PROXY: 'http://user-proxy' - }) - expect(env.CLAUDE_CODE_MESSAGING_SOCKET).toBeUndefined() - expect(env.CLAUDE_CODE_ENTRYPOINT).toBeUndefined() - expect( - (await resolveHostStructuredAgentLaunchEnvironment('codex', settings)).CLAUDE_EFFORT - ).toBe('parent-effort') - expect(inherited.CLAUDE_CODE_MESSAGING_SOCKET).toBe('parent-socket') - }) - - it('uses the CLI title only for automatic default naming and honors changed settings', async () => { - const state = rig() - const record = agentSessionRecordFixture() - const pending = Promise.withResolvers() - const generate = vi.fn(() => pending.promise) - mocks.titleOwner.mockReturnValue({ isCurrent: () => true, generate }) - const result = state.deps.generate( - record, - 'Repair login', - () => true, - state.deps.captureAutomaticTitle!(record) - ) - await vi.waitFor(() => expect(generate).toHaveBeenCalled()) - pending.resolve('Broken chat title') - expect(await result).toMatchObject({ name: 'Broken chat title' }) - expect(mocks.generate).not.toHaveBeenCalled() - await state.deps.generate(record, 'Repair login') - expect(mocks.generate).toHaveBeenCalledOnce() - - generate.mockImplementationOnce(async () => { - state.settings.sourceControlAi!.actions!.conversationName = { - commandInputTemplate: 'Custom {basePrompt}' - } - return 'Wrong settings title' - }) - expect( - await state.deps.generate( - record, - 'Repair login', - () => true, - state.deps.captureAutomaticTitle!(record) - ) - ).toEqual({ name: 'Login repair' }) - }) - - it.each(['action', 'shared', 'legacy', 'seeded-default', 'effort', 'template'] as const)( - 'preserves authored %s naming choices without consulting the CLI', - async (choice) => { - const state = rig() - const source = state.settings.sourceControlAi! - if (choice === 'action') { - source.modelOverridesByOperation = { - conversationName: { selectedModelByAgent: { claude: 'opus' } } - } - } - if (choice === 'shared') { - source.selectedModelByAgent = { claude: 'opus' } - } - if (choice === 'legacy') { - state.settings.commitMessageAi!.selectedModelByAgent = { claude: 'opus' } - } - if (choice === 'seeded-default') { - state.settings.commitMessageAi!.selectedModelByAgent = { claude: 'sonnet' } - state.settings.commitMessageAi!.selectedThinkingByModel = { sonnet: 'high' } - } - if (choice === 'effort') { - source.selectedThinkingByModel = { sonnet: 'high' } - } - if (choice === 'template') { - source.actions!.conversationName = { commandInputTemplate: 'Custom {basePrompt}' } - } - const record = agentSessionRecordFixture() - expect( - await state.deps.generate( - record, - 'Repair login', - () => true, - state.deps.captureAutomaticTitle!(record) - ) - ).toEqual({ name: 'Login repair' }) - expect(mocks.titleOwner).not.toHaveBeenCalled() - } - ) - it.each(['grok', 'antigravity'] as const)( - 'codes %s native naming failures without exposing provider text', - async (provider) => { - const state = rig() - const record = agentSessionRecordFixture() - record.provider = provider - for (const outcome of ['throw', 'empty'] as const) { - if (outcome === 'throw') { - mocks.native.mockRejectedValueOnce(new Error('private provider diagnostic')) - } else { - mocks.native.mockResolvedValueOnce('') - } - expect(await state.deps.generate(record, 'Repair login')).toEqual({ - errorCode: `${provider}Failed`, - error: `${provider === 'grok' ? 'Grok' : 'Antigravity'} could not name this chat. Try generating the name again.` - }) - } - } - ) -}) - -function automaticNaming(state: ReturnType, before?: 'prompt' | 'seed') { - let record = agentSessionRecordFixture() - record.sessionId = 'session-1' - record.lease.sessionId = 'session-1' - record.providerHandleChain[0]!.handle.nativeId = PROVIDER_SESSION_ID - const blocked = Promise.withResolvers() - const entered = Promise.withResolvers() - const awaitPreparationRelease = async (stage: 'prompt' | 'seed') => { - if (before === stage) { - entered.resolve() - await blocked.promise - } - } - const store = { - getRecord: () => record, - compareAndSetConversationName: async (_id, name, expected, context, applicable) => - compareAndSetAgentSessionRecordName( - async (apply) => { - if (expected === null) { - await awaitPreparationRelease('seed') - } - record = apply(record) - return record - }, - name, - expected, - context, - applicable - ), - setUserConversationName: vi.fn() - } satisfies NonNullable> - mocks.record.mockImplementation(() => record) - const handler = createStructuredChatNamingHandler({ - ...state.deps, - getStore: () => store, - readFirstPrompt: async () => { - await awaitPreparationRelease('prompt') - return 'Repair login' - }, - wait: async () => {} - }) - return { - handler, - entered: entered.promise, - release: () => blocked.resolve(), - record: () => record, - replace: () => { - record = { ...record, lease: { ...record.lease, runtimeFence: 8 } } - }, - start: () => - handler( - { - sessionId: record.sessionId, - workspaceId: 'workspace-1', - agent: 'claude', - status: 'working', - latestPrompt: 'Repair login', - updatedAt: 1 - }, - { replay: false, firstInputSubmissionKey: 'input-1' } - ) - } -} - -it.each(['prompt', 'seed', 'workspace', 'support'] as const)( - 'retains the accepted input owner while %s preparation is pending', - async (stage) => { - const state = rig() - const blocked = Promise.withResolvers() - const entered = Promise.withResolvers() - if (stage === 'workspace') { - state.runtime.resolveWorkspace.mockImplementationOnce(async () => { - entered.resolve() - await blocked.promise - return { path: '/workspace/folder', executionHostId: 'local' } - }) - } - const naming = automaticNaming( - state, - stage === 'prompt' || stage === 'seed' ? stage : undefined - ) - const control = vi.fn(async () => 'Successor title') - mocks.titleOwner.mockImplementation(() => { - const fence = naming.record().lease.runtimeFence - return { - isCurrent: (current: AgentSessionRecord) => current.lease.runtimeFence === fence, - generate: async (_prompt: string, shouldExecute: () => boolean) => { - if (stage === 'support') { - entered.resolve() - await blocked.promise - } - return shouldExecute() ? control() : null - } - } - }) - naming.start() - await (stage === 'workspace' || stage === 'support' ? entered.promise : naming.entered) - naming.replace() - naming.release() - blocked.resolve() - await vi.waitFor(() => expect(naming.handler.activeSessionIds()).toEqual([])) - expect(control).not.toHaveBeenCalled() - expect(mocks.generate).toHaveBeenCalledOnce() - expect(naming.record().conversationName).toBe('Login repair') - } -) - -it.each([false, true])( - 'bounds timeout fallback to its owner (retired=%s), retries independently, and ignores late CLI results', - async (retired) => { - const state = rig() - const pending = Promise.withResolvers() - const generateSessionTitle = vi.fn(() => pending.promise) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this flow calls only the feature-detected title method. - const controls = createClaudeControlSurface({ generateSessionTitle } as unknown as Query) - let owned = true - mocks.titleOwner.mockReturnValue({ - isCurrent: () => owned, - generate: controls.generateSessionTitle - }) - mocks.generate - .mockResolvedValueOnce({ success: false, error: 'Retry naming' }) - .mockImplementationOnce(async () => { - if (retired) { - owned = false - } - return { success: true, name: 'Recovered name' } - }) - const naming = automaticNaming(state) - vi.useFakeTimers() - naming.start() - await vi.advanceTimersByTimeAsync(30_000) - expect(naming.record().conversationName).toBe(retired ? 'Repair login' : 'Recovered name') - pending.resolve('Late CLI name') - await vi.advanceTimersByTimeAsync(0) - expect(naming.record().conversationName).toBe(retired ? 'Repair login' : 'Recovered name') - expect(generateSessionTitle).toHaveBeenCalledOnce() - expect(mocks.generate).toHaveBeenCalledTimes(2) - expect(naming.handler.activeSessionIds()).toEqual([]) - } -) - -it.each([ - { support: 'unsupported' as const, transition: 'close', response: 'unused' }, - { support: 'unknown' as const, transition: 'replacement', response: 'unused' }, - { support: 'supported' as const, transition: 'replacement', response: 'error' }, - { support: 'supported' as const, transition: 'close', response: 'null' } -])( - 'finishes independent naming after $transition with support=$support and response=$response', - async ({ support, transition, response }) => { - const cli = fakeClaude() - const adapter = await acquired(cli, { cliFlag: async () => support }) - const state = rig() - const naming = automaticNaming(state) - const entered = Promise.withResolvers() - const independent = - Promise.withResolvers< - Awaited> - >() - const control = vi.fn(async () => { - if (response === 'error') { - throw new Error('Optional control rejected') - } - return response === 'null' ? null : 'Wrong live title' - }) - cli.connections[0]!.generateSessionTitle = control - mocks.titleOwner.mockImplementation((record) => adapter.captureConversationTitleOwner(record)) - mocks.generate.mockImplementationOnce(async () => { - entered.resolve() - return independent.promise - }) - try { - naming.start() - await entered.promise - await adapter.closeSession('session-1') - if (transition === 'replacement') { - naming.replace() - await adapter.acquire({ - identity: identityFor(), - fence: 8, - spawnToken: 'replacement', - events: recordingJournalSink() - }) - cli.connections[1]!.generateSessionTitle = control - } - independent.resolve({ success: true, name: 'Independent completion' }) - await vi.waitFor(() => expect(naming.handler.activeSessionIds()).toEqual([])) - expect(naming.record().conversationName).toBe('Independent completion') - expect(control).toHaveBeenCalledTimes(response === 'unused' ? 0 : 1) - } finally { - await adapter.closeAll() - cli.dispose() - } - } -) - -it('discards a retired CLI result and publishes only independent fallback text', async () => { - const cli = fakeClaude() - const adapter = await acquired(cli) - const state = rig() - const naming = automaticNaming(state) - const pending = Promise.withResolvers() - const started = Promise.withResolvers() - cli.connections[0]!.generateSessionTitle = async () => { - started.resolve() - return pending.promise - } - mocks.titleOwner.mockImplementation((record) => adapter.captureConversationTitleOwner(record)) - try { - naming.start() - await started.promise - await adapter.closeSession('session-1') - pending.resolve('Stale CLI title') - await vi.waitFor(() => expect(naming.handler.activeSessionIds()).toEqual([])) - expect(naming.record().conversationName).toBe('Login repair') - } finally { - await adapter.closeAll() - cli.dispose() - } -}) - -it.each(['capture', 'pending result'] as const)( - 'keeps the seed and existing naming failure when account lookup fails at %s', - async (stage) => { - const cli = fakeClaude() - const adapter = await acquired(cli) - const state = rig() - const naming = automaticNaming(state) - const router = new ClaudeProfileRouter({ - getSettings: () => ({ - claudeManagedAccounts: [], - activeClaudeManagedAccountId: null, - agentStatusHooksEnabled: false, - disabledTuiAgents: [] - }), - dataRoot: '/isolated', - userHome: '/users/test', - env: {} - }) - const preparation = vi.spyOn(router, 'preparation') - installClaudeProfileRouter(router) - const unavailable = () => { - throw new Error('Selected account folder missing') - } - const pending = Promise.withResolvers() - const started = Promise.withResolvers() - cli.connections[0]!.generateSessionTitle = async () => { - started.resolve() - return pending.promise - } - mocks.titleOwner.mockImplementation((record) => adapter.captureConversationTitleOwner(record)) - state.runtime.resolveNamingEnvironment.mockImplementation(async () => unavailable()) - try { - if (stage === 'capture') { - preparation.mockImplementation(unavailable) - } - naming.start() - if (stage === 'pending result') { - await started.promise - preparation.mockImplementation(unavailable) - pending.resolve('Unusable account title') - } - await vi.waitFor(() => expect(naming.handler.activeSessionIds()).toEqual([])) - expect(naming.record().conversationName).toBe('Repair login') - expect(naming.handler.failure('session-1')?.messageCode).toBe('agentNotRun') - } finally { - await adapter.closeAll() - cli.dispose() - } - } -) - -async function atRestNaming() { - const state = rig() - const chat = await createQueuedMessageTestRig({ - agent: 'claude', - atRest: true, - starting: true, - restartable: true - }) - await vi.waitFor(() => - expect( - chat.host.collaboratorsForTests().conversationDelivery.loop.isRunning(HOST_TEST_SESSION) - ).toBe(false) - ) - mocks.host.mockReturnValue(chat.host) - const title = vi.fn(async () => 'CLI first handover title') - chat.host.deps.adapter.captureConversationTitleOwner = (_record) => { - const child = chat.host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)?.child - if (!child || child.phase !== 'ready') { - return null - } - const isCurrent = (current: AgentSessionRecord) => - current.lease.runtimeFence === child.fence && - chat.host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)?.child === child - return { isCurrent, generate: title } - } - const handler = createStructuredChatNamingHandler({ ...state.deps, now: () => 0 }) - chat.host.deps.onSessionStatusChanged = handler - chat.host.deps.conversationNaming = handler - const done = () => vi.waitFor(() => expect(handler.activeSessionIds()).toEqual([])) - const seeded = () => - vi.waitFor(() => - expect(chat.store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe('Repair login') - ) - return { state, chat, title, handler, done, seeded } -} - -it.each(['fresh', 'startup retry', 'projected context'] as const)( - 'names an at-rest chat from its first ready handover (%s)', - async (scenario) => { - const { chat, title, done, seeded } = await atRestNaming() - try { - expect(chat.starts).not.toHaveBeenCalled() - const journal = chat.host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)!.journal - if (scenario === 'projected context') { - await journal.replaceEpochItems('handle_forked', 1, []) - expect(journal.cursor().epoch).not.toBe(journal.physicalCursor().epoch) - } - if (scenario === 'startup retry') { - chat.failNextStart( - new AgentSessionAcquisitionRootExitObservedError( - new AgentSessionStartFailure(new Error('Temporary start failure'), 'safe') - ) - ) - } - const sent = chat.send('Repair login') - expect(await sent.result).toMatchObject({ ok: true }) - await seeded() - expect(title).not.toHaveBeenCalled() - expect(mocks.generate).not.toHaveBeenCalled() - await journal.resolveDispatch({ - clientMessageId: 'different-input', - state: 'pending', - fence: chat.store.getRecord(HOST_TEST_SESSION)!.lease.runtimeFence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(title).not.toHaveBeenCalled() - await chat.proveStart() - await done() - expect(chat.dispatch).toHaveBeenCalled() - expect(chat.store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe( - 'CLI first handover title' - ) - expect(title).toHaveBeenCalledOnce() - expect(chat.starts).toHaveBeenCalledTimes(scenario === 'startup retry' ? 2 : 1) - expect(mocks.generate).not.toHaveBeenCalled() - } finally { - await chat.dispose() - } - } -) - -it.each(['same-text rename', 'settings', 'auto-off', 'shutdown', 'Stop', 'close', 'held'] as const)( - 'releases a pending first-input title on %s without adopting a future child', - async (exit) => { - const { chat, state, title, handler, done, seeded } = await atRestNaming() - const preclaim = exit === 'Stop' || exit === 'close' || exit === 'held' ? holdDelivery() : null - let stopping: Promise | undefined - try { - expect(await chat.send('Repair login').result).toMatchObject({ ok: true }) - await seeded() - if (exit === 'same-text rename') { - await handler.setUserName(HOST_TEST_SESSION, 'Repair login', 'rename') - } - if (exit === 'settings') { - state.settings.sourceControlAi!.actions!.conversationName = { - commandInputTemplate: 'Custom {basePrompt}' - } - state.settingsChanged() - } - if (exit === 'auto-off') { - state.settings.nativeChatAutoName = false - state.settingsChanged() - } - if (exit === 'shutdown') { - chat.host.stopDelivery() - } - if (preclaim) { - await preclaim.held - expect(chat.starts).not.toHaveBeenCalled() - if (exit === 'Stop') { - stopping = chat.stop() - } - if (exit === 'close') { - stopping = chat.host.close(HOST_TEST_SESSION, 'user-close') - } - if (exit === 'held') { - await holdUnsentSends( - chat.host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)!.journal, - { - fence: chat.store.getRecord(HOST_TEST_SESSION)!.lease.runtimeFence, - hold: { cause: 'chatClosed' } - } - ) - } - } - await done() - const independent = - exit === 'settings' || exit === 'Stop' || exit === 'close' || exit === 'held' - expect(chat.store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe( - independent ? 'Login repair' : 'Repair login' - ) - expect(mocks.generate).toHaveBeenCalledTimes(independent ? 1 : 0) - expect(title).not.toHaveBeenCalled() - preclaim?.release() - await stopping - if (exit !== 'shutdown' && !preclaim) { - await chat.proveStart() - } - expect(title).not.toHaveBeenCalled() - } finally { - preclaim?.release() - await stopping - await chat.dispose() - } - } -) - -it('retires the selected first-handover source without adopting a replacement child', async () => { - const { chat, title, done } = await atRestNaming() - const entered = Promise.withResolvers() - const result = Promise.withResolvers() - title.mockImplementation(async () => { - entered.resolve() - return result.promise - }) - try { - expect(await chat.send('Repair login').result).toMatchObject({ ok: true }) - await chat.proveStart() - await entered.promise - await chat.host.close(HOST_TEST_SESSION, 'user-close') - const successor = chat.send('A follow-up') - expect(await successor.result).toMatchObject({ ok: true }) - await chat.proveStart() - result.resolve('Stale first CLI title') - await done() - expect(chat.store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe('Login repair') - expect(title).toHaveBeenCalledOnce() - } finally { - result.resolve('Late') - await chat.dispose() - } -}) - -it('finishes Send now naming during delivery even if recording its failure cannot commit', async () => { - const { chat, title, done, seeded } = await atRestNaming() - const release = chat.holdNextStart() - let releaseSecond: (() => void) | undefined - chat.failNextStart(new AgentSessionStartFailure(new Error('Startup refused'), 'never')) - const fields = { command: 'compact' as const } - const command = chat.host.conversationCommand(QUEUED_RIG_CALLER, { - ...fields, - envelope: chat.envelope(fields, 'agentSession.conversationCommand', hostTestOperationId()) - }) - try { - await vi.waitFor(() => expect(chat.starts).toHaveBeenCalledOnce()) - const sent = chat.send('Repair login') - const queued = await sent.result - if (!queued.ok || !('queued' in queued.value)) { - throw new Error('expected a queued receipt') - } - const messageId = queued.value.queued.messageId - expect(await chat.submission(sent.id)).toBeUndefined() - expect(await chat.sendNow(messageId)).toMatchObject({ ok: true }) - expect(await chat.handoff(messageId)).toMatchObject({ - queuedMessageId: messageId, - dispatchState: 'pending' - }) - await seeded() - const journal = chat.host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)!.journal - const failure = vi - .spyOn(journal, 'appendLifecycleBatch') - .mockRejectedValue(new Error('Journal write unavailable')) - releaseSecond = chat.holdNextStart() - release() - await vi.waitFor(() => expect(chat.starts).toHaveBeenCalledTimes(2)) - chat.failNextStart(new AgentSessionStartFailure(new Error('Startup refused'), 'never')) - releaseSecond() - await done() - expect(chat.store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe('Login repair') - expect((await chat.handoff(messageId))?.dispatchState).toBe('pending') - expect(title).not.toHaveBeenCalled() - failure.mockRestore() - } finally { - release() - releaseSecond?.() - vi.restoreAllMocks() - await chat.stop() - await command - await chat.dispose() - } -}) diff --git a/src/main/runtime/agent-session/structured-agent-session-startup-reconcile.test.ts b/src/main/runtime/agent-session/structured-agent-session-startup-reconcile.test.ts index ef06df8ce96..f22ffb49272 100644 --- a/src/main/runtime/agent-session/structured-agent-session-startup-reconcile.test.ts +++ b/src/main/runtime/agent-session/structured-agent-session-startup-reconcile.test.ts @@ -1,13 +1,12 @@ -// Newer records reconcile read-only in memory; bookkeeping write failures must not put startup into Session restore failed. +// Newer records reconcile read-only in memory. import { readFile, mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, expect, it } from 'vitest' import { agentSessionRecordFixture } from '../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' import { journalDatabasePath } from '../../native-chat/agent-session-journal/database/journal-host-database' import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-registry' -import type * as AgentSessionRecordRows from './records/agent-session-record-rows' import { seedTestAgentSessionRecordStore, seedTestAgentSessionStoreFromNewerBuild @@ -18,24 +17,8 @@ import { ensureStructuredAgentSessionHost, stopStructuredAgentSessionRuntime } from './structured-agent-session-runtime' -import { observeStructuredSession } from '../orchestration/terminal-authority/structured-sessions/structured-worker-authority' import { recordingStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' -const writes = vi.hoisted(() => ({ failing: false })) - -vi.mock('./records/agent-session-record-rows', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - writeAgentSessionStoreRows: (...args: Parameters) => { - if (writes.failing) { - throw new Error('disk I/O error') - } - return actual.writeAgentSessionStoreRows(...args) - } - } -}) - let root: string beforeEach(async () => { @@ -43,10 +26,8 @@ beforeEach(async () => { }) afterEach(async () => { - writes.failing = false await stopStructuredAgentSessionRuntime().catch(() => undefined) await closeTestJournalHostDatabases() - vi.restoreAllMocks() await rm(root, { recursive: true, force: true }) }) @@ -61,11 +42,8 @@ async function seedChat(options: { newer?: boolean } = {}) { return { path: journalDatabasePath(root), sessionId: record.sessionId } } -function startupRuntime( - log = recordingStructuredAgentSessionLogger(), - deps?: ConstructorParameters[2] -) { - const runtime = new OrcaRuntimeService(undefined, undefined, deps) +function startupRuntime(log = recordingStructuredAgentSessionLogger()) { + const runtime = new OrcaRuntimeService() // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these are the runtime's own protected members; the test roots the host at `root` and stubs the PTY daemon. const internal = runtime as unknown as { hasPersistedStructuredAgentSessionStore(): boolean @@ -104,74 +82,3 @@ it('finishes startup over records a newer Orca wrote, reads them, and writes not await stopStructuredAgentSessionRuntime() expect(await readFile(path)).toEqual(bytes) }) - -it('finishes startup when the reconcile cannot write, and reports it', async () => { - const { sessionId } = await seedChat() - const log = recordingStructuredAgentSessionLogger() - const runtime = startupRuntime(log) - writes.failing = true - - await expect(runtime.prepareStructuredAgentSessionStartupRestoration()).resolves.toBeUndefined() - - expect(log.entries).toEqual([ - expect.objectContaining({ - fields: { - scope: 'lease-reconcile', - error: expect.objectContaining({ message: 'disk I/O error' }) - } - }) - ]) - expect(getStructuredAgentSessionHost()?.sessionAgent(sessionId)).toBe('claude') -}) - -it('closes a chat tab over records a newer Orca wrote, reporting the index it cannot write', async () => { - const { sessionId } = await seedChat({ newer: true }) - const log = recordingStructuredAgentSessionLogger() - const runtime = startupRuntime(log) - await runtime.prepareStructuredAgentSessionStartupRestoration() - const host = getStructuredAgentSessionHost() - const close = vi.spyOn(host!, 'close') - vi.spyOn(runtime, 'captureStructuredAgentSessionPresentation').mockReturnValue({ - raw: null, - saved: [] - }) - vi.spyOn(runtime, 'currentLocalStructuredSessionPresentation').mockReturnValue(null) - const { captureStructuredSessionSurface, closeCapturedStructuredSession } = - await import('./structured-agent-session-close') - expect(host).not.toBeNull() - if (!host) { - throw new Error('Expected installed host') - } - await expect( - closeCapturedStructuredSession( - host, - sessionId, - 'user-close', - captureStructuredSessionSurface(host, sessionId, runtime), - runtime - ) - ).resolves.toBe(false) - - expect(log.entries).toContainEqual({ - level: 'warn', - message: 'recording a closed chat tab failed', - fields: { - scope: 'tab-close-hide', - sessionId, - error: expect.objectContaining({ - refusal: expect.objectContaining({ details: { reason: 'journalWrittenByNewerOrca' } }) - }) - } - }) - expect(close).toHaveBeenCalledWith(sessionId, 'user-close') -}) - -it('settles a chat worker that died with the last run when orchestration restores its workers', async () => { - const { sessionId } = await seedChat() - // A host without recoverable PTYs restores no terminal workers, only chats. - const runtime = startupRuntime(undefined, { canRecoverPersistentLocalPtys: () => false }) - - await runtime.refreshRestoredOrchestrationAuthority() - - expect(observeStructuredSession(sessionId).status).toBe('exited') -}) diff --git a/src/main/runtime/agent-state-rules/blocked-text-layer.ts b/src/main/runtime/agent-state-rules/blocked-text-layer.ts index 307e42e9788..38cd8d636b3 100644 --- a/src/main/runtime/agent-state-rules/blocked-text-layer.ts +++ b/src/main/runtime/agent-state-rules/blocked-text-layer.ts @@ -12,7 +12,7 @@ import { // Any pane can contain another agent's dialog; the latest live blocker wins. const BUILT_IN_SENTINEL_RE = - /update available|choose working directory to|codex just got an upgrade|available\s*\u00B7|esc\s*skip|enter\s*confirm\s*\u00B7|enter\/esc\s*(?:continue|confirm)|hooks need review|do you trust|trust this|trusted workspace|press enter to (?:confirm|continue|view|insert)|press t to trust|permission required|requires permission|allow once|allow always/ + /update available|choose working directory to|codex just got an upgrade|available\s*\u00B7|esc\s*skip|enter\s*confirm\s*\u00B7|enter\/esc\s*(?:continue|confirm)|hooks need review|do you trust|trust this|trusted workspace|press enter to (?:confirm|continue|view|insert)|press t to trust|new\s*mcp\s*servers?\s*found|custom\s*api\s*key|bypass\s*permissions\s*mode|external\s*claude\.md|permission required|requires permission|allow once|allow always/ /** Cheap negative test; identity remains stable until rules change for caller caches. */ export const terminalWaitBlockedSentinelRe = compiledFromActiveAgentStateRules( diff --git a/src/main/runtime/construction/orca-runtime.test.ts b/src/main/runtime/construction/orca-runtime.test.ts index de646ef3264..f0ca09dcef6 100644 --- a/src/main/runtime/construction/orca-runtime.test.ts +++ b/src/main/runtime/construction/orca-runtime.test.ts @@ -31,7 +31,6 @@ await import('../orca-runtime-tests/pty-title-status.spec') await import('../orca-runtime-tests/terminal-side-effect-facts.spec') await import('../orca-runtime-tests/terminal-side-effect-facts-part-02.spec') await import('../orca-runtime-tests/terminal-side-effect-facts-part-03.spec') -await import('../orca-runtime-tests/decorative-title-fact-throttle.spec') await import('../orca-runtime-tests/headless-snapshots.spec') await import('../orca-runtime-tests/headless-snapshots-part-02.spec') await import('../orca-runtime-tests/agent-status-and-waits.spec') @@ -39,7 +38,6 @@ await import('../orca-runtime-tests/agent-status-and-waits-part-02.spec') await import('../orca-runtime-tests/agent-status-and-waits-part-03.spec') await import('../orca-runtime-tests/terminal-creation-and-readiness.spec') await import('../orca-runtime-tests/terminal-creation-and-readiness-part-02.spec') -await import('../orca-runtime-tests/terminal-creation-and-readiness-part-03.spec') await import('../orca-runtime-tests/terminal-creation-and-readiness-part-04.spec') await import('../orca-runtime-tests/terminal-creation-and-readiness-part-05.spec') await import('../orca-runtime-tests/terminal-creation-and-readiness-part-06.spec') @@ -103,7 +101,6 @@ await import('../orca-runtime-tests/worktree-setup-and-startup-part-03.spec') await import('../orca-runtime-tests/worktree-setup-and-startup-part-04.spec') await import('../orca-runtime-tests/worktree-setup-single-creator.spec') await import('../orca-runtime-tests/gitlab-and-pr-bases-part-02.spec') -await import('../orca-runtime-tests/gitlab-and-pr-bases-part-03.spec') await import('../orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec') await import('../orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec') await import('../orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec') diff --git a/src/main/runtime/integrations/git/runtime-branch-switch-host.test.ts b/src/main/runtime/integrations/git/runtime-branch-switch-host.test.ts deleted file mode 100644 index c7b5040da27..00000000000 --- a/src/main/runtime/integrations/git/runtime-branch-switch-host.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { createBranchSwitchHost } from './runtime-branch-switch-host' -import type { RuntimeStore } from '../../construction/runtime-store-contract' -import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' - -vi.mock('../../../persistence/host-qualified-worktree-meta', () => ({ - worktreeRowTarget: (_store: unknown, worktree: unknown) => worktree -})) - -it('keeps automatic naming after commit checkout while preserving branch-link clearing', () => { - const meta = { linkedPR: 42, branchNameIsUserChosen: false } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the switch callback only reads and updates this metadata fixture. - const store = { - getWorktreeMetaForHost: () => meta, - setWorktreeMeta: (_target: unknown, updates: Partial) => - Object.assign(meta, updates) - } as unknown as RuntimeStore - const host = createBranchSwitchHost({ - getStore: () => store, - readAgentRows: () => [], - readAgentPaneRows: () => [], - ptys: () => [], - paneOf: () => ({ tabId: null, paneKey: null }), - terminalHandlesOf: () => [], - hasSyncedTab: () => false, - savedTabIds: () => [], - probeProcess: async () => null, - notifyBranchChanged: () => {}, - folderWorkspacePaths: () => new Map() - }) - const worktree = { id: 'r::/repo', hostId: 'local' as const, repoId: 'r' } - host.recordBranchSwitched(worktree, true) - expect(meta).toMatchObject({ linkedPR: null, branchNameIsUserChosen: false }) - host.recordBranchSwitched(worktree) - expect(meta.branchNameIsUserChosen).toBe(true) -}) diff --git a/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts b/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts index 6f5b09d0283..20f26c42aa0 100644 --- a/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts +++ b/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts @@ -1,4 +1,4 @@ -import type { OrcaCloudAuthConfig } from '../../orca-profiles/profile-cloud-auth-config' +import type { OrcaCloudAuthConfig } from '../../orca-profiles/cloud-auth/profile-cloud-auth-config' import type { MobilePairingConnectionContext } from '../rpc/server/runtime-rpc-pairing-types' import type { OrcaRuntimeRpcServer } from '../rpc/server/runtime-rpc' import type { diff --git a/src/main/runtime/mobile-cloud-relay/relay-auth-context.ts b/src/main/runtime/mobile-cloud-relay/relay-auth-context.ts index 5b62672fcea..6f4b751dec0 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-auth-context.ts +++ b/src/main/runtime/mobile-cloud-relay/relay-auth-context.ts @@ -1,6 +1,6 @@ -import type { OrcaCloudAuthConfig } from '../../orca-profiles/profile-cloud-auth-config' +import type { OrcaCloudAuthConfig } from '../../orca-profiles/cloud-auth/profile-cloud-auth-config' import { ensureActiveOrcaProfile } from '../../orca-profiles/profile-index-store' -import { readFreshOrcaCloudSession } from '../../orca-profiles/profile-cloud-session-refresh' +import { readFreshOrcaCloudSession } from '../../orca-profiles/cloud-session/profile-cloud-session-refresh' import type { RelayAuthContext } from './relay-auth-identity' export async function readRelayAuthContext( diff --git a/src/main/runtime/mobile-cloud-relay/relay-session-broker-contract.ts b/src/main/runtime/mobile-cloud-relay/relay-session-broker-contract.ts index 488a31a1463..033bfefc318 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-session-broker-contract.ts +++ b/src/main/runtime/mobile-cloud-relay/relay-session-broker-contract.ts @@ -1,5 +1,5 @@ import type WebSocket from 'ws' -import type { OrcaCloudAuthConfig } from '../../orca-profiles/profile-cloud-auth-config' +import type { OrcaCloudAuthConfig } from '../../orca-profiles/cloud-auth/profile-cloud-auth-config' import type { MobileRelayStatusPublisher } from '../../../shared/remote-runtime/relay/mobile-relay-status' import type { E2EEKeypair } from '../rpc/server/pairing/e2ee-keypair' import type { MobileSocketWiring } from '../rpc/mobile-socket-wiring' diff --git a/src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts b/src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts index 4c1d8db32d5..fab3ff38b1b 100644 --- a/src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts +++ b/src/main/runtime/mobile-cloud-relay/relay-session-broker.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import nacl from 'tweetnacl' -import type { OrcaCloudAuthConfig } from '../../orca-profiles/profile-cloud-auth-config' +import type { OrcaCloudAuthConfig } from '../../orca-profiles/cloud-auth/profile-cloud-auth-config' import type { RelayHostHelloAckMessage } from './relay-control-protocol' import type * as RelayHttpClientModule from './relay-http-client' @@ -89,19 +89,11 @@ vi.mock('../rpc/relay-transport', () => ({ })) import { RelaySessionBroker } from './relay-session-broker' -import { StaleRelayBrokerError } from './relay-session-broker-contract' -import { RelayHttpError } from './relay-http-client' -import { RelayAuthCoordinator } from './relay-auth-coordinator' -import type { RelayAuthContext } from './relay-auth-identity' -import { RELAY_HOST_CLOSE_REASON } from '../../../shared/relay-host-close-reason' +import './relay-session-broker-contract' +import './relay-http-client' +import './relay-auth-coordinator' -function deferred() { - let resolve!: (value: T) => void - const promise = new Promise((resolvePromise) => { - resolve = resolvePromise - }) - return { promise, resolve } -} +import '../../../shared/relay-host-close-reason' describe('RelaySessionBroker lifecycle ownership', () => { beforeEach(() => { @@ -138,378 +130,6 @@ describe('RelaySessionBroker lifecycle ownership', () => { expect(onStatus).toHaveBeenLastCalledWith('offline') }) - it('closes partially opened resources without publishing stale state', async () => { - const controlAck = deferred() - fakes.controlConnect.mockReturnValue(controlAck.promise) - let current = true - const statuses: string[] = [] - const keypair = nacl.box.keyPair() - const detachTransport = vi.fn() - const connecting = RelaySessionBroker.connect({ - authConfig: { - relayTokenEndpoint: 'https://auth.example.test/v1/relay-token', - relayDirectorUrl: 'https://relay.example.test' - } as OrcaCloudAuthConfig, - accessToken: 'access-token', - identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' }, - keypair: { - ...keypair, - publicKeyB64: Buffer.from(keypair.publicKey).toString('base64') - }, - appVersion: '1.0.0', - mobileSocketWiring: { attachTransport: vi.fn(() => detachTransport) } as never, - isCurrent: () => current, - refreshAccessToken: async () => ({ accessToken: null }), - onStatus: (status) => statuses.push(status) - }) - await vi.waitFor(() => expect(fakes.controls).toHaveLength(1)) - const transportStopped = deferred() - fakes.transports[0]!.stop.mockReturnValue(transportStopped.promise) - current = false - controlAck.resolve({ - type: 'host-hello-ack', - v: 1, - generation: 1, - controlResumeSecret: 'A'.repeat(43), - leaseExpiresAt: 1_000_000, - activeConnIds: [], - pendingConns: [] - }) - - await expect(connecting).rejects.toBeInstanceOf(StaleRelayBrokerError) - expect(fakes.controls[0]!.closeNow).toHaveBeenCalledOnce() - expect(fakes.transports[0]!.stop).toHaveBeenCalledOnce() - expect(detachTransport).not.toHaveBeenCalled() - transportStopped.resolve(undefined) - await vi.waitFor(() => expect(detachTransport).toHaveBeenCalledOnce()) - expect(statuses).toEqual(['connecting']) - }) - - it('fails connect when the control closes before origin activation', async () => { - // hello-ack and close can share a parser turn; never publish already-closed control. - fakes.controlConnect.mockImplementationOnce(async () => { - fakes.controls[0]!.options.onClose(1006) - return { - type: 'host-hello-ack', - v: 1, - generation: 1, - controlResumeSecret: 'A'.repeat(43), - leaseExpiresAt: 1_000_000, - activeConnIds: [], - pendingConns: [] - } satisfies RelayHostHelloAckMessage - }) - const statuses: string[] = [] - - await expect( - RelaySessionBroker.connect(brokerOptions({ onStatus: (status) => statuses.push(status) })) - ).rejects.toThrow('relay_control_closed_before_activation') - - expect(statuses).not.toContain('registered') - expect(statuses.at(-1)).toBe('offline') - await vi.waitFor(() => expect(fakes.transports[0]!.stop).toHaveBeenCalled()) - }) - - it('activates a new origin while keeping basis-bound work on the drained origin', async () => { - const firstAck: RelayHostHelloAckMessage = { - type: 'host-hello-ack', - v: 1, - generation: 1, - controlResumeSecret: 'A'.repeat(43), - leaseExpiresAt: 1_000_000, - activeConnIds: [], - pendingConns: [] - } - fakes.controlConnect.mockResolvedValueOnce(firstAck).mockResolvedValueOnce({ - ...firstAck, - generation: 2, - controlResumeSecret: 'B'.repeat(43) - }) - fakes.assign - .mockResolvedValueOnce(relayAssignment('https://relay-c1.example.test', 1)) - .mockResolvedValueOnce(relayAssignment('https://relay-c2.example.test', 2)) - const resolvePreferredRegion = vi - .fn() - .mockResolvedValueOnce('asia-east2') - .mockResolvedValueOnce('us-central1') - const broker = await RelaySessionBroker.connect( - brokerOptions({ - onStatus: vi.fn(), - resolvePreferredRegion - }) - ) - expect(fakes.assign).toHaveBeenNthCalledWith( - 1, - expect.objectContaining({ - preferredRegion: 'asia-east2', - reconnect: true, - // Rate-gate waits depend on superseded-caller fencing. - isCurrent: expect.any(Function) - }) - ) - const wiredIsCurrent = (fakes.assign.mock.calls[0]![0] as { isCurrent: () => boolean }) - .isCurrent - expect(wiredIsCurrent()).toBe(true) - fakes.controls[0]!.options.onConnectionOpen({ - connId: 'old-basis', - connTicket: 'T'.repeat(43), - kind: 'resume', - relayDeviceId: 'device-1', - attachDeadlineMs: 1_000 - }) - fakes.controls[0]!.options.onDrain({ - type: 'drain', - graceMs: 30_000, - recovery: 'resolve-director' - }) - await vi.waitFor(() => expect(fakes.controls).toHaveLength(2)) - - expect(fakes.assign).toHaveBeenNthCalledWith( - 2, - expect.objectContaining({ preferredRegion: 'us-central1', reconnect: true }) - ) - expect(resolvePreferredRegion).toHaveBeenCalledTimes(2) - - expect(broker.endpoint?.cellUrl).toBe('https://relay-c2.example.test') - expect(fakes.transports[0]!.openConnection).toHaveBeenCalledOnce() - expect(fakes.controls[0]!.closeNow).not.toHaveBeenCalled() - expect(fakes.transports[0]!.stop).not.toHaveBeenCalled() - await broker.confirmResume('old-basis', 'confirm-1') - expect(fakes.controls[0]!.confirmResume).toHaveBeenCalledWith('old-basis', 'confirm-1') - await broker.installCredential( - 'device-1', - { reqId: 'install-1', newResumeTokenHash: 'H'.repeat(43) }, - { mode: 'relay-basis', basisConnId: 'old-basis' } - ) - expect(fakes.controls[0]!.installCredential).toHaveBeenCalledOnce() - }) - - it('rebinds the same process generation with its control resume secret', async () => { - const ack: RelayHostHelloAckMessage = { - type: 'host-hello-ack', - v: 1, - generation: 7, - controlResumeSecret: 'R'.repeat(43), - leaseExpiresAt: 1_000_000, - activeConnIds: ['existing-basis'], - pendingConns: [] - } - fakes.controlConnect.mockResolvedValueOnce(ack).mockResolvedValueOnce({ - ...ack, - leaseExpiresAt: 2_000_000 - }) - fakes.assign - .mockResolvedValueOnce(relayAssignment('https://relay.example.test', 1)) - .mockResolvedValueOnce(relayAssignment('https://relay.example.test', 1)) - const broker = await RelaySessionBroker.connect(brokerOptions()) - fakes.controls[0]!.options.onDrain({ - type: 'drain', - graceMs: 5_000, - recovery: 'resolve-director' - }) - await vi.waitFor(() => expect(fakes.controls).toHaveLength(2)) - - expect(fakes.transports).toHaveLength(1) - expect(fakes.controls[1]!.options.previousGeneration).toBe(7) - expect(fakes.controls[1]!.options.controlResumeSecret).toBe('R'.repeat(43)) - await broker.confirmResume('existing-basis', 'confirm-1') - expect(fakes.controls[1]!.confirmResume).toHaveBeenCalledOnce() - }) - - it('reports the assigned cell each time an origin registers', async () => { - fakes.controlConnect.mockResolvedValue({ - type: 'host-hello-ack', - v: 1, - generation: 1, - controlResumeSecret: 'A'.repeat(43), - leaseExpiresAt: 1_000_000, - activeConnIds: [], - pendingConns: [] - } satisfies RelayHostHelloAckMessage) - fakes.assign - .mockResolvedValueOnce(relayAssignment('https://cell-a.relay.example.test', 1)) - .mockResolvedValueOnce(relayAssignment('https://cell-b.relay.example.test', 2)) - const onAssignedCellActive = vi.fn() - - await RelaySessionBroker.connect(brokerOptions({ onAssignedCellActive })) - expect(onAssignedCellActive.mock.calls).toEqual([['https://cell-a.relay.example.test']]) - fakes.controls[0]!.options.onDrain({ - type: 'drain', - graceMs: 5_000, - recovery: 'resolve-director' - }) - await vi.waitFor(() => expect(onAssignedCellActive).toHaveBeenCalledTimes(2)) - expect(onAssignedCellActive).toHaveBeenLastCalledWith('https://cell-b.relay.example.test') - }) - - it('attaches a phone whose accept straddles a control rebind', async () => { - const ack: RelayHostHelloAckMessage = { - type: 'host-hello-ack', - v: 1, - generation: 7, - controlResumeSecret: 'R'.repeat(43), - leaseExpiresAt: 1_000_000, - activeConnIds: [], - pendingConns: [] - } - fakes.controlConnect.mockResolvedValueOnce(ack).mockResolvedValueOnce({ - ...ack, - leaseExpiresAt: 2_000_000, - // Drain must replay once-announced connections or their phones hit the 10s attach deadline (4404). - pendingConns: [{ connId: 'straddling-basis', connTicket: 'T'.repeat(43) }] - }) - fakes.assign.mockResolvedValue(relayAssignment('https://relay.example.test', 1)) - const broker = await RelaySessionBroker.connect(brokerOptions()) - fakes.controls[0]!.options.onConnectionOpen({ - connId: 'straddling-basis', - connTicket: 'T'.repeat(43), - kind: 'invite', - relayDeviceId: 'device-1', - attachDeadlineMs: 10_000 - }) - fakes.transports[0]!.openConnection.mockClear() - - fakes.controls[0]!.options.onDrain({ - type: 'drain', - graceMs: 5_000, - recovery: 'resolve-director' - }) - await vi.waitFor(() => expect(fakes.controls).toHaveLength(2)) - - expect(fakes.transports).toHaveLength(1) - await vi.waitFor(() => - expect(fakes.transports[0]!.openConnection).toHaveBeenCalledWith({ - type: 'conn-open', - connId: 'straddling-basis', - connTicket: 'T'.repeat(43), - kind: 'invite', - relayDeviceId: 'device-1', - attachDeadlineMs: 10_000 - }) - ) - await broker.confirmResume('straddling-basis', 'confirm-replay') - expect(fakes.controls[1]!.confirmResume).toHaveBeenCalledWith( - 'straddling-basis', - 'confirm-replay' - ) - }) - - it('opens a fresh same-cell generation when process-local rebind state is lost', async () => { - const ack: RelayHostHelloAckMessage = { - type: 'host-hello-ack', - v: 1, - generation: 7, - controlResumeSecret: 'R'.repeat(43), - leaseExpiresAt: 1_000_000, - activeConnIds: [], - pendingConns: [] - } - fakes.controlConnect - .mockResolvedValueOnce(ack) - .mockRejectedValueOnce(new Error('relay_control_closed_4401')) - .mockResolvedValueOnce({ - ...ack, - generation: 1, - controlResumeSecret: 'N'.repeat(43), - leaseExpiresAt: 2_000_000 - }) - fakes.assign - .mockResolvedValueOnce(relayAssignment('https://relay.example.test', 1)) - .mockResolvedValueOnce(relayAssignment('https://relay.example.test', 1)) - const onStatus = vi.fn() - const broker = await RelaySessionBroker.connect(brokerOptions({ onStatus })) - - fakes.controls[0]!.options.onClose(1006) - await vi.waitFor(() => expect(fakes.controls).toHaveLength(3)) - - expect(fakes.controls[1]!.options.previousGeneration).toBe(7) - expect(fakes.controls[1]!.options.controlResumeSecret).toBe('R'.repeat(43)) - expect(fakes.controls[2]!.options.previousGeneration).toBeUndefined() - expect(fakes.controls[2]!.options.controlResumeSecret).toBeUndefined() - expect(fakes.transports).toHaveLength(2) - await vi.waitFor(() => - expect(onStatus).toHaveBeenLastCalledWith('registered', 'https://relay.example.test') - ) - expect(broker.endpoint?.cellUrl).toBe('https://relay.example.test') - }) - - it('backs off drain resolution failures without duplicate retries or post-close work', async () => { - vi.useFakeTimers() - try { - const ack: RelayHostHelloAckMessage = { - type: 'host-hello-ack', - v: 1, - generation: 1, - controlResumeSecret: 'R'.repeat(43), - leaseExpiresAt: 1_000_000, - activeConnIds: [], - pendingConns: [] - } - fakes.controlConnect.mockResolvedValue(ack) - fakes.assign - .mockResolvedValueOnce(relayAssignment('https://relay.example.test', 1)) - .mockRejectedValue(new Error('director_unavailable')) - const broker = await RelaySessionBroker.connect(brokerOptions({ random: () => 0.5 })) - const drain = { - type: 'drain' as const, - graceMs: 5_000, - recovery: 'resolve-director' as const - } - - fakes.controls[0]!.options.onDrain(drain) - await vi.advanceTimersByTimeAsync(0) - expect(fakes.assign).toHaveBeenCalledTimes(2) - fakes.controls[0]!.options.onDrain(drain) - await vi.advanceTimersByTimeAsync(499) - expect(fakes.assign).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(1) - expect(fakes.assign).toHaveBeenCalledTimes(3) - await vi.advanceTimersByTimeAsync(999) - expect(fakes.assign).toHaveBeenCalledTimes(3) - await vi.advanceTimersByTimeAsync(1) - expect(fakes.assign).toHaveBeenCalledTimes(4) - - broker.closeNow() - await vi.advanceTimersByTimeAsync(5 * 60_000) - expect(fakes.assign).toHaveBeenCalledTimes(4) - } finally { - vi.useRealTimers() - } - }) - - it('does not retry drain resolution before the director Retry-After window', async () => { - vi.useFakeTimers() - try { - const ack: RelayHostHelloAckMessage = { - type: 'host-hello-ack', - v: 1, - generation: 1, - controlResumeSecret: 'R'.repeat(43), - leaseExpiresAt: 1_000_000, - activeConnIds: [], - pendingConns: [] - } - fakes.controlConnect.mockResolvedValue(ack) - fakes.assign - .mockResolvedValueOnce(relayAssignment('https://relay.example.test', 1)) - .mockRejectedValue(new RelayHttpError('assignment', 503, 30_000)) - const broker = await RelaySessionBroker.connect(brokerOptions({ random: () => 0.5 })) - - fakes.controls[0]!.options.onDrain({ - type: 'drain', - graceMs: 5_000, - recovery: 'resolve-director' - }) - await vi.advanceTimersByTimeAsync(29_999) - expect(fakes.assign).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(1) - expect(fakes.assign).toHaveBeenCalledTimes(3) - broker.closeNow() - } finally { - vi.useRealTimers() - } - }) - it('recovers through a new origin after the director failure clears', async () => { vi.useFakeTimers() try { @@ -547,60 +167,6 @@ describe('RelaySessionBroker lifecycle ownership', () => { }) // Renewal can discover auth loss before the coordinator; its close must carry the reason. -describe('RelaySessionBroker renewal close reason', () => { - const signedInContext: RelayAuthContext = { - identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' }, - accessToken: 'access-token', - relayEntitled: true - } - - beforeEach(() => { - fakes.controls.length = 0 - fakes.transports.length = 0 - fakes.controlConnect.mockReset().mockResolvedValue({ - type: 'host-hello-ack', - v: 1, - generation: 1, - controlResumeSecret: 'A'.repeat(43), - leaseExpiresAt: 1_000_000, - activeConnIds: [], - pendingConns: [] - } satisfies RelayHostHelloAckMessage) - // An expired lease schedules renewal on the next turn. - fakes.exchange.mockReset().mockResolvedValue({ relayToken: 'relay-jwt', expiresAt: 0 }) - fakes.assign.mockReset().mockResolvedValue(relayAssignment('https://relay.example.test', 1)) - }) - - async function closeReasonAfterRenewalReads( - secondRead: RelayAuthContext | null - ): Promise { - let reads = 0 - const coordinator = new RelayAuthCoordinator({ - readContext: async () => (++reads === 1 ? signedInContext : secondRead), - openBroker: ({ context, isCurrent, refreshAccessToken }) => - RelaySessionBroker.connect( - brokerOptions({ accessToken: context.accessToken, isCurrent, refreshAccessToken }) - ), - onStatus: vi.fn() - }) - coordinator.reconcile() - await vi.waitFor(() => expect(fakes.controls[0]?.closeNow).toHaveBeenCalled()) - coordinator.stop() - return fakes.controls[0]!.closeNow.mock.calls[0]! - } - - it('names the sign-out when its renewal reads the lost session first', async () => { - await expect(closeReasonAfterRenewalReads(null)).resolves.toEqual([ - RELAY_HOST_CLOSE_REASON.SIGNED_OUT - ]) - }) - - it('stays silent when its renewal finds the entitlement gone but the session alive', async () => { - await expect( - closeReasonAfterRenewalReads({ ...signedInContext, relayEntitled: false }) - ).resolves.toEqual([undefined]) - }) -}) function relayAssignment( cellUrl: string, diff --git a/src/main/runtime/orca-runtime-tests/decorative-title-fact-throttle.spec.ts b/src/main/runtime/orca-runtime-tests/decorative-title-fact-throttle.spec.ts deleted file mode 100644 index a32d52ae100..00000000000 --- a/src/main/runtime/orca-runtime-tests/decorative-title-fact-throttle.spec.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { TerminalSideEffectBatch } from '../../../shared/terminal/output/terminal-side-effect-facts' -import { syncSinglePty } from './orca-runtime-test-fixtures.spec' -import { createSideEffectRuntime } from './orca-runtime-test-scenario-builders.spec' -const SPINNER_INTERVAL_MS = 80 -const EPOCH = 1_700_000_000_000 - -type TitleFact = { kind: 'title'; normalizedTitle: string; rawTitle: string } - -function titleFacts(batches: TerminalSideEffectBatch[]): TitleFact[] { - return batches.flatMap((batch) => - batch.facts.filter((fact): fact is TitleFact => fact.kind === 'title') - ) -} - -describe('decorative title fact throttle', () => { - beforeEach(() => { - vi.useFakeTimers({ toFake: ['Date'] }) - vi.setSystemTime(new Date(EPOCH)) - }) - - afterEach(() => { - vi.useRealTimers() - }) - - it('propagates a changed working label immediately even while the spinner rotates', () => { - // Only spinner glyphs are decorative; Grok/Pi label churn changes content. - const { runtime, batches } = createSideEffectRuntime() - syncSinglePty(runtime) - - runtime.ingestSyntheticTitleFrame('pty-1', '\x1b]0;⠋ Claude Code\x07') - vi.setSystemTime(new Date(EPOCH + SPINNER_INTERVAL_MS)) - runtime.ingestSyntheticTitleFrame('pty-1', '\x1b]0;⠙ Reviewing diff — Claude Code\x07') - - expect(titleFacts(batches).map((fact) => fact.rawTitle)).toEqual([ - '⠋ Claude Code', - '⠙ Reviewing diff — Claude Code' - ]) - }) - - it('keeps main-side tracked title state current for every suppressed frame', () => { - // Mobile/remote read tracked records; suppressed facts must not freeze those snapshots. - const { runtime } = createSideEffectRuntime() - syncSinglePty(runtime) - - runtime.ingestSyntheticTitleFrame('pty-1', '\x1b]0;⠋ Claude Code\x07') - vi.setSystemTime(new Date(EPOCH + SPINNER_INTERVAL_MS)) - runtime.ingestSyntheticTitleFrame('pty-1', '\x1b]0;⠙ Claude Code\x07') - - expect(runtime.getTerminalSideEffectSnapshot('pty-1')?.facts).toEqual([ - { kind: 'title', normalizedTitle: '⠙ Claude Code', rawTitle: '⠙ Claude Code' } - ]) - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-03.spec.ts deleted file mode 100644 index e78efcf3e11..00000000000 --- a/src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-03.spec.ts +++ /dev/null @@ -1,41 +0,0 @@ -import * as gitExecFile from '../../git/command-runner/git-exec-file' -import { SshHostNotServedError } from '../../providers/ssh-host-not-served-error' -import { describe, expect, it, vi } from 'vitest' -import './runtime-test-module-registration.spec' -import { OrcaRuntimeService } from '../orca-runtime' -import { getGlabKnownHostsMock } from '../orca-runtime-test-mocks/setup.spec' -import { TEST_REPO_ID, store } from './orca-runtime-test-fixtures.spec' - -describe('OrcaRuntimeService', () => { - it('refuses SSH GitLab MR bases instead of resolving them on this machine', async () => { - const remoteRepo = { - id: TEST_REPO_ID, - path: '/remote/repo', - displayName: 'repo', - badgeColor: 'blue', - addedAt: 1, - connectionId: 'ssh-1', - issueSourcePreference: 'origin' as const - } - const runtimeStore = { - ...store, - getRepos: () => [remoteRepo], - getRepo: (id: string) => (id === remoteRepo.id ? remoteRepo : undefined) - } - const gitSpy = vi.spyOn(gitExecFile, 'gitExecFileAsync') - const runtime = new OrcaRuntimeService(runtimeStore as never) - - await expect( - runtime.resolveManagedMrBase({ - repoSelector: 'id:repo-1', - mrIid: 77, - sourceBranch: 'feature', - targetBranch: 'main', - isCrossRepository: true - }) - ).rejects.toThrow(SshHostNotServedError) - expect(getGlabKnownHostsMock).not.toHaveBeenCalled() - expect(gitSpy).not.toHaveBeenCalled() - gitSpy.mockRestore() - }) -}) diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts deleted file mode 100644 index dea386ce478..00000000000 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts +++ /dev/null @@ -1,57 +0,0 @@ -import 'node:fs/promises' -import { describe, expect, it, vi } from 'vitest' -import '../../preflight/agent-command-detection' -import './runtime-test-module-registration.spec' -import '../../../shared/constants' -import { OrcaRuntimeService } from '../orca-runtime' -import '../../../shared/agent-launch/startup/setup-agent-sequencing' -import { join } from 'node:path' - -import { randomUUID } from 'node:crypto' -import { tmpdir } from 'node:os' -import { - TEST_FOLDER_WORKSPACE_ID, - TEST_FOLDER_WORKSPACE_KEY, - createFolderWorkspaceRuntimeStore, - makeFolderProjectGroup, - makeFolderWorkspace -} from './orca-runtime-test-fixtures.spec' -import '../terminal/launch/spawned-pty-env-fixtures' - -describe('OrcaRuntimeService', () => { - it('rejects folder workspace terminal creation when the backing path is missing', async () => { - const missingPath = join(tmpdir(), `orca-missing-folder-workspace-${randomUUID()}`) - const spawn = vi.fn().mockResolvedValue({ id: 'pty-folder' }) - const folderWorkspace = makeFolderWorkspace({ folderPath: missingPath }) - const projectGroup = makeFolderProjectGroup({ parentPath: missingPath }) - const runtime = new OrcaRuntimeService( - createFolderWorkspaceRuntimeStore(folderWorkspace, projectGroup) as never - ) - runtime.setPtyController({ - spawn, - write: () => true, - kill: () => true, - getForegroundProcess: async () => null - }) - - await expect(runtime.createTerminal(TEST_FOLDER_WORKSPACE_KEY)).rejects.toThrow( - 'folder_workspace_path_missing' - ) - expect(spawn).not.toHaveBeenCalled() - }) - - it('rejects folder workspace folderPath updates when the new path is missing', async () => { - const missingPath = join(tmpdir(), `orca-missing-folder-update-${randomUUID()}`) - const folderWorkspace = makeFolderWorkspace() - const runtimeStore = { - ...createFolderWorkspaceRuntimeStore(folderWorkspace), - updateFolderWorkspace: vi.fn() - } - const runtime = new OrcaRuntimeService(runtimeStore as never) - - await expect( - runtime.updateFolderWorkspace(TEST_FOLDER_WORKSPACE_ID, { folderPath: missingPath }) - ).rejects.toThrow('folder_workspace_path_missing') - expect(runtimeStore.updateFolderWorkspace).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 456f346a079..aecce3dc198 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -61,7 +61,10 @@ import { HEADLESS_RUNTIME_WINDOW_ID } from '../../shared/runtime-session-contrac import { getHostDisplayLabelOverrides } from '../../shared/host-setting-overrides' import type { OrchestrationDb } from './orchestration/db/orchestration-db' import { continueRestoredWorkerMailSoon } from './rpc/methods/orchestration/messaging/settled-worker-follow-through' -import { PeerMailRelay } from './orchestration/federation/peer-mail/peer-mail-relay' +import { + PeerMailRelay, + type PeerServerAnswerStatus +} from './orchestration/federation/peer-mail/peer-mail-relay' import { structuredAgentSessionHostTabId } from '../../shared/agent-session/view/structured-agent-session-host-tab-id' const OrcaRuntimeSidebarBase: typeof OrcaRuntimeWithAgentTransitions = ORCA_SIDEBAR_INPUTS_IS_MAIN @@ -79,6 +82,11 @@ class OrcaRuntimeService extends OrcaRuntimeSidebarBase { this.peerMailRelay.ensure() } + /** What the pull loop last heard from a paired server, without asking it. */ + getPeerServerAnswerStatus(environmentId: string): PeerServerAnswerStatus | undefined { + return this.peerMailRelay?.answerStatus(environmentId) + } + override stopOrchestrationFederationRelay(): void { super.stopOrchestrationFederationRelay() this.peerMailRelay?.stop() diff --git a/src/main/runtime/orchestration/db/decision-gates/decision-gate-store.ts b/src/main/runtime/orchestration/db/decision-gates/decision-gate-store.ts index d169d716031..d3da51cf9fb 100644 --- a/src/main/runtime/orchestration/db/decision-gates/decision-gate-store.ts +++ b/src/main/runtime/orchestration/db/decision-gates/decision-gate-store.ts @@ -4,6 +4,7 @@ import { generateId } from '../generated-id' import type { OrchestrationDb } from '../orchestration-db' import { transitionLifecycleWithDb } from '../lifecycle-transition' import { DISPATCH_CONTEXT_COLUMN_LIST } from '../row-column-lists' +import { remoteHoldOnTask } from '../remote-owned/remote-placements' export function createGate( this: OrchestrationDb, @@ -52,7 +53,7 @@ export function createGate( { taskId: gate.taskId, dispatchId: active?.id } ) } - const activeWorker = this.db + const localWorker = this.db .prepare( `SELECT active.id FROM dispatch_contexts active @@ -62,6 +63,11 @@ export function createGate( ORDER BY active.rowid DESC LIMIT 1` ) .get(gate.taskId) as { id: string } | undefined + // A worker a paired server runs for the Task holds it exactly as a local one does. + const remote = remoteHoldOnTask(this, gate.taskId) + const activeWorker = + localWorker ?? + (remote?.liveWorker ? { id: remote.dispatchId ?? '(a start on a paired server)' } : undefined) if (activeWorker) { throw new OrchestrationError( 'task_not_startable', diff --git a/src/main/runtime/orchestration/db/dispatch-context/attempt-task-settlement.ts b/src/main/runtime/orchestration/db/dispatch-context/attempt-task-settlement.ts new file mode 100644 index 00000000000..99050c0e0bf --- /dev/null +++ b/src/main/runtime/orchestration/db/dispatch-context/attempt-task-settlement.ts @@ -0,0 +1,156 @@ +import type { WorkerReportOutcome, WorkerReportSettlement } from '../orchestration-records' +import type { OrchestrationDb } from '../orchestration-db' +import { + beginLifecycleWriteTransaction, + commitLifecycleWriteTransaction, + rollbackLifecycleWriteTransaction, + transitionLifecycleWithDb +} from '../lifecycle-transition' +import { currentRemoteAttempt, remoteHoldOnTask } from '../remote-owned/remote-placements' + +/** + * The Task half of settlement, shared by every attempt wherever it ran: the Task takes the + * attempt's result and its dependents become ready. `from` is the Task status the result settles: + * dispatched; blocked, for a worker that reconnected; failed, for the unobserved-prompt correction. + */ +export function settleTaskForAttemptResult( + db: OrchestrationDb, + params: { + taskId: string + outcome: WorkerReportOutcome + result: string + from: 'dispatched' | 'blocked' | 'failed' + } +): boolean { + const now = new Date().toISOString() + if (params.from === 'blocked') { + transitionLifecycleWithDb(db.db, { + entity: 'task', + id: params.taskId, + from: 'blocked', + to: 'dispatched' + }) + } + const settled = transitionLifecycleWithDb(db.db, { + entity: 'task', + id: params.taskId, + from: params.from === 'failed' ? 'failed' : 'dispatched', + to: params.outcome === 'succeeded' ? 'completed' : 'failed', + projection: { result: params.result, completed_at: now }, + ...(params.from === 'failed' ? { correction: 'unobserved_prompt_report' as const } : {}) + }) + if (!settled.changed) { + return false + } + if (params.outcome === 'succeeded') { + db.promoteReadyTasks(params.taskId) + } + return true +} + +/** Another attempt of the Task whose worker still runs, here or on a paired server; its result is still to come. */ +export function findConflictingActiveAttempt( + db: OrchestrationDb, + taskId: string, + attemptId: string +): { id: string } | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT over this table returns exactly these columns. + const local = db.db + .prepare( + `SELECT active.id + FROM dispatch_contexts active + JOIN worker_dispatches worker ON worker.dispatch_id = active.id + WHERE active.task_id = ? AND active.id != ? + AND active.status IN ('pending', 'dispatched') + AND worker.state NOT IN ('failed', 'succeeded', 'stopped', 'abandoned') + ORDER BY active.rowid DESC LIMIT 1` + ) + .get(taskId, attemptId) as { id: string } | undefined + const remote = remoteHoldOnTask(db, taskId) + return ( + local ?? + (remote?.liveWorker && remote.dispatchId !== attemptId + ? { id: remote.dispatchId ?? '(a start on a paired server)' } + : undefined) + ) +} + +/** + * A result from the paired server that ran the attempt: it already ran the execution half, so only + * the Task half runs here. The first result stands; a duplicate is a no-op; only the Task's current + * attempt there settles it. The unobserved-prompt correction is the server's decision, carried in. + */ +export function settleRemoteAttemptResult( + this: OrchestrationDb, + params: { + taskId: string + dispatchId: string + outcome: WorkerReportOutcome + result: string + correctedUnobservedPrompt: boolean + } +): WorkerReportSettlement { + const transaction = beginLifecycleWriteTransaction(this.db, 'settle_remote_attempt_result') + try { + const settlement = settleRemoteAttemptResultInTransaction(this, params) + if (settlement.action === 'rejected') { + rollbackLifecycleWriteTransaction(this.db, transaction) + } else { + commitLifecycleWriteTransaction(this.db, transaction) + } + return settlement + } catch (error) { + rollbackLifecycleWriteTransaction(this.db, transaction) + throw error + } +} + +function settleRemoteAttemptResultInTransaction( + db: OrchestrationDb, + params: Parameters[0] +): WorkerReportSettlement { + const task = db.getTask(params.taskId) + if (!task) { + return { action: 'rejected', code: 'unknown_task', reason: `Unknown task ${params.taskId}.` } + } + const expectedTaskStatus = params.outcome === 'succeeded' ? 'completed' : 'failed' + const correcting = params.correctedUnobservedPrompt && task.status === 'failed' + if (!correcting && task.status === expectedTaskStatus) { + return { action: 'settled', outcome: params.outcome, duplicate: true } + } + if (!correcting && task.status !== 'dispatched' && task.status !== 'blocked') { + return { + action: 'rejected', + code: 'inactive_dispatch', + reason: `inactive dispatch ${params.dispatchId}: it or task ${params.taskId} is already settled.` + } + } + if (currentRemoteAttempt(db, params.taskId)?.dispatch_id !== params.dispatchId) { + return { + action: 'rejected', + code: 'stale_dispatch', + reason: `Dispatch ${params.dispatchId} is not the current dispatch for task ${params.taskId}.` + } + } + const conflictingWorker = findConflictingActiveAttempt(db, params.taskId, params.dispatchId) + if (conflictingWorker) { + return { + action: 'rejected', + code: 'inactive_dispatch', + reason: `Task ${params.taskId} still has active supervised Dispatch ${conflictingWorker.id}; stop or settle it before completing ${params.dispatchId}.` + } + } + const settled = settleTaskForAttemptResult(db, { + taskId: params.taskId, + outcome: params.outcome, + result: params.result, + from: correcting ? 'failed' : task.status === 'blocked' ? 'blocked' : 'dispatched' + }) + return settled + ? { action: 'settled', outcome: params.outcome, duplicate: false } + : { + action: 'rejected', + code: 'inactive_dispatch', + reason: `Dispatch ${params.dispatchId} changed while its result was settling.` + } +} diff --git a/src/main/runtime/orchestration/db/dispatch-context/dispatch-context-store.ts b/src/main/runtime/orchestration/db/dispatch-context/dispatch-context-store.ts index 7aac9cae143..9e4a7900871 100644 --- a/src/main/runtime/orchestration/db/dispatch-context/dispatch-context-store.ts +++ b/src/main/runtime/orchestration/db/dispatch-context/dispatch-context-store.ts @@ -14,6 +14,7 @@ import { } from '../../coordinator/dispatch/task-dispatch-refusal' import { dispatchAssigneeOrcaSessionId } from '../../addressing/session-lineage/dispatch-assignee-orca-session-id' import { assertTakesNewWork } from '../worker-terminal/worker-terminal-transfer' +import { retireRemotePlacement } from '../remote-owned/remote-placement-hold' export function createDispatchContext( this: OrchestrationDb, @@ -97,6 +98,8 @@ export function createDispatchContext( from: 'ready', to: 'dispatched' }) + // The Task runs here now; an earlier attempt on a paired server no longer speaks for it. + retireRemotePlacement(this, taskId) const dispatch = this.db .prepare('SELECT * FROM dispatch_contexts WHERE id = ?') .get(id) as DispatchContextRow diff --git a/src/main/runtime/orchestration/db/dispatch-context/task-dispatch-reconciliation.ts b/src/main/runtime/orchestration/db/dispatch-context/task-dispatch-reconciliation.ts index e7deb7fc0ae..7d5d56531ca 100644 --- a/src/main/runtime/orchestration/db/dispatch-context/task-dispatch-reconciliation.ts +++ b/src/main/runtime/orchestration/db/dispatch-context/task-dispatch-reconciliation.ts @@ -39,3 +39,29 @@ export function reconcileTaskAfterDispatchInterruption( to: next }) } + +/** + * A worker lost with its runtime (restart recovery) leaves its Task ready for a fresh start, or + * failed once its retries broke the circuit, while no other attempt runs for it. + */ +export function settleTaskAfterLostWorker( + db: OrchestrationDb, + taskId: string, + to: 'ready' | 'failed' +): void { + const task = db.getTask(taskId) + if ( + !task || + !['dispatched', 'blocked'].includes(task.status) || + getActiveDispatchForTask(db, taskId) + ) { + return + } + transitionLifecycleWithDb(db.db, { + entity: 'task', + id: taskId, + from: task.status, + to, + projection: { completed_at: to === 'failed' ? new Date().toISOString() : null } + }) +} diff --git a/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts b/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts index 4f812539964..d6075d79a4f 100644 --- a/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts +++ b/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts @@ -3,6 +3,11 @@ import type { WorkerReportOutcome, WorkerReportSettlement } from '../orchestrati import type { OrchestrationDb } from '../orchestration-db' import { settleActiveDispatchesForTask } from './dispatch-completion' import { getActiveDispatchForTask } from './task-dispatch-reconciliation' +import { + findConflictingActiveAttempt, + settleTaskForAttemptResult, + settleRemoteAttemptResult +} from './attempt-task-settlement' import { transitionLifecycleWithDb } from '../lifecycle-transition' import { runLifecycleWriteTransaction } from '../lifecycle-write-transaction-runner' import { @@ -131,17 +136,7 @@ export function settleWorkerReportInTransaction( reason: `inactive dispatch ${params.dispatchId}: it or task ${params.taskId} is already settled.` } } - const conflictingWorker = this.db - .prepare( - `SELECT active.id - FROM dispatch_contexts active - JOIN worker_dispatches worker ON worker.dispatch_id = active.id - WHERE active.task_id = ? AND active.id != ? - AND active.status IN ('pending', 'dispatched') - AND worker.state NOT IN ('failed', 'succeeded', 'stopped', 'abandoned') - ORDER BY active.rowid DESC LIMIT 1` - ) - .get(params.taskId, params.dispatchId) as { id: string } | undefined + const conflictingWorker = findConflictingActiveAttempt(this, params.taskId, params.dispatchId) if (conflictingWorker) { return { action: 'rejected', @@ -165,67 +160,41 @@ export function settleWorkerReportInTransaction( .all(params.taskId, params.dispatchId) as { id: string }[] this.db.exec('SAVEPOINT settle_worker_report') - let dispatchUpdate: { changes: number } - let taskUpdate: { changes: number } if (settledByUnobservedPrompt) { // A paired coordinator gets the correction once, after all its writes; see peer_run_corrections. this.db .prepare('INSERT INTO peer_run_corrections (dispatch_id) VALUES (?)') .run(params.dispatchId) - const now = new Date().toISOString() - const dispatchTransition = transitionLifecycleWithDb(this.db, { - entity: 'dispatch', - id: params.dispatchId, - from: dispatch.status, - to: params.outcome === 'succeeded' ? 'completed' : dispatch.status, - projection: { - completed_at: now, - last_failure: params.outcome === 'failed' ? params.result : dispatch.last_failure, - capability_revoked_at: dispatch.capability_revoked_at ?? now - }, - correction: 'unobserved_prompt_report' - }) - const taskTransition = transitionLifecycleWithDb(this.db, { - entity: 'task', - id: params.taskId, - from: 'failed', - to: expectedTaskStatus, - projection: { result: params.result, completed_at: now }, - correction: 'unobserved_prompt_report' - }) - dispatchUpdate = { changes: dispatchTransition.changed ? 1 : 0 } - taskUpdate = { changes: taskTransition.changed ? 1 : 0 } - } else { - if (reconnectingWorker) { - transitionLifecycleWithDb(this.db, { - entity: 'task', - id: params.taskId, - from: 'blocked', - to: 'dispatched' - }) - } - const dispatchTransition = transitionLifecycleWithDb(this.db, { - entity: 'dispatch', - id: params.dispatchId, - from: reconnectingWorker || reportingStart ? ['pending', 'dispatched'] : 'dispatched', - to: expectedDispatchStatus, - projection: { - completed_at: new Date().toISOString(), - last_failure: params.outcome === 'failed' ? params.result : dispatch.last_failure, - capability_revoked_at: dispatch.capability_revoked_at ?? new Date().toISOString() - } - }) - const taskTransition = transitionLifecycleWithDb(this.db, { - entity: 'task', - id: params.taskId, - from: 'dispatched', - to: expectedTaskStatus, - projection: { result: params.result, completed_at: new Date().toISOString() } - }) - dispatchUpdate = { changes: dispatchTransition.changed ? 1 : 0 } - taskUpdate = { changes: taskTransition.changed ? 1 : 0 } } - if (dispatchUpdate.changes !== 1 || taskUpdate.changes !== 1) { + const now = new Date().toISOString() + const dispatchTransition = transitionLifecycleWithDb(this.db, { + entity: 'dispatch', + id: params.dispatchId, + from: settledByUnobservedPrompt + ? dispatch.status + : reconnectingWorker || reportingStart + ? ['pending', 'dispatched'] + : 'dispatched', + to: + params.outcome === 'succeeded' || !settledByUnobservedPrompt + ? expectedDispatchStatus + : dispatch.status, + projection: { + completed_at: now, + last_failure: params.outcome === 'failed' ? params.result : dispatch.last_failure, + capability_revoked_at: dispatch.capability_revoked_at ?? now + }, + ...(settledByUnobservedPrompt ? { correction: 'unobserved_prompt_report' as const } : {}) + }) + const taskSettled = + dispatchTransition.changed && + settleTaskForAttemptResult(this, { + taskId: params.taskId, + outcome: params.outcome, + result: params.result, + from: previousTaskStatus + }) + if (!taskSettled) { this.db.exec('ROLLBACK TO settle_worker_report') this.db.exec('RELEASE settle_worker_report') return { @@ -279,9 +248,6 @@ export function settleWorkerReportInTransaction( for (const sibling of siblingDispatchIds) { this.closeQuestionsForDispatch(sibling.id) } - if (params.outcome === 'succeeded') { - this.promoteReadyTasks(params.taskId) - } if (reportingWorker && this.workerAutoReleaseEnabled?.() !== false) { this.armWorkerTerminalAutoReleaseStatement(params.dispatchId) } @@ -294,11 +260,13 @@ export function settleWorkerReportInTransaction( export type WorkerReportSettlementMethods = { settleWorkerReport: typeof settleWorkerReport settleWorkerReportInTransaction: typeof settleWorkerReportInTransaction + settleRemoteAttemptResult: typeof settleRemoteAttemptResult } export function attachWorkerReportSettlement(ctor: { prototype: object }): void { Object.assign(ctor.prototype, { settleWorkerReport, - settleWorkerReportInTransaction + settleWorkerReportInTransaction, + settleRemoteAttemptResult }) } diff --git a/src/main/runtime/orchestration/db/remote-owned/remote-dispatch-records.ts b/src/main/runtime/orchestration/db/remote-owned/remote-dispatch-records.ts new file mode 100644 index 00000000000..a696a2c0f22 --- /dev/null +++ b/src/main/runtime/orchestration/db/remote-owned/remote-dispatch-records.ts @@ -0,0 +1,301 @@ +import type { OrchestrationDb } from '../orchestration-db' +import { runLifecycleWriteTransaction } from '../lifecycle-write-transaction-runner' +import type { RemoteRunLinkRow } from './remote-run-links' +import { writtenRow } from './written-row' + +export type RemoteDispatchRow = { + dispatch_id: string + conversation_id: string + run_id: string + environment_id: string + task_id: string + status: string + worker_state: string | null + last_failure: string | null + agent: string | null + last_report: string | null + stop_owed: number + stop_count: number + stop_attempt: number + stop_retries: number + stop_retry_at: number | null + stop_last_error: string | null + task_settled_here: number + created_at: string + updated_at: string +} + +const SETTLED_WORKER_STATES = ['succeeded', 'failed', 'stopped', 'abandoned'] +/** `task_settled_here` for an attempt abandoned here, which a retry may follow at once. */ +export const ABANDONED_HERE = 2 +const ACTIVE_DISPATCH_STATUSES = ['pending', 'dispatched'] + +/** Proof the server's worker is done: a settled worker, or a settled context-only Dispatch. */ +export function isRemoteDispatchTerminal( + record: Pick +): boolean { + return record.worker_state === null + ? !ACTIVE_DISPATCH_STATUSES.includes(record.status) + : SETTLED_WORKER_STATES.includes(record.worker_state) +} + +/** Counted as a local Dispatch would be: active while its Dispatch is pending or dispatched there. */ +/** A prior a retry may follow, by the local rule: its worker settled there, or it was abandoned here. */ +export function isRemoteAttemptSettledForRetry( + record: Pick +): boolean { + return ( + record.task_settled_here === ABANDONED_HERE || + (record.worker_state === null + ? record.status === 'failed' + : ['failed', 'stopped', 'abandoned'].includes(record.worker_state)) + ) +} + +export function isRemoteDispatchActive(record: Pick): boolean { + return ACTIVE_DISPATCH_STATUSES.includes(record.status) +} + +export function getRemoteDispatch( + db: OrchestrationDb, + dispatchId: string +): RemoteDispatchRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table returns exactly its row shape. + return db.db.prepare('SELECT * FROM remote_dispatches WHERE dispatch_id = ?').get(dispatchId) as + | RemoteDispatchRow + | undefined +} + +/** Newest first, in one Run or every Run, with the state of the link each came home under. */ +export function listRemoteDispatches( + db: OrchestrationDb, + scope: { runId?: string; limit: number } +): (RemoteDispatchRow & { link_state: RemoteRunLinkRow['state'] | null })[] { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the record's columns plus the joined link state. + return db.db + .prepare( + `SELECT record.*, link.state AS link_state FROM remote_dispatches record + LEFT JOIN remote_run_links link ON link.conversation_id = record.conversation_id + WHERE (? IS NULL OR record.run_id = ?) ORDER BY record.rowid DESC LIMIT ?` + ) + .all(scope.runId ?? null, scope.runId ?? null, scope.limit) as (RemoteDispatchRow & { + link_state: RemoteRunLinkRow['state'] | null + })[] +} + +export function countRemoteDispatches(db: OrchestrationDb, runId: string | undefined): number { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: COUNT(*) returns one number. + const row = db.db + .prepare('SELECT COUNT(*) AS count FROM remote_dispatches WHERE (? IS NULL OR run_id = ?)') + .get(runId ?? null, runId ?? null) as { count: number } + return row.count +} + +/** Identity only: which server runs the Dispatch and for which Task. State comes from the server's queue. */ +export function ensureRemoteDispatchRecord( + db: OrchestrationDb, + link: RemoteRunLinkRow, + identity: { dispatchId: string; taskId: string; agent?: string | null } +): RemoteDispatchRow { + db.db + .prepare( + `INSERT INTO remote_dispatches (dispatch_id, conversation_id, run_id, environment_id, task_id, agent) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(dispatch_id) DO UPDATE SET agent = COALESCE(remote_dispatches.agent, excluded.agent)` + ) + .run( + identity.dispatchId, + link.conversation_id, + link.run_id, + link.environment_id, + identity.taskId, + identity.agent ?? null + ) + return writtenRow(getRemoteDispatch(db, identity.dispatchId), `Dispatch ${identity.dispatchId}`) +} + +/** The server's state for the Dispatch, applied in its queue order. A terminal state sends any stop owed at once: its receipt is now the proof. */ +export function recordRemoteDispatchState( + db: OrchestrationDb, + dispatchId: string, + state: Pick +): RemoteDispatchRow { + const terminal = isRemoteDispatchTerminal(state) + db.db + .prepare( + `UPDATE remote_dispatches SET + status = ?, worker_state = ?, last_failure = ?, agent = COALESCE(?, agent), + stop_retry_at = CASE WHEN ? THEN NULL ELSE stop_retry_at END, + updated_at = datetime('now') + WHERE dispatch_id = ?` + ) + .run( + state.status, + state.worker_state, + state.last_failure, + state.agent, + terminal ? 1 : 0, + dispatchId + ) + return writtenRow(getRemoteDispatch(db, dispatchId), `Dispatch ${dispatchId}`) +} + +export function recordRemoteDispatchReport( + db: OrchestrationDb, + dispatchId: string, + report: string +): void { + db.db + .prepare(`UPDATE remote_dispatches SET last_report = ? WHERE dispatch_id = ?`) + .run(report, dispatchId) +} + +/** + * One stop intent from this Orca: owed until the server's ordinary stop proves the worker and its + * helpers stopped, even for a worker already finished, whose helpers may still run. A retry of an + * intent keeps the count it was first given, so the server replays that stop instead of a new one. + */ +export function oweRemoteDispatchStop( + db: OrchestrationDb, + dispatchId: string, + intentKey: string +): { record: RemoteDispatchRow; stopCount: number } | undefined { + return runLifecycleWriteTransaction(db.db, 'owe_remote_dispatch_stop', () => + oweStopInTransaction(db, dispatchId, intentKey) + ) +} + +function oweStopInTransaction( + db: OrchestrationDb, + dispatchId: string, + intentKey: string +): { record: RemoteDispatchRow; stopCount: number } | undefined { + const record = getRemoteDispatch(db, dispatchId) + if (!record) { + return undefined + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT over this table returns exactly these columns. + const known = db.db + .prepare('SELECT stop_count FROM remote_stop_intents WHERE dispatch_id = ? AND intent_key = ?') + .get(dispatchId, intentKey) as { stop_count: number } | undefined + if (known) { + return { record, stopCount: known.stop_count } + } + db.db + .prepare( + `UPDATE remote_dispatches SET + stop_owed = 1, stop_count = stop_count + 1, stop_attempt = 0, + stop_retries = 0, stop_retry_at = NULL, stop_last_error = NULL + WHERE dispatch_id = ?` + ) + .run(dispatchId) + db.db + .prepare( + 'INSERT INTO remote_stop_intents (dispatch_id, intent_key, stop_count) VALUES (?, ?, ?)' + ) + .run(dispatchId, intentKey, record.stop_count + 1) + return { + record: writtenRow(getRemoteDispatch(db, dispatchId), `Dispatch ${dispatchId}`), + stopCount: record.stop_count + 1 + } +} + +/** The key one attempt at the owed stop goes out under; the server runs each distinct key once. */ +export function remoteStopKey( + record: Pick +): string { + return `stop-${record.stop_count}.${record.stop_attempt}:${record.dispatch_id}` +} + +export function listOwedRemoteStops( + db: OrchestrationDb, + environmentId: string, + now: number +): RemoteDispatchRow[] { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table returns exactly its row shape. + return db.db + .prepare( + `SELECT record.* FROM remote_dispatches record + JOIN remote_run_links link + ON link.conversation_id = record.conversation_id AND link.state = 'open' + WHERE record.environment_id = ? AND record.stop_owed = 1 + AND (record.stop_retry_at IS NULL OR record.stop_retry_at <= ?) + ORDER BY record.rowid` + ) + .all(environmentId, now) as RemoteDispatchRow[] +} + +/** The server no longer has the Dispatch at all; whatever stop was owed for it can never be proven. */ +export function abandonRemoteDispatchStop(db: OrchestrationDb, dispatchId: string): void { + db.db + .prepare( + `UPDATE remote_dispatches SET stop_owed = 0, stop_retry_at = NULL WHERE dispatch_id = ?` + ) + .run(dispatchId) +} + +/** Clears the debt only for the count the proof answered; a newer intent since then stays owed. */ +export function settleRemoteDispatchStop( + db: OrchestrationDb, + dispatchId: string, + stopCount: number +): boolean { + return ( + db.db + .prepare( + `UPDATE remote_dispatches SET stop_owed = 0, stop_retry_at = NULL, stop_last_error = NULL + WHERE dispatch_id = ? AND stop_owed = 1 AND stop_count = ?` + ) + .run(dispatchId, stopCount).changes === 1 + ) +} + +/** How long a resend waits after its `retries`-th unanswered or unproven try, doubling to a minute. */ +export function remoteResendRetryAt(retries: number, now: number): number { + return now + Math.min(2_000 * 2 ** Math.min(retries, 5), 60_000) +} + +/** + * The server answered without proof. The next attempt waits, then goes out under a new key so the + * server's ordinary stop really runs again; a send that got no answer keeps its key. + */ +export function deferRemoteDispatchStop( + db: OrchestrationDb, + record: Pick, + outcome: { answered: boolean; error: string; retryAt: number } +): void { + db.db + .prepare( + `UPDATE remote_dispatches SET + stop_attempt = CASE WHEN ? THEN stop_attempt + 1 ELSE stop_attempt END, + stop_retries = stop_retries + 1, stop_retry_at = ?, stop_last_error = ? + WHERE dispatch_id = ? AND stop_owed = 1 AND stop_count = ? AND stop_attempt = ?` + ) + .run( + outcome.answered ? 1 : 0, + outcome.retryAt, + outcome.error, + record.dispatch_id, + record.stop_count, + record.stop_attempt + ) +} + +export type RemoteOwnedQuestionRow = { + message_id: string + conversation_id: string + run_id: string + environment_id: string + dispatch_id: string +} + +/** A question a remote worker asked here, which its server answers. */ +export function getRemoteOwnedQuestion( + db: OrchestrationDb, + messageId: string +): RemoteOwnedQuestionRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table returns exactly its row shape. + return db.db + .prepare('SELECT * FROM remote_owned_questions WHERE message_id = ?') + .get(messageId) as RemoteOwnedQuestionRow | undefined +} diff --git a/src/main/runtime/orchestration/db/remote-owned/remote-owned-import.ts b/src/main/runtime/orchestration/db/remote-owned/remote-owned-import.ts new file mode 100644 index 00000000000..30c0393d2f4 --- /dev/null +++ b/src/main/runtime/orchestration/db/remote-owned/remote-owned-import.ts @@ -0,0 +1,273 @@ +import { + REMOTE_OWNED_ITEM_KINDS, + type RemoteOwnedWorkerMail, + type RemoteOwnedWorkerState +} from '../../../../../shared/orchestration/remote-owned-wire' +import { OrchestrationError } from '../../orchestration-error' +import type { MessageType } from '../orchestration-records' +import type { OrchestrationDb } from '../orchestration-db' +import { presentImportedPeerItem } from '../../mailbox/formatting/imported-peer-item-presentation' +import { + reconcileTaskAfterDispatchInterruption, + settleTaskAfterLostWorker +} from '../dispatch-context/task-dispatch-reconciliation' +import { runLifecycleWriteTransaction } from '../lifecycle-write-transaction-runner' +import { + abandonRemoteDispatchStop, + isRemoteDispatchTerminal, + recordRemoteDispatchReport, + recordRemoteDispatchState +} from './remote-dispatch-records' +import { + adoptRemoteAttempt, + currentRemoteAttempt, + noteRemoteRunLinkPeerRun +} from './remote-placements' +import { + closeRemoteRunLink, + getRemoteRunLink, + remoteRunLinkPinMatches, + type RemoteRunLinkRow, + type RemoteServerPin +} from './remote-run-links' + +export type PulledRemoteOwnedItem = { + conversationId: string + sequence: number + messageId: string + kind?: string + payload: string +} + +/** Mail to wake its mailbox for once the import commits. */ +export type ImportedRemoteOwnedMail = { to: string; type: MessageType } + +/** + * Imports one item of a link's queue, with everything it implies, in one transaction that also + * advances the link's import position; an item at or below it was already imported and does + * nothing. Throws on anything it cannot read, so the pull stops and the item is never acked. + */ +export function importRemoteOwnedItem( + db: OrchestrationDb, + server: RemoteServerPin, + item: PulledRemoteOwnedItem, + /** For a link a re-pair closed: the server's name, and how to wake the Run's coordinator. */ + onClose: { name: string; notify?: (handle: string, messageType: string) => void } = { + name: server.environment_id + } +): ImportedRemoteOwnedMail | undefined { + const parsed = parseRemoteOwnedItem(item) + return runLifecycleWriteTransaction(db.db, 'import_remote_owned_item', () => { + const link = getRemoteRunLink(db, item.conversationId) + if (!link || link.environment_id !== server.environment_id) { + throw unreadable(item, `it names no Run this Orca placed on ${server.environment_id}`) + } + if (item.sequence <= link.last_imported_sequence) { + return undefined + } + advanceImportPosition(db, link, item.sequence) + // A reset or re-pair since then: the item is read and acknowledged, and records nothing. + if (link.state === 'open' && !remoteRunLinkPinMatches(link, server)) { + closeRemoteRunLink( + db, + link.conversation_id, + `The pairing with ${onClose.name} was re-made.`, + onClose.notify + ) + } + if (link.state !== 'open' || !remoteRunLinkPinMatches(link, server)) { + return undefined + } + if (parsed.value.homeRunId !== link.run_id) { + throw unreadable(item, `it belongs to Run ${parsed.value.homeRunId}, not ${link.run_id}`) + } + if (link.peer_run_id !== null && parsed.value.peerRunId !== link.peer_run_id) { + throw unreadable( + item, + `it comes from peer Run ${parsed.value.peerRunId}, not ${link.peer_run_id}` + ) + } + noteRemoteRunLinkPeerRun(db, link.conversation_id, parsed.value.peerRunId) + return parsed.kind === 'worker_mail' + ? importWorkerMail(db, link, parsed.value) + : importWorkerState(db, link, parsed.value) + }) +} + +type ParsedItem = + | { kind: 'worker_mail'; value: RemoteOwnedWorkerMail } + | { kind: 'worker_state'; value: RemoteOwnedWorkerState } + +function parseRemoteOwnedItem(item: PulledRemoteOwnedItem): ParsedItem { + let json: unknown + try { + json = JSON.parse(item.payload) + } catch { + throw unreadable(item, 'its payload is not JSON') + } + const parsed = parseKind(item.kind, json) + if (!parsed) { + throw unreadable(item, `its kind ${item.kind ?? '(none)'} is not one this Orca reads`) + } + if (!parsed.success) { + throw unreadable(item, `its payload does not match ${item.kind}: ${parsed.error}`) + } + if (parsed.item.value.id !== item.messageId) { + throw unreadable(item, `its payload names ${parsed.item.value.id}`) + } + return parsed.item +} + +function parseKind( + kind: string | undefined, + json: unknown +): { success: true; item: ParsedItem } | { success: false; error: string } | undefined { + if (kind === 'worker_mail') { + const result = REMOTE_OWNED_ITEM_KINDS.worker_mail.safeParse(json) + return result.success + ? { success: true, item: { kind, value: result.data } } + : { success: false, error: result.error.issues[0]?.message ?? 'invalid' } + } + if (kind === 'worker_state') { + const result = REMOTE_OWNED_ITEM_KINDS.worker_state.safeParse(json) + return result.success + ? { success: true, item: { kind, value: result.data } } + : { success: false, error: result.error.issues[0]?.message ?? 'invalid' } + } + return undefined +} + +function unreadable(item: PulledRemoteOwnedItem, why: string): OrchestrationError { + return new OrchestrationError( + 'invalid_argument', + `Queue item ${item.messageId} (sequence ${item.sequence}) from a paired server was not imported: ${why}.` + ) +} + +function advanceImportPosition( + db: OrchestrationDb, + link: RemoteRunLinkRow, + sequence: number +): void { + db.db + .prepare(`UPDATE remote_run_links SET last_imported_sequence = ? WHERE conversation_id = ?`) + .run(sequence, link.conversation_id) +} + +function importWorkerMail( + db: OrchestrationDb, + link: RemoteRunLinkRow, + mail: RemoteOwnedWorkerMail +): ImportedRemoteOwnedMail | undefined { + if (mail.dispatchId && mail.taskId) { + adoptRemoteAttempt(db, link, { taskId: mail.taskId, dispatchId: mail.dispatchId }) + if (mail.message.type === 'worker_done') { + recordRemoteDispatchReport(db, mail.dispatchId, mail.message.subject) + } + if (mail.message.type === 'question') { + db.db + .prepare( + `INSERT OR IGNORE INTO remote_owned_questions ( + message_id, conversation_id, run_id, environment_id, dispatch_id + ) VALUES (?, ?, ?, ?, ?)` + ) + .run(mail.id, link.conversation_id, link.run_id, link.environment_id, mail.dispatchId) + } + } + if (db.getMessageById(mail.id)) { + return undefined + } + const to = `run:${link.run_id}` + const presented = presentImportedPeerItem({ + kind: 'worker_mail', + from: mail.message.from, + body: mail.message.body + }) + db.insertMessage({ + id: mail.id, + from: presented.from, + to, + subject: mail.message.subject, + body: presented.body, + type: mail.message.type, + priority: mail.message.priority, + threadId: mail.message.threadId ?? undefined, + payload: mail.message.payload ?? undefined, + runId: link.run_id + }) + return { to, type: mail.message.type } +} + +function importWorkerState( + db: OrchestrationDb, + link: RemoteRunLinkRow, + state: RemoteOwnedWorkerState +): undefined { + const { dispatch, task } = state + adoptRemoteAttempt(db, link, { + taskId: dispatch.taskId, + dispatchId: dispatch.id, + agent: dispatch.agent + }) + const record = recordRemoteDispatchState( + db, + dispatch.id, + state.removed + ? // The server deleted it without a stop, as any reset does; nothing there answers for it now. + { + status: 'failed', + worker_state: 'abandoned', + last_failure: state.removed.reason, + agent: dispatch.agent + } + : { + status: dispatch.status, + worker_state: dispatch.workerState, + last_failure: dispatch.lastFailure, + agent: dispatch.agent + } + ) + if (state.removed) { + // No stop there can prove anything about a Dispatch its reset deleted, so nothing is owed for it. + abandonRemoteDispatchStop(db, dispatch.id) + } + // The Task here follows the server's Task through the ordinary owner's Task half, unless this + // Orca already settled it for this attempt: the first result stands. + // The server's restart recovery lost its worker and readied its Task: as the local rule does, + // the Task here is ready for a fresh start. Ready is no result, so it applies even if settled here. + if ( + task.status === 'ready' && + !state.removed && + isRemoteDispatchTerminal(record) && + currentRemoteAttempt(db, dispatch.taskId)?.dispatch_id === dispatch.id + ) { + settleTaskAfterLostWorker(db, dispatch.taskId, 'ready') + return undefined + } + if (record.task_settled_here) { + return undefined + } + if (state.removed || task.status === 'failed') { + db.settleRemoteAttemptResult({ + taskId: dispatch.taskId, + dispatchId: dispatch.id, + outcome: 'failed', + result: state.removed?.reason ?? task.result ?? dispatch.lastFailure ?? '', + correctedUnobservedPrompt: !state.removed && state.correctedUnobservedPrompt + }) + } else if (task.status === 'completed') { + db.settleRemoteAttemptResult({ + taskId: dispatch.taskId, + dispatchId: dispatch.id, + outcome: 'succeeded', + result: task.result ?? '', + correctedUnobservedPrompt: state.correctedUnobservedPrompt + }) + } else if ( + task.status === 'blocked' && + currentRemoteAttempt(db, dispatch.taskId)?.dispatch_id === dispatch.id + ) { + reconcileTaskAfterDispatchInterruption(db, dispatch.taskId, dispatch.id) + } + return undefined +} diff --git a/src/main/runtime/orchestration/db/remote-owned/remote-owned-records.test.ts b/src/main/runtime/orchestration/db/remote-owned/remote-owned-records.test.ts new file mode 100644 index 00000000000..0e688d81a02 --- /dev/null +++ b/src/main/runtime/orchestration/db/remote-owned/remote-owned-records.test.ts @@ -0,0 +1,805 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { OrchestrationDb } from '../orchestration-db' +import { createRootDispatch } from '../root-dispatch-test-fixture' +import { claimTaskForStart } from '../tasks/task-start-claim' +import type { RunRow } from '../orchestration-records' +import type { OrchestrationWorkerServer } from '../../federation/environment-transport' +import { + getRemoteDispatch, + listRemoteDispatches, + oweRemoteDispatchStop +} from './remote-dispatch-records' +import { importRemoteOwnedItem, type PulledRemoteOwnedItem } from './remote-owned-import' +import { refuseTaskOfClosedPairing } from './remote-placement-hold' +import { + getRemotePlacement, + recordRemoteStart, + releaseRemotePlacement, + reserveRemotePlacement, + settleRemoteAttemptHere +} from './remote-placements' +import { + getRemoteRunLink, + openRemoteRunLink, + remoteServerPin, + type RemoteRunLinkRow +} from './remote-run-links' + +const SERVER: OrchestrationWorkerServer = { + environmentId: 'env_b', + name: 'devB', + peerFingerprint: 'host_b', + homePeerFingerprint: 'cred_a', + pairingRevision: 1 +} +const PIN = remoteServerPin(SERVER) +const PEER_RUN = 'run_on_b' + +describe('remote-owned records on the coordinating Orca', () => { + let db: OrchestrationDb + let run: RunRow + let link: RemoteRunLinkRow + let sequence: number + + beforeEach(() => { + db = new OrchestrationDb(':memory:') + run = db.createRun({ + objective: 'Ship', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: null + }) + link = openRemoteRunLink(db, run.id, SERVER) + sequence = 0 + }) + + afterEach(() => db.close()) + + function placeTask(taskId: string, requestKey = `key_${taskId}`, deps?: string[]) { + return reserveRemotePlacement(db, { + link, + taskId, + requestKey, + create: { spec: `do ${taskId}`, ...(deps ? { deps } : {}) } + }) + } + + function startedOnB(taskId: string, dispatchId: string) { + placeTask(taskId) + return recordRemoteStart(db, { + conversationId: link.conversation_id, + taskId, + dispatchId, + requestKey: `key_${taskId}`, + peerRunId: PEER_RUN + }) + } + + function item( + kind: string, + payload: Record, + at = ++sequence + ): PulledRemoteOwnedItem { + return { + conversationId: link.conversation_id, + sequence: at, + messageId: String(payload.id), + kind, + payload: JSON.stringify(payload) + } + } + + function stateItem( + dispatchId: string, + taskId: string, + change: { + status?: string + workerState?: string | null + taskStatus?: string + result?: string | null + corrected?: boolean + removed?: string + }, + at?: number + ) { + const seq = at ?? ++sequence + return item( + 'worker_state', + { + v: 1, + id: `state_${seq}`, + homeRunId: run.id, + peerRunId: PEER_RUN, + dispatch: { + id: dispatchId, + taskId, + status: change.status ?? 'dispatched', + workerState: change.workerState === undefined ? 'ready' : change.workerState, + lastFailure: null, + agent: 'claude' + }, + task: { status: change.taskStatus ?? 'dispatched', result: change.result ?? null }, + correctedUnobservedPrompt: change.corrected ?? false, + removed: change.removed ? { reason: change.removed } : null + }, + seq + ) + } + + function mailItem( + id: string, + type: string, + provenance: { dispatchId: string; taskId: string } | null + ) { + return item('worker_mail', { + v: 1, + id, + homeRunId: run.id, + peerRunId: PEER_RUN, + message: { + from: 'dispatch:ctx_b1', + type, + subject: `${type} subject`, + body: 'body', + payload: null, + priority: 'normal', + threadId: null + }, + dispatchId: provenance?.dispatchId ?? null, + taskId: provenance?.taskId ?? null + }) + } + + const importItem = (pulled: PulledRemoteOwnedItem) => importRemoteOwnedItem(db, PIN, pulled) + + describe('a database an unreleased build made', () => { + it('repairs the placement and record tables on open, so starts and settlements work', () => { + db.db.exec(` + DROP TABLE remote_placements; + CREATE TABLE remote_placements ( + task_id TEXT PRIMARY KEY, run_id TEXT NOT NULL, environment_id TEXT NOT NULL, + conversation_id TEXT NOT NULL, state TEXT NOT NULL, request_key TEXT NOT NULL, + prior_task_status TEXT NOT NULL, dispatch_id TEXT, reserved_by_runtime TEXT NOT NULL, + outcome_unknown INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + ALTER TABLE remote_dispatches DROP COLUMN task_settled_here; + `) + db.createTables() + + startedOnB('task_t', 'ctx_b1') + settleRemoteAttemptHere(db, 'ctx_b1', 'stopped') + expect(getRemoteDispatch(db, 'ctx_b1')).toMatchObject({ task_settled_here: 1 }) + }) + }) + + describe('a retry here of an attempt on the server, by the local rule', () => { + const retryHere = () => claimTaskForStart(db, db.getTask('task_t')!, { retryOf: 'ctx_b1' }) + + it('refuses while a stop is unproven, and follows an abandon here or a proven stop', () => { + startedOnB('task_t', 'ctx_b1') + importItem(stateItem('ctx_b1', 'task_t', { status: 'dispatched', workerState: 'ready' })) + settleRemoteAttemptHere(db, 'ctx_b1', 'stopped') + expect(db.getTask('task_t')?.status).toBe('blocked') + // As a local stop_unknown worker: its outcome is unknown, so nothing may follow it yet. + expect(retryHere).toThrow('Task task_t cannot retry from Dispatch ctx_b1.') + + settleRemoteAttemptHere(db, 'ctx_b1', 'abandoned') + expect(retryHere).not.toThrow() + }) + + it('follows a stop the server proved', () => { + startedOnB('task_t', 'ctx_b1') + importItem(stateItem('ctx_b1', 'task_t', { status: 'dispatched', workerState: 'ready' })) + settleRemoteAttemptHere(db, 'ctx_b1', 'stopped') + importItem( + stateItem('ctx_b1', 'task_t', { + status: 'failed', + workerState: 'stopped', + taskStatus: 'blocked' + }) + ) + expect(retryHere).not.toThrow() + }) + }) + + describe('#5 placement fence', () => { + it('refuses a local start of a Task being placed on a server, with the ordinary text', () => { + placeTask('task_t') + expect(db.getTask('task_t')?.status).toBe('dispatched') + expect(() => + db.createStartingWorkerDispatch({ + taskId: 'task_t', + startOptions: {}, + creator: { kind: 'system' }, + maxDepth: Number.MAX_SAFE_INTEGER + }) + ).toThrow('Task task_t is dispatched; only a ready Task can start.') + }) + + it('refuses --task naming another Run', () => { + const other = db.createRun({ + objective: 'Other', + coordinatorHandle: null, + coordinatorPaneKey: null + }) + const foreign = db.createTask({ spec: 'theirs', runId: other.id }) + expect(() => + reserveRemotePlacement(db, { + link, + taskId: foreign.id, + requestKey: 'k' + }) + ).toThrow(`Task ${foreign.id} was not found in Run ${run.id}.`) + expect(getRemotePlacement(db, foreign.id)).toBeUndefined() + }) + + it('frees the Task only when the server applied nothing, and a same-key retry finds its reservation', () => { + placeTask('task_t') + expect(placeTask('task_t').placement.state).toBe('reserved') + releaseRemotePlacement(db, 'task_t', 'key_task_t') + expect(getRemotePlacement(db, 'task_t')).toBeUndefined() + expect(db.getTask('task_t')?.status).toBe('ready') + }) + + it('refuses a start whose deps are unfinished with the ordinary not-ready text', () => { + const dep = db.createTask({ spec: 'first', runId: run.id }) + expect(() => placeTask('task_t', 'k', [dep.id])).toThrow( + 'Task task_t is pending; only a ready Task can start.' + ) + expect(db.getTask('task_t')).toBeUndefined() + }) + }) + + describe('a known older attempt never answers a new reservation', () => { + it('keeps a fresh start fenced and releasable when an item for the earlier attempt arrives', () => { + startedOnB('task_t', 'ctx_d0') + importItem( + stateItem('ctx_d0', 'task_t', { + status: 'failed', + workerState: 'failed', + taskStatus: 'failed', + result: 'd0' + }) + ) + db.updateTaskStatus('task_t', 'ready') + placeTask('task_t', 'fresh') + importItem( + stateItem('ctx_d0', 'task_t', { + status: 'failed', + workerState: 'abandoned', + taskStatus: 'failed', + result: 'd0' + }) + ) + expect(getRemotePlacement(db, 'task_t')).toMatchObject({ + state: 'reserved', + request_key: 'fresh' + }) + expect(db.getTask('task_t')?.status).toBe('dispatched') + expect( + recordRemoteStart(db, { + conversationId: link.conversation_id, + taskId: 'task_t', + dispatchId: 'ctx_d0', + requestKey: 'fresh' + })?.dispatch_id + ).toBe('ctx_d0') + expect(getRemotePlacement(db, 'task_t')?.state).toBe('reserved') + releaseRemotePlacement(db, 'task_t', 'fresh') + expect(db.getTask('task_t')?.status).toBe('ready') + }) + }) + + describe('a re-made pairing', () => { + it('releases what the old link held, so the Task can be changed here again', () => { + startedOnB('task_t', 'ctx_b1') + openRemoteRunLink(db, run.id, { + ...SERVER, + homePeerFingerprint: 'cred_a_new', + pairingRevision: 2 + }) + expect(db.updateTaskStatus('task_t', 'failed', 'pairing re-made')?.status).toBe('failed') + }) + }) + + describe('#3 late facts after a reset', () => { + for (const reset of ['resetAll', 'resetTasks'] as const) { + it(`records nothing from a start answer that lands after ${reset}`, () => { + placeTask('task_t') + db[reset]() + expect(getRemoteRunLink(db, link.conversation_id)?.state).toBe('cancel_owed') + expect( + recordRemoteStart(db, { + conversationId: link.conversation_id, + taskId: 'task_t', + dispatchId: 'ctx_late', + requestKey: 'key_task_t' + }) + ).toBeUndefined() + releaseRemotePlacement(db, 'task_t', 'key_task_t') + expect( + importItem( + stateItem('ctx_late', 'task_t', { + taskStatus: 'completed', + status: 'completed', + workerState: 'succeeded' + }) + ) + ).toBeUndefined() + expect(getRemoteDispatch(db, 'ctx_late')).toBeUndefined() + expect(listRemoteDispatches(db, { runId: run.id, limit: 10 })).toEqual([]) + expect(getRemotePlacement(db, 'task_t')).toBeUndefined() + }) + } + + it('records nothing from a start answer that lands after the pairing was re-made', () => { + placeTask('task_t') + openRemoteRunLink(db, run.id, { + ...SERVER, + homePeerFingerprint: 'cred_a_new', + pairingRevision: 2 + }) + expect(getRemoteRunLink(db, link.conversation_id)?.state).toBe('closed') + expect( + recordRemoteStart(db, { + conversationId: link.conversation_id, + taskId: 'task_t', + dispatchId: 'ctx_late', + requestKey: 'key_task_t' + }) + ).toBeUndefined() + expect(getRemoteDispatch(db, 'ctx_late')).toBeUndefined() + }) + + it('opens a new link for the Run after a reset, so a later start gets its own cancel', () => { + db.resetTasks() + const next = openRemoteRunLink(db, run.id, SERVER) + expect(next.conversation_id).not.toBe(link.conversation_id) + expect(getRemoteRunLink(db, link.conversation_id)?.state).toBe('cancel_owed') + }) + }) + + describe('#4 import position', () => { + it('ignores a redelivered page after a crash before the ack, and a page interrupted midway', () => { + startedOnB('task_t', 'ctx_b1') + const first = stateItem('ctx_b1', 'task_t', { workerState: 'ready' }) + const second = mailItem('msg_report', 'worker_done', { + dispatchId: 'ctx_b1', + taskId: 'task_t' + }) + const third = stateItem('ctx_b1', 'task_t', { + status: 'completed', + workerState: 'succeeded', + taskStatus: 'completed', + result: 'done' + }) + importItem(first) + importItem(second) + // Crash before the ack: the server redelivers the page from the start. + for (const pulled of [first, second]) { + expect(importItem(pulled)).toBeUndefined() + } + importItem(third) + expect(db.getTask('task_t')).toMatchObject({ status: 'completed', result: 'done' }) + // An older state redelivered after the newer one changes nothing. + expect(importItem(first)).toBeUndefined() + expect(getRemoteDispatch(db, 'ctx_b1')).toMatchObject({ + worker_state: 'succeeded', + last_report: 'worker_done subject' + }) + expect( + db.getUnreadMessages(`run:${run.id}`).filter((m) => m.id === 'msg_report') + ).toHaveLength(1) + expect(getRemoteRunLink(db, link.conversation_id)?.last_imported_sequence).toBe(3) + }) + + it('fails each Task when the server reset removed its Dispatch', () => { + startedOnB('task_t', 'ctx_b1') + oweRemoteDispatchStop(db, 'ctx_b1', 'intent_1') + importItem(stateItem('ctx_b1', 'task_t', { removed: 'Reset on devB.' })) + expect(db.getTask('task_t')).toMatchObject({ status: 'failed', result: 'Reset on devB.' }) + expect(getRemoteDispatch(db, 'ctx_b1')?.stop_owed).toBe(0) + }) + }) + + describe('#8 settlement through the Task half', () => { + it('completes the Task from the first success and readies its dependents, writing no local execution rows', () => { + startedOnB('task_t', 'ctx_b1') + const dependent = db.createTask({ spec: 'next', runId: run.id, deps: ['task_t'] }) + importItem( + stateItem('ctx_b1', 'task_t', { + status: 'completed', + workerState: 'succeeded', + taskStatus: 'completed', + result: 'shipped' + }) + ) + expect(db.getTask('task_t')).toMatchObject({ status: 'completed', result: 'shipped' }) + expect(db.getTask(dependent.id)?.status).toBe('ready') + expect(db.db.prepare('SELECT COUNT(*) AS n FROM dispatch_contexts').get()).toEqual({ n: 0 }) + expect(db.db.prepare('SELECT COUNT(*) AS n FROM worker_dispatches').get()).toEqual({ n: 0 }) + }) + + it('lets the first result stand: a later failure and a duplicate success are no-ops', () => { + startedOnB('task_t', 'ctx_b1') + importItem( + stateItem('ctx_b1', 'task_t', { + status: 'completed', + workerState: 'succeeded', + taskStatus: 'completed', + result: 'first' + }) + ) + importItem( + stateItem('ctx_b1', 'task_t', { + status: 'completed', + workerState: 'succeeded', + taskStatus: 'completed', + result: 'again' + }) + ) + importItem( + stateItem('ctx_b1', 'task_t', { + status: 'failed', + workerState: 'failed', + taskStatus: 'failed', + result: 'late' + }) + ) + expect(db.getTask('task_t')).toMatchObject({ status: 'completed', result: 'first' }) + }) + + it('keeps a late D1 failure from failing a Task reopened under D2', () => { + startedOnB('task_t', 'ctx_d1') + importItem( + stateItem('ctx_d1', 'task_t', { + status: 'failed', + workerState: 'stopped', + taskStatus: 'blocked' + }) + ) + expect(db.getTask('task_t')?.status).toBe('blocked') + reserveRemotePlacement(db, { + link, + taskId: 'task_t', + requestKey: 'retry', + retryOf: 'ctx_d1' + }) + recordRemoteStart(db, { + conversationId: link.conversation_id, + taskId: 'task_t', + dispatchId: 'ctx_d2', + requestKey: 'retry' + }) + expect(db.getTask('task_t')?.status).toBe('dispatched') + importItem( + stateItem('ctx_d1', 'task_t', { + status: 'failed', + workerState: 'stopped', + taskStatus: 'failed', + result: 'late D1' + }) + ) + expect(db.getTask('task_t')?.status).toBe('dispatched') + importItem( + stateItem('ctx_d2', 'task_t', { + status: 'completed', + workerState: 'succeeded', + taskStatus: 'completed', + result: 'D2' + }) + ) + expect(db.getTask('task_t')).toMatchObject({ status: 'completed', result: 'D2' }) + }) + + it("applies the server's unobserved-prompt correction after a failed state item", () => { + startedOnB('task_t', 'ctx_b1') + importItem( + stateItem('ctx_b1', 'task_t', { + status: 'failed', + workerState: 'failed', + taskStatus: 'failed', + result: 'stalled' + }) + ) + expect(db.getTask('task_t')?.status).toBe('failed') + // Without B's decision, a later success is a second result and does not stand. + importItem( + stateItem('ctx_b1', 'task_t', { + status: 'completed', + workerState: 'succeeded', + taskStatus: 'completed', + result: 'uncorrected' + }) + ) + expect(db.getTask('task_t')?.status).toBe('failed') + importItem( + stateItem('ctx_b1', 'task_t', { + status: 'completed', + workerState: 'succeeded', + taskStatus: 'completed', + result: 'it worked', + corrected: true + }) + ) + expect(db.getTask('task_t')).toMatchObject({ status: 'completed', result: 'it worked' }) + }) + + it('ignores a late remote result once the Task was started here', () => { + startedOnB('task_t', 'ctx_d1') + importItem( + stateItem('ctx_d1', 'task_t', { + status: 'failed', + workerState: 'stopped', + taskStatus: 'blocked' + }) + ) + db.updateTaskStatus('task_t', 'ready') + const local = createRootDispatch(db, 'task_t', 'term_local') + importItem( + stateItem('ctx_d1', 'task_t', { + status: 'failed', + workerState: 'stopped', + taskStatus: 'failed', + result: 'late D1' + }) + ) + expect(db.getTask('task_t')?.status).toBe('dispatched') + expect(db.getDispatchContextById(local.id)?.status).toBe('dispatched') + }) + + it('counts a remote attempt as the Task’s active worker for local Task updates', () => { + startedOnB('task_t', 'ctx_b1') + expect(() => db.updateTaskStatus('task_t', 'completed', 'by hand')).toThrow( + 'Task task_t cannot move to completed while supervised Dispatch ctx_b1 is active' + ) + }) + }) + + describe('a local claim takes the Task back', () => { + it('keeps a late correction of an older remote attempt off a Task a local manual Dispatch settled', () => { + startedOnB('task_t', 'ctx_d1') + importItem( + stateItem('ctx_d1', 'task_t', { + status: 'failed', + workerState: 'failed', + taskStatus: 'failed', + result: 'stalled' + }) + ) + db.updateTaskStatus('task_t', 'ready') + const local = createRootDispatch(db, 'task_t', 'term_local') + expect(getRemotePlacement(db, 'task_t')).toBeUndefined() + db.updateTaskStatus('task_t', 'failed', 'local D2 failure') + expect(db.getDispatchContextById(local.id)?.status).toBe('failed') + importItem( + stateItem('ctx_d1', 'task_t', { + status: 'completed', + workerState: 'succeeded', + taskStatus: 'completed', + result: 'old D1 correction', + corrected: true + }) + ) + expect(db.getTask('task_t')).toMatchObject({ status: 'failed', result: 'local D2 failure' }) + }) + + it('lets a local start through once the pairing behind a reservation was re-made', () => { + placeTask('task_t') + openRemoteRunLink(db, run.id, { + ...SERVER, + homePeerFingerprint: 'cred_a_new', + pairingRevision: 2 + }) + db.updateTaskStatus('task_t', 'ready') + const started = db.createStartingWorkerDispatch({ + taskId: 'task_t', + startOptions: {}, + creator: { kind: 'system' }, + maxDepth: Number.MAX_SAFE_INTEGER + }) + expect(started.task.status).toBe('dispatched') + expect(getRemotePlacement(db, 'task_t')).toBeUndefined() + }) + }) + + describe('Task guards', () => { + it('refuses a decision gate on a Task a remote worker still holds', () => { + startedOnB('task_t', 'ctx_b1') + expect(() => db.createGate({ taskId: 'task_t', question: 'Ship?' })).toThrow( + 'Task task_t cannot open a gate while supervised Dispatch ctx_b1 is active' + ) + }) + + it('keeps holding a Task whose worker finished until its result comes home', () => { + startedOnB('task_t', 'ctx_b1') + importItem( + stateItem('ctx_b1', 'task_t', { + status: 'dispatched', + workerState: 'succeeded', + taskStatus: 'dispatched' + }) + ) + expect(() => db.updateTaskStatus('task_t', 'completed', 'by hand')).toThrow( + 'ctx_b1 is active' + ) + importItem( + stateItem('ctx_b1', 'task_t', { + status: 'circuit_broken', + workerState: null, + taskStatus: 'dispatched' + }) + ) + expect(() => db.updateTaskStatus('task_t', 'failed', 'by hand')).toThrow('ctx_b1 is active') + importItem( + stateItem('ctx_b1', 'task_t', { + status: 'failed', + workerState: null, + taskStatus: 'failed', + result: 'from the server' + }) + ) + expect(db.getTask('task_t')).toMatchObject({ status: 'failed', result: 'from the server' }) + }) + + it('refuses a local retry of an older local attempt once a server attempt is the latest', () => { + const task = db.createTask({ spec: 'work', runId: run.id }) + const d1 = db.createStartingWorkerDispatch({ + taskId: task.id, + startOptions: {}, + creator: { kind: 'system' }, + maxDepth: Number.MAX_SAFE_INTEGER + }) + db.failWorkerStart(d1.dispatch.id, 'agent_readiness', 'local failed') + db.updateTaskStatus(task.id, 'ready') + reserveRemotePlacement(db, { + link, + taskId: task.id, + requestKey: 'remote' + }) + recordRemoteStart(db, { + conversationId: link.conversation_id, + taskId: task.id, + dispatchId: 'ctx_d2', + requestKey: 'remote' + }) + importItem( + stateItem('ctx_d2', task.id, { + status: 'failed', + workerState: 'failed', + taskStatus: 'failed', + result: 'remote failed' + }) + ) + expect(db.getTask(task.id)?.status).toBe('failed') + expect(() => + db.createStartingWorkerDispatch({ + taskId: task.id, + retryOf: d1.dispatch.id, + startOptions: {}, + creator: { kind: 'system' }, + maxDepth: Number.MAX_SAFE_INTEGER + }) + ).toThrow(`Task ${task.id} cannot retry from Dispatch ${d1.dispatch.id}.`) + }) + + it('refuses to place a Task again on a server whose pairing was re-made since it was placed', () => { + placeTask('task_t', 'k') + openRemoteRunLink(db, run.id, { + ...SERVER, + homePeerFingerprint: 'cred_a_new', + pairingRevision: 2 + }) + db.updateTaskStatus('task_t', 'ready') + expect(() => refuseTaskOfClosedPairing(db, 'task_t', { ...SERVER, name: 'devB' })).toThrow( + 'Task task_t was placed through a pairing with devB that was re-made or removed; create a new task to run it there.' + ) + expect(db.getTask('task_t')?.status).toBe('ready') + }) + + it("takes the server's corrected failure text", () => { + startedOnB('task_t', 'ctx_b1') + importItem( + stateItem('ctx_b1', 'task_t', { + status: 'failed', + workerState: 'failed', + taskStatus: 'failed', + result: 'stalled' + }) + ) + importItem( + stateItem('ctx_b1', 'task_t', { + status: 'failed', + workerState: 'failed', + taskStatus: 'failed', + result: 'real failure', + corrected: true + }) + ) + expect(db.getTask('task_t')).toMatchObject({ status: 'failed', result: 'real failure' }) + }) + }) + + describe('S3 / S8 queue items', () => { + it('lets a late start answer seed identity only, never state', () => { + placeTask('task_t') + importItem( + stateItem('ctx_b1', 'task_t', { + status: 'completed', + workerState: 'succeeded', + taskStatus: 'completed', + result: 'r' + }) + ) + recordRemoteStart(db, { + conversationId: link.conversation_id, + taskId: 'task_t', + dispatchId: 'ctx_b1', + requestKey: 'key_task_t', + agent: 'codex' + }) + expect(getRemoteDispatch(db, 'ctx_b1')).toMatchObject({ + status: 'completed', + worker_state: 'succeeded' + }) + expect(db.getTask('task_t')?.status).toBe('completed') + }) + + it('creates the record of a Dispatch it never heard of from the item, and adopts it as the placement’s attempt', () => { + placeTask('task_t') + importItem(stateItem('ctx_unseen', 'task_t', { status: 'pending', workerState: 'starting' })) + expect(getRemoteDispatch(db, 'ctx_unseen')).toMatchObject({ + task_id: 'task_t', + run_id: run.id, + worker_state: 'starting' + }) + expect(getRemotePlacement(db, 'task_t')).toMatchObject({ + state: 'accepted', + dispatch_id: 'ctx_unseen' + }) + }) + + it('refuses an item whose message ID, Run, peer Run or kind does not match, leaving the position', () => { + startedOnB('task_t', 'ctx_b1') + const good = stateItem('ctx_b1', 'task_t', {}) + expect(() => importItem({ ...good, messageId: 'other' })).toThrow('was not imported') + const wrongPeer = JSON.parse(good.payload) + expect(() => + importItem({ + ...good, + payload: JSON.stringify({ ...wrongPeer, peerRunId: 'run_elsewhere' }) + }) + ).toThrow('peer Run') + expect(() => + importItem({ ...good, payload: JSON.stringify({ ...wrongPeer, homeRunId: 'run_other' }) }) + ).toThrow('belongs to Run') + expect(() => importItem({ ...good, kind: 'worker_future' })).toThrow('kind worker_future') + expect(() => importItem({ ...good, payload: '{"v":2}' })).toThrow('does not match') + expect(getRemoteRunLink(db, link.conversation_id)?.last_imported_sequence).toBe(0) + importItem(good) + expect(getRemoteRunLink(db, link.conversation_id)?.last_imported_sequence).toBe(good.sequence) + }) + + it('records the question a remote worker asked, and files its mail in the Run mailbox', () => { + startedOnB('task_t', 'ctx_b1') + expect( + importItem(mailItem('msg_q', 'question', { dispatchId: 'ctx_b1', taskId: 'task_t' })) + ).toEqual({ to: `run:${run.id}`, type: 'question' }) + expect( + db.db + .prepare( + 'SELECT dispatch_id, environment_id FROM remote_owned_questions WHERE message_id = ?' + ) + .get('msg_q') + ).toEqual({ dispatch_id: 'ctx_b1', environment_id: 'env_b' }) + expect(db.getUnreadMessages(`run:${run.id}`)).toEqual([ + expect.objectContaining({ + id: 'msg_q', + type: 'question', + from_handle: 'dispatch:ctx_b1', + body: 'body' + }) + ]) + }) + }) +}) diff --git a/src/main/runtime/orchestration/db/remote-owned/remote-owned-schema-sql.ts b/src/main/runtime/orchestration/db/remote-owned/remote-owned-schema-sql.ts new file mode 100644 index 00000000000..4910528812e --- /dev/null +++ b/src/main/runtime/orchestration/db/remote-owned/remote-owned-schema-sql.ts @@ -0,0 +1,95 @@ +// What this Orca placed on paired servers that own the workers. New tables only, so an older build +// opens the file and ignores them. Facts in them change only from the server's queue, in its order. +export const REMOTE_OWNED_SCHEMA_SQL = ` +-- One per (Run, server) while open; an A reset turns it into a cancel owed and the Run's next start +-- there opens a new one, under a new conversation and so a new peer Run on the server. +CREATE TABLE IF NOT EXISTS remote_run_links ( + conversation_id TEXT PRIMARY KEY, + run_id TEXT NOT NULL, + environment_id TEXT NOT NULL, + peer_fingerprint TEXT NOT NULL, + home_fingerprint TEXT NOT NULL, + pairing_revision INTEGER, + peer_run_id TEXT, + -- The server's name when the link was made, for a server removed from this Orca since. + server_name TEXT, + state TEXT NOT NULL DEFAULT 'open' + CHECK(state IN ('open', 'cancel_owed', 'closed')), + cancel_key TEXT, + cancel_attempt INTEGER NOT NULL DEFAULT 0, + cancel_retries INTEGER NOT NULL DEFAULT 0, + cancel_retry_at INTEGER, + last_imported_sequence INTEGER NOT NULL DEFAULT 0, + last_error TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE UNIQUE INDEX IF NOT EXISTS idx_remote_run_links_open + ON remote_run_links(run_id, environment_id) WHERE state = 'open'; +CREATE INDEX IF NOT EXISTS idx_remote_run_links_environment + ON remote_run_links(environment_id, state); + +-- A Task being started on, or started on, a server. 'reserved' fences it from every other start +-- until the server answers; the answer's Dispatch is the Task's current attempt there. +CREATE TABLE IF NOT EXISTS remote_placements ( + task_id TEXT PRIMARY KEY, + run_id TEXT NOT NULL, + environment_id TEXT NOT NULL, + conversation_id TEXT NOT NULL, + state TEXT NOT NULL CHECK(state IN ('reserved', 'accepted')), + request_key TEXT NOT NULL, + prior_task_status TEXT NOT NULL, + dispatch_id TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +-- What the server last said about one of its Dispatches here, and any stop this Orca owes it. +CREATE TABLE IF NOT EXISTS remote_dispatches ( + dispatch_id TEXT PRIMARY KEY, + conversation_id TEXT NOT NULL, + run_id TEXT NOT NULL, + environment_id TEXT NOT NULL, + task_id TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', + worker_state TEXT, + last_failure TEXT, + agent TEXT, + last_report TEXT, + stop_owed INTEGER NOT NULL DEFAULT 0, + stop_count INTEGER NOT NULL DEFAULT 0, + stop_attempt INTEGER NOT NULL DEFAULT 0, + stop_retries INTEGER NOT NULL DEFAULT 0, + stop_retry_at INTEGER, + stop_last_error TEXT, + -- This Orca already ran the Task half for the attempt: 1 for a stop the server did not answer, + -- 2 once it was abandoned here. The first result stands: later states from the server change + -- only this record. Abandoned here, the attempt is settled for a retry, as a local abandon is. + task_settled_here INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + -- When this Orca recorded the server's start answer or, after that, its latest state for the + -- Dispatch. Reports and this Orca's own stop bookkeeping leave it. + updated_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_remote_dispatches_run ON remote_dispatches(run_id); +CREATE INDEX IF NOT EXISTS idx_remote_dispatches_task ON remote_dispatches(task_id); +CREATE INDEX IF NOT EXISTS idx_remote_dispatches_stop_owed + ON remote_dispatches(environment_id) WHERE stop_owed = 1; + +-- Each distinct stop intent from this Orca and the count it was given, so a retry of an older +-- intent finds its own count instead of minting another. +CREATE TABLE IF NOT EXISTS remote_stop_intents ( + dispatch_id TEXT NOT NULL, + intent_key TEXT NOT NULL, + stop_count INTEGER NOT NULL, + PRIMARY KEY (dispatch_id, intent_key) +); + +-- A question a remote worker asked here; its reply goes to the server that owns the question. +CREATE TABLE IF NOT EXISTS remote_owned_questions ( + message_id TEXT PRIMARY KEY, + conversation_id TEXT NOT NULL, + run_id TEXT NOT NULL, + environment_id TEXT NOT NULL, + dispatch_id TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_remote_owned_questions_run ON remote_owned_questions(run_id); +` diff --git a/src/main/runtime/orchestration/db/remote-owned/remote-placement-hold.ts b/src/main/runtime/orchestration/db/remote-owned/remote-placement-hold.ts new file mode 100644 index 00000000000..4d3080f95c0 --- /dev/null +++ b/src/main/runtime/orchestration/db/remote-owned/remote-placement-hold.ts @@ -0,0 +1,64 @@ +import { OrchestrationError } from '../../orchestration-error' +import type { TaskStatus } from '../orchestration-records' +import type { OrchestrationDb } from '../orchestration-db' + +export type RemotePlacementRow = { + task_id: string + run_id: string + environment_id: string + conversation_id: string + state: 'reserved' | 'accepted' + request_key: string + prior_task_status: TaskStatus + dispatch_id: string | null + created_at: string +} + +/** + * The Task's placement on a server, while its link is open. Under a closed link (a re-made + * pairing) the server can never answer for it, so it holds nothing: not the Task, not its starts. + */ +export function getLiveRemotePlacement( + db: OrchestrationDb, + taskId: string +): RemotePlacementRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT placement.* over this table returns exactly its row shape. + return db.db + .prepare( + `SELECT placement.* FROM remote_placements placement + JOIN remote_run_links link + ON link.conversation_id = placement.conversation_id AND link.state = 'open' + WHERE placement.task_id = ?` + ) + .get(taskId) as RemotePlacementRow | undefined +} + +/** A start claimed the Task here: no attempt on a server speaks for it any more. */ +export function retireRemotePlacement(db: OrchestrationDb, taskId: string): void { + db.db.prepare('DELETE FROM remote_placements WHERE task_id = ?').run(taskId) +} + +/** + * A Task placed on this server through a link its re-made or removed pairing closed is still held + * there under that link's Run, which this pairing cannot reach; the Task is not reused there. + */ +export function refuseTaskOfClosedPairing( + db: OrchestrationDb, + taskId: string, + server: { peerFingerprint: string; name: string } +): void { + const earlier = db.db + .prepare( + `SELECT 1 FROM remote_placements placement + JOIN remote_run_links earlier ON earlier.conversation_id = placement.conversation_id + WHERE placement.task_id = ? AND earlier.state = 'closed' AND earlier.peer_fingerprint = ?` + ) + .get(taskId, server.peerFingerprint) + if (earlier) { + throw new OrchestrationError( + 'task_not_startable', + `Task ${taskId} was placed through a pairing with ${server.name} that was re-made or removed; create a new task to run it there. No effects were applied.`, + { taskId, effectsApplied: false } + ) + } +} diff --git a/src/main/runtime/orchestration/db/remote-owned/remote-placements.ts b/src/main/runtime/orchestration/db/remote-owned/remote-placements.ts new file mode 100644 index 00000000000..ed1e9c50d6e --- /dev/null +++ b/src/main/runtime/orchestration/db/remote-owned/remote-placements.ts @@ -0,0 +1,342 @@ +import type { TaskRow } from '../orchestration-records' +import type { OrchestrationDb } from '../orchestration-db' +import { OrchestrationError } from '../../orchestration-error' +import { taskNotFoundError } from '../../coordinator/dispatch/task-dispatch-refusal' +import { + beginLifecycleWriteTransaction, + commitLifecycleWriteTransaction, + rollbackLifecycleWriteTransaction, + transitionLifecycleWithDb +} from '../lifecycle-transition' +import { + getActiveDispatchForTask, + reconcileTaskAfterDispatchInterruption +} from '../dispatch-context/task-dispatch-reconciliation' +import { runLifecycleWriteTransaction } from '../lifecycle-write-transaction-runner' +import { claimTaskForStart } from '../tasks/task-start-claim' +import { + ABANDONED_HERE, + ensureRemoteDispatchRecord, + getRemoteDispatch, + isRemoteDispatchActive, + isRemoteDispatchTerminal, + type RemoteDispatchRow +} from './remote-dispatch-records' +import { getOpenRemoteRunLink, type RemoteRunLinkRow } from './remote-run-links' +import { getLiveRemotePlacement, type RemotePlacementRow } from './remote-placement-hold' +import { writtenRow } from './written-row' + +export type { RemotePlacementRow } + +export function getRemotePlacement( + db: OrchestrationDb, + taskId: string +): RemotePlacementRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table returns exactly its row shape. + return db.db.prepare('SELECT * FROM remote_placements WHERE task_id = ?').get(taskId) as + | RemotePlacementRow + | undefined +} + +type TaskCreation = Omit[0], 'id' | 'runId'> + +/** + * Claims the Task for a start on the link's server before the start is sent: the Task is + * dispatched here and fenced from every other start until the server answers. A same-key retry + * finds its own reservation. Creates the Task (under its adopted ID) when `create` is given. + */ +export function reserveRemotePlacement( + db: OrchestrationDb, + params: { + link: RemoteRunLinkRow + taskId: string + requestKey: string + create?: TaskCreation + retryOf?: string + } +): { placement: RemotePlacementRow; task: TaskRow } { + const transaction = beginLifecycleWriteTransaction(db.db, 'reserve_remote_placement') + try { + const link = getOpenRemoteRunLink(db, params.link.conversation_id) + if (!link) { + throw new OrchestrationError( + 'run_not_found', + `Run ${params.link.run_id} was reset while this start was waiting. No effects were applied.`, + { effectsApplied: false } + ) + } + const existing = getRemotePlacement(db, params.taskId) + // Only this link's own reservation answers a retry; one under a link a re-pair closed holds nothing. + if ( + existing?.request_key === params.requestKey && + existing.conversation_id === link.conversation_id + ) { + commitLifecycleWriteTransaction(db.db, transaction) + return { + placement: existing, + task: writtenRow(db.getTask(params.taskId), `Task ${params.taskId}`) + } + } + const task = + db.getTask(params.taskId) ?? + (params.create + ? db.createTask({ ...params.create, id: params.taskId, runId: link.run_id }) + : undefined) + if (!task || task.run_id !== link.run_id) { + throw taskNotFoundError(`Task ${params.taskId} was not found in Run ${link.run_id}.`, { + taskId: params.taskId, + runId: link.run_id + }) + } + claimTaskForStart(db, task, { retryOf: params.retryOf, onServer: link.environment_id }) + db.db + .prepare( + `INSERT INTO remote_placements ( + task_id, run_id, environment_id, conversation_id, state, request_key, prior_task_status, + dispatch_id + ) VALUES (?, ?, ?, ?, 'reserved', ?, ?, ?) + ON CONFLICT(task_id) DO UPDATE SET + run_id = excluded.run_id, environment_id = excluded.environment_id, + conversation_id = excluded.conversation_id, state = 'reserved', + request_key = excluded.request_key, prior_task_status = excluded.prior_task_status, + dispatch_id = excluded.dispatch_id` + ) + .run( + task.id, + link.run_id, + link.environment_id, + link.conversation_id, + params.requestKey, + task.status, + params.retryOf ?? null + ) + transitionLifecycleWithDb(db.db, { + entity: 'task', + id: task.id, + from: task.status, + to: 'dispatched', + projection: { result: null, completed_at: null } + }) + commitLifecycleWriteTransaction(db.db, transaction) + return { + placement: writtenRow(getRemotePlacement(db, task.id), `Placement of ${task.id}`), + task: writtenRow(db.getTask(task.id), `Task ${task.id}`) + } + } catch (error) { + rollbackLifecycleWriteTransaction(db.db, transaction) + throw error + } +} + +/** + * The server said the start applied nothing, so the Task goes back to where it was and is free to + * start again. A Task the start itself created ends failed, as a local start that fails after + * creating its Task leaves it: others may already depend on it. + */ +export function releaseRemotePlacement( + db: OrchestrationDb, + taskId: string, + requestKey: string, + { createdByStart = false }: { createdByStart?: boolean } = {} +): void { + const transaction = beginLifecycleWriteTransaction(db.db, 'release_remote_placement') + try { + const placement = getRemotePlacement(db, taskId) + if (placement?.state === 'reserved' && placement.request_key === requestKey) { + // A refused retry leaves the attempt it retried as the Task's current one. + if (placement.dispatch_id) { + db.db + .prepare(`UPDATE remote_placements SET state = 'accepted' WHERE task_id = ?`) + .run(taskId) + } else { + db.db.prepare('DELETE FROM remote_placements WHERE task_id = ?').run(taskId) + } + const task = db.getTask(taskId) + if (task?.status === 'dispatched') { + const failed = createdByStart + transitionLifecycleWithDb(db.db, { + entity: 'task', + id: taskId, + from: 'dispatched', + to: failed ? 'failed' : placement.prior_task_status, + ...(failed ? { projection: { completed_at: new Date().toISOString() } } : {}) + }) + } + } + commitLifecycleWriteTransaction(db.db, transaction) + } catch (error) { + rollbackLifecycleWriteTransaction(db.db, transaction) + throw error + } +} + +/** + * The server confirmed it runs `dispatchId` for the Task (launch, then record). Recorded only while + * the link is still open and the Task is still placed there, so a late answer after a reset records + * nothing. Identity only; the Dispatch's state comes from the server's queue. + */ +export function recordRemoteStart( + db: OrchestrationDb, + params: { + conversationId: string + taskId: string + dispatchId: string + requestKey: string + peerRunId?: string + agent?: string | null + } +): RemoteDispatchRow | undefined { + const transaction = beginLifecycleWriteTransaction(db.db, 'record_remote_start') + try { + const link = getOpenRemoteRunLink(db, params.conversationId) + const placement = getRemotePlacement(db, params.taskId) + const ours = + placement?.conversation_id === params.conversationId && + (placement.request_key === params.requestKey || placement.dispatch_id === params.dispatchId) + const record = + link && ours + ? adoptRemoteAttempt(db, link, { + taskId: params.taskId, + dispatchId: params.dispatchId, + agent: params.agent + }) + : undefined + if (record && params.peerRunId) { + noteRemoteRunLinkPeerRun(db, params.conversationId, params.peerRunId) + } + commitLifecycleWriteTransaction(db.db, transaction) + return record + } catch (error) { + rollbackLifecycleWriteTransaction(db.db, transaction) + throw error + } +} + +/** + * A Dispatch the server started for a Task placed through this link becomes the Task's current + * attempt. Called inside its caller's transaction, after the caller re-read the link as open. + */ +export function adoptRemoteAttempt( + db: OrchestrationDb, + link: RemoteRunLinkRow, + attempt: { taskId: string; dispatchId: string; agent?: string | null } +): RemoteDispatchRow { + const known = getRemoteDispatch(db, attempt.dispatchId) + const record = ensureRemoteDispatchRecord(db, link, attempt) + const placement = getRemotePlacement(db, attempt.taskId) + if ( + placement?.conversation_id !== link.conversation_id || + placement.dispatch_id === record.dispatch_id + ) { + return record + } + if (known) { + // A Dispatch this Orca already knew predates the placement's attempt or reservation; only a new one is its answer. + return record + } + db.db + .prepare(`UPDATE remote_placements SET state = 'accepted', dispatch_id = ? WHERE task_id = ?`) + .run(record.dispatch_id, attempt.taskId) + const task = db.getTask(attempt.taskId) + // A retry the server started reopens the Task here, as a local retry's claim does. + if (task && task.status !== 'dispatched' && isRemoteDispatchActive(record)) { + transitionLifecycleWithDb(db.db, { + entity: 'task', + id: task.id, + from: task.status, + to: 'dispatched', + projection: { result: null, completed_at: null } + }) + } + return record +} + +export function noteRemoteRunLinkPeerRun( + db: OrchestrationDb, + conversationId: string, + peerRunId: string +): void { + db.db + .prepare( + `UPDATE remote_run_links SET peer_run_id = ? WHERE conversation_id = ? AND peer_run_id IS NULL` + ) + .run(peerRunId, conversationId) +} + +/** + * The attempt whose result the Task takes: the Dispatch its placement holds, unless the Task has + * since been started here, where a local Dispatch speaks for it. + */ +export function currentRemoteAttempt( + db: OrchestrationDb, + taskId: string +): RemoteDispatchRow | undefined { + const placement = getLiveRemotePlacement(db, taskId) + if (placement?.state !== 'accepted' || !placement.dispatch_id) { + return undefined + } + if (getActiveDispatchForTask(db, taskId)) { + return undefined + } + return getRemoteDispatch(db, placement.dispatch_id) +} + +/** + * How a Task's placement on a server holds it, for the guards a local Dispatch would trip: a + * reservation holds it as a starting worker; an accepted attempt as its Dispatch and worker do. + */ +export function remoteHoldOnTask( + db: OrchestrationDb, + taskId: string +): { dispatchId: string | null; active: boolean; liveWorker: boolean } | undefined { + const placement = getLiveRemotePlacement(db, taskId) + if (!placement) { + return undefined + } + if (placement.state === 'reserved') { + return { dispatchId: placement.dispatch_id, active: true, liveWorker: true } + } + const attempt = currentRemoteAttempt(db, taskId) + if (!attempt || attempt.task_settled_here) { + return undefined + } + // The server owns the Task until its result has come home: a finished worker whose Task here is + // still dispatched holds it just as a running one does. + const held = !isRemoteDispatchTerminal(attempt) || db.getTask(taskId)?.status === 'dispatched' + return held ? { dispatchId: attempt.dispatch_id, active: true, liveWorker: true } : undefined +} + +/** + * A stop or abandon the server did not answer: the Task half runs here at once, as a local stop's + * does (blocked, so it can be retried), while the stop stays owed. The first result stands, so a + * later state from the server changes only this attempt's record. + */ +export function settleRemoteAttemptHere( + db: OrchestrationDb, + dispatchId: string, + how: 'stopped' | 'abandoned' +): void { + runLifecycleWriteTransaction(db.db, 'settle_remote_attempt_here', () => { + const record = getRemoteDispatch(db, dispatchId) + if (!record) { + return + } + if (how === 'abandoned') { + db.db + .prepare('UPDATE remote_dispatches SET task_settled_here = ? WHERE dispatch_id = ?') + .run(ABANDONED_HERE, dispatchId) + } + if (record.task_settled_here) { + return + } + const current = currentRemoteAttempt(db, record.task_id)?.dispatch_id === dispatchId + if (how === 'stopped') { + db.db + .prepare('UPDATE remote_dispatches SET task_settled_here = 1 WHERE dispatch_id = ?') + .run(dispatchId) + } + if (current) { + reconcileTaskAfterDispatchInterruption(db, record.task_id, dispatchId) + } + }) +} diff --git a/src/main/runtime/orchestration/db/remote-owned/remote-run-links.ts b/src/main/runtime/orchestration/db/remote-owned/remote-run-links.ts new file mode 100644 index 00000000000..a97cfa36acd --- /dev/null +++ b/src/main/runtime/orchestration/db/remote-owned/remote-run-links.ts @@ -0,0 +1,309 @@ +import type { OrchestrationWorkerServer } from '../../federation/environment-transport' +import { generateId } from '../generated-id' +import { + beginLifecycleWriteTransaction, + commitLifecycleWriteTransaction, + rollbackLifecycleWriteTransaction, + transitionLifecycleWithDb +} from '../lifecycle-transition' +import type { OrchestrationDb } from '../orchestration-db' +import { writtenRow } from './written-row' +import { escalateWorkerFailure } from '../../workers/reports/worker-failure-escalation' + +export type RemoteRunLinkRow = { + conversation_id: string + run_id: string + environment_id: string + peer_fingerprint: string + home_fingerprint: string + pairing_revision: number | null + peer_run_id: string | null + state: 'open' | 'cancel_owed' | 'closed' + cancel_key: string | null + cancel_attempt: number + cancel_retries: number + cancel_retry_at: number | null + last_imported_sequence: number + last_error: string | null + server_name: string | null + created_at: string +} + +/** The pairing a link was made under: the server's host key, this Orca's credential there, and the re-pair generation. */ +export type RemoteServerPin = Pick< + RemoteRunLinkRow, + 'environment_id' | 'peer_fingerprint' | 'home_fingerprint' | 'pairing_revision' +> + +export function remoteServerPin(server: OrchestrationWorkerServer): RemoteServerPin { + return { + environment_id: server.environmentId, + peer_fingerprint: server.peerFingerprint, + home_fingerprint: server.homePeerFingerprint ?? server.peerFingerprint, + pairing_revision: server.pairingRevision ?? null + } +} + +/** A re-made pairing reaches a different identity on the server, which owns none of this link's work. */ +export function remoteRunLinkPinMatches(link: RemoteServerPin, server: RemoteServerPin): boolean { + return ( + link.environment_id === server.environment_id && + link.peer_fingerprint === server.peer_fingerprint && + link.home_fingerprint === server.home_fingerprint && + link.pairing_revision === server.pairing_revision + ) +} + +export function getRemoteRunLink( + db: OrchestrationDb, + conversationId: string +): RemoteRunLinkRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table returns exactly its row shape. + return db.db + .prepare('SELECT * FROM remote_run_links WHERE conversation_id = ?') + .get(conversationId) as RemoteRunLinkRow | undefined +} + +/** The link a write about this Run's remote work may still land under; a reset or re-pair since then closed it. */ +export function getOpenRemoteRunLink( + db: OrchestrationDb, + conversationId: string +): RemoteRunLinkRow | undefined { + const link = getRemoteRunLink(db, conversationId) + return link?.state === 'open' ? link : undefined +} + +/** Written before the first command about the Run reaches the server, so its queue always has a reader here. */ +export function openRemoteRunLink( + db: OrchestrationDb, + runId: string, + server: OrchestrationWorkerServer, + notify?: (handle: string, messageType: string) => void +): RemoteRunLinkRow { + const pin = remoteServerPin(server) + const transaction = beginLifecycleWriteTransaction(db.db, 'open_remote_run_link') + try { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table returns exactly its row shape. + const open = db.db + .prepare( + `SELECT * FROM remote_run_links WHERE run_id = ? AND environment_id = ? AND state = 'open'` + ) + .get(runId, pin.environment_id) as RemoteRunLinkRow | undefined + let link = open + if (open && !remoteRunLinkPinMatches(open, pin)) { + // Nothing can reach that link's work any more: the server knows this Orca by another pairing now. + closeRemoteRunLink( + db, + open.conversation_id, + `The pairing with ${server.name} was re-made.`, + notify + ) + link = undefined + } + if (!link) { + const conversationId = generateId('peerconv') + db.db + .prepare( + `INSERT INTO remote_run_links ( + conversation_id, run_id, environment_id, peer_fingerprint, home_fingerprint, pairing_revision, + server_name + ) VALUES (?, ?, ?, ?, ?, ?, ?)` + ) + .run( + conversationId, + runId, + pin.environment_id, + pin.peer_fingerprint, + pin.home_fingerprint, + pin.pairing_revision, + server.name + ) + link = getRemoteRunLink(db, conversationId) + } + commitLifecycleWriteTransaction(db.db, transaction) + return writtenRow(link, `Link for Run ${runId}`) + } catch (error) { + rollbackLifecycleWriteTransaction(db.db, transaction) + throw error + } +} + +/** Servers with a link whose queue still needs reading or whose cancel is still owed. */ +export function listLiveRemoteRunLinkEnvironments(db: OrchestrationDb): string[] { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT over this table returns exactly these columns. + const rows = db.db + .prepare( + `SELECT DISTINCT environment_id FROM remote_run_links WHERE state IN ('open', 'cancel_owed')` + ) + .all() as { environment_id: string }[] + return rows.map((row) => row.environment_id) +} + +export function listOwedRemoteRunCancels( + db: OrchestrationDb, + environmentId: string +): RemoteRunLinkRow[] { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table returns exactly its row shape. + return db.db + .prepare( + `SELECT * FROM remote_run_links WHERE environment_id = ? AND state = 'cancel_owed' ORDER BY rowid` + ) + .all(environmentId) as RemoteRunLinkRow[] +} + +/** Part of both resets: every open link owes its server a cancel under a fresh key, and keeps its import position as the tombstone. */ +export const OWE_REMOTE_RUN_CANCELS_SQL = ` + UPDATE remote_run_links + SET state = 'cancel_owed', cancel_key = 'cancel:' || lower(hex(randomblob(12))), + cancel_attempt = 0, cancel_retries = 0, cancel_retry_at = NULL, last_error = NULL + WHERE state = 'open'; + DELETE FROM remote_placements; + DELETE FROM remote_dispatches; + DELETE FROM remote_stop_intents; + DELETE FROM remote_owned_questions; +` + +/** + * The server can no longer answer for this link's work (its pairing was re-made, or it was removed): nothing more is sent for it, each Task it held fails here + * through the ordinary Task half with the reason. Its placements stay, holding nothing, so a start + * there of one of its Tasks is refused here. + */ +export function closeRemoteRunLink( + db: OrchestrationDb, + conversationId: string, + reason: string, + notify: (handle: string, messageType: string) => void = () => undefined +): void { + const transaction = beginLifecycleWriteTransaction(db.db, 'close_remote_run_link') + try { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT of one column returns exactly that column. + const held = db.db + .prepare( + `SELECT placement.task_id, placement.run_id, placement.dispatch_id, task.status + FROM remote_placements placement JOIN tasks task ON task.id = placement.task_id + LEFT JOIN remote_dispatches attempt ON attempt.dispatch_id = placement.dispatch_id + WHERE placement.conversation_id = ? + AND (task.status = 'dispatched' OR (task.status = 'blocked' AND attempt.stop_owed = 1))` + ) + .all(conversationId) as { + task_id: string + run_id: string + dispatch_id: string | null + status: 'dispatched' | 'blocked' + }[] + const now = new Date().toISOString() + const result = `${reason} Its worker may still run there.` + for (const placement of held) { + transitionLifecycleWithDb(db.db, { + entity: 'task', + id: placement.task_id, + // Blocked by a stop the server never proved, which nothing can prove now; a proven stop or an abandon stays blocked. + from: placement.status, + to: 'failed', + projection: { result, completed_at: now } + }) + // As a local worker's failure is: the Run's coordinator is told. + const dispatchId = placement.dispatch_id ?? placement.task_id + escalateWorkerFailure( + db, + { id: dispatchId, run_id: placement.run_id, task_id: placement.task_id }, + { + id: `msg_unlinked_${conversationId}_${placement.task_id}`, + from: `dispatch:${dispatchId}`, + describe: (task) => ({ + subject: 'Worker unreachable: its server no longer answers here', + body: `Task ${task} failed here: ${result}` + }), + payload: { taskId: placement.task_id, dispatchId: placement.dispatch_id } + }, + notify + ) + } + db.db + .prepare( + `UPDATE remote_run_links SET state = 'closed', last_error = ? + WHERE conversation_id = ? AND state <> 'closed'` + ) + .run(reason, conversationId) + // Nothing there can prove a stop now, and nothing here may send one. + db.db + .prepare( + `UPDATE remote_dispatches SET stop_owed = 0, stop_retry_at = NULL WHERE conversation_id = ?` + ) + .run(conversationId) + commitLifecycleWriteTransaction(db.db, transaction) + } catch (error) { + rollbackLifecycleWriteTransaction(db.db, transaction) + throw error + } +} + +/** Every open link to this server made under an earlier pairing: none of their work answers here now. */ +export function closeRemoteRunLinksOfChangedPairing( + db: OrchestrationDb, + server: RemoteServerPin, + serverName: string, + notify: (handle: string, messageType: string) => void +): void { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table returns exactly its row shape. + const links = db.db + .prepare(`SELECT * FROM remote_run_links WHERE environment_id = ? AND state = 'open'`) + .all(server.environment_id) as RemoteRunLinkRow[] + for (const link of links) { + if (!remoteRunLinkPinMatches(link, server)) { + closeRemoteRunLink( + db, + link.conversation_id, + `The pairing with ${serverName} was re-made.`, + notify + ) + } + } +} + +/** Every link to a server this Orca no longer pairs with: none of their work can be reached again. */ +export function closeRemoteRunLinksOfRemovedServer( + db: OrchestrationDb, + environmentId: string, + reason: string, + notify: (handle: string, messageType: string) => void +): void { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT of one column returns exactly that column. + const links = db.db + .prepare( + `SELECT conversation_id FROM remote_run_links WHERE environment_id = ? AND state <> 'closed'` + ) + .all(environmentId) as { conversation_id: string }[] + for (const link of links) { + closeRemoteRunLink(db, link.conversation_id, reason, notify) + } +} + +/** Why the link's queue stopped being read; shown with the link, cleared by its next import. */ +export function noteRemoteRunLinkError( + db: OrchestrationDb, + conversationId: string, + error: unknown +): void { + db.db + // A closed link keeps why it closed. + .prepare( + `UPDATE remote_run_links SET last_error = ? WHERE conversation_id = ? AND state <> 'closed'` + ) + .run(error instanceof Error ? error.message : String(error), conversationId) +} + +/** The server answers again: every stop and cancel owed to it is due now instead of after its backoff. */ +export function dueRemoteResendsNow(db: OrchestrationDb, environmentId: string): void { + db.db + .prepare( + `UPDATE remote_dispatches SET stop_retry_at = NULL WHERE environment_id = ? AND stop_owed = 1` + ) + .run(environmentId) + db.db + .prepare( + `UPDATE remote_run_links SET cancel_retry_at = NULL + WHERE environment_id = ? AND state = 'cancel_owed'` + ) + .run(environmentId) +} diff --git a/src/main/runtime/orchestration/db/remote-owned/written-row.ts b/src/main/runtime/orchestration/db/remote-owned/written-row.ts new file mode 100644 index 00000000000..b8b63016c63 --- /dev/null +++ b/src/main/runtime/orchestration/db/remote-owned/written-row.ts @@ -0,0 +1,7 @@ +/** A row read back inside the transaction that just wrote it; its absence is a broken invariant, not a state. */ +export function writtenRow(row: T | undefined, what: string): T { + if (row === undefined) { + throw new Error(`${what} was not found right after it was written.`) + } + return row +} diff --git a/src/main/runtime/orchestration/db/reset/orchestration-reset.ts b/src/main/runtime/orchestration/db/reset/orchestration-reset.ts index b8af86962be..ecce599a455 100644 --- a/src/main/runtime/orchestration/db/reset/orchestration-reset.ts +++ b/src/main/runtime/orchestration/db/reset/orchestration-reset.ts @@ -6,6 +6,7 @@ import { readRemovedWorkWatermark, summarizeRemovedWorkSince } from './removed-orchestration-work-read' +import { OWE_REMOTE_RUN_CANCELS_SQL } from '../remote-owned/remote-run-links' /** Returns the removed-work watermark, read inside the transaction so the reply counts only this reset. */ export function runResetTransaction( @@ -39,6 +40,7 @@ export function resetAll(this: OrchestrationDb): void { // Keep receipts so a lost reset reply cannot replay the mutation. this.runResetTransaction( ` + ${OWE_REMOTE_RUN_CANCELS_SQL} DELETE FROM coordinator_runs; DELETE FROM decision_gates; DELETE FROM remote_questions; @@ -75,6 +77,7 @@ export function resetTasks(this: OrchestrationDb): ResetRemovedWork | undefined // Messages survive, and so do replies waiting for a paired Orca to pull them; close threads so orphaned questions cannot masquerade as generic replies. const watermark = this.runResetTransaction( ` + ${OWE_REMOTE_RUN_CANCELS_SQL} DELETE FROM coordinator_runs; DELETE FROM decision_gates; DELETE FROM remote_questions; diff --git a/src/main/runtime/orchestration/db/schema/create-tables.ts b/src/main/runtime/orchestration/db/schema/create-tables.ts index 5378ee71629..27aee9c3f6e 100644 --- a/src/main/runtime/orchestration/db/schema/create-tables.ts +++ b/src/main/runtime/orchestration/db/schema/create-tables.ts @@ -3,16 +3,31 @@ import { createCoreTablesSql } from './create-core-tables-sql' import { createGraphTablesSql } from './create-graph-tables-sql' import { DERIVED_DELIVERY_SCHEMA_SQL } from './migrate-v41' import { REMOVED_WORK_SCHEMA_SQL } from '../reset/removed-orchestration-work-store' +import { REMOTE_OWNED_SCHEMA_SQL } from '../remote-owned/remote-owned-schema-sql' import { PEER_RUN_SCHEMA_SQL } from '../peer-runs/peer-run-queue-sql' export function createTables(this: OrchestrationDb): void { this.db.exec( - `${createCoreTablesSql()}\n${createGraphTablesSql()}\n${REMOVED_WORK_SCHEMA_SQL}\n${PEER_RUN_SCHEMA_SQL}` + `${createCoreTablesSql()}\n${createGraphTablesSql()}\n${REMOVED_WORK_SCHEMA_SQL}\n${REMOTE_OWNED_SCHEMA_SQL}\n${PEER_RUN_SCHEMA_SQL}` ) // Unreleased builds saved each send's fence as NOT NULL; nothing reads it, and new rows carry none. if (this.hasColumn('structured_mail_sends', 'fence')) { this.db.exec('ALTER TABLE structured_mail_sends DROP COLUMN fence') } + // Unreleased builds of remote-owned workers kept an orphan-lookup fence on placements and had no settled-here mark. + for (const column of ['reserved_by_runtime', 'outcome_unknown']) { + if (this.hasColumn('remote_placements', column)) { + this.db.exec(`ALTER TABLE remote_placements DROP COLUMN ${column}`) + } + } + if (!this.hasColumn('remote_run_links', 'server_name')) { + this.db.exec('ALTER TABLE remote_run_links ADD COLUMN server_name TEXT') + } + if (!this.hasColumn('remote_dispatches', 'task_settled_here')) { + this.db.exec( + 'ALTER TABLE remote_dispatches ADD COLUMN task_settled_here INTEGER NOT NULL DEFAULT 0' + ) + } this.createMailboxDeliveryIndexesIfPossible() this.db.exec(DERIVED_DELIVERY_SCHEMA_SQL) } diff --git a/src/main/runtime/orchestration/db/tasks/task-start-claim.ts b/src/main/runtime/orchestration/db/tasks/task-start-claim.ts new file mode 100644 index 00000000000..2be9f4aec76 --- /dev/null +++ b/src/main/runtime/orchestration/db/tasks/task-start-claim.ts @@ -0,0 +1,119 @@ +import type { TaskRow } from '../orchestration-records' +import type { OrchestrationDb } from '../orchestration-db' +import { taskNotStartableError } from '../../coordinator/dispatch/task-dispatch-refusal' +import { + getLiveRemotePlacement, + retireRemotePlacement +} from '../remote-owned/remote-placement-hold' +import { + getRemoteDispatch, + isRemoteAttemptSettledForRetry +} from '../remote-owned/remote-dispatch-records' + +/** + * The one claim every start of a Task passes, inside its caller's write transaction: a start here, + * or a start placed on a paired server (`onServer`). While a start is being placed on a server, its + * reservation is the Task's claim and every other start is refused. + */ +export function claimTaskForStart( + db: OrchestrationDb, + task: TaskRow, + start: { retryOf?: string; onServer?: string } +): { priorFailures: number } { + const placement = getLiveRemotePlacement(db, task.id) + if (placement?.state === 'reserved') { + throw taskNotStartableError( + db, + `Task ${task.id} is ${task.status}; only a ready Task can start.`, + task + ) + } + if (start.onServer !== undefined) { + // The server checks the rest of the retry chain on its own attempt; here it must be the Task's latest. + if ( + start.retryOf !== undefined && + (placement?.environment_id !== start.onServer || + placement.dispatch_id !== start.retryOf || + !['failed', 'blocked'].includes(task.status)) + ) { + throw taskNotStartableError( + db, + `Task ${task.id} cannot retry from Dispatch ${start.retryOf}.`, + task, + start.retryOf + ) + } + if (start.retryOf === undefined) { + requireReadyTask(db, task) + } + return { priorFailures: 0 } + } + let priorFailures = 0 + const remotePrior = + start.retryOf && placement?.dispatch_id === start.retryOf + ? getRemoteDispatch(db, start.retryOf) + : undefined + if (remotePrior) { + // The Task's latest attempt ran on a paired server: a retry here follows it by the same rule. + if ( + !isRemoteAttemptSettledForRetry(remotePrior) || + !['failed', 'blocked'].includes(task.status) + ) { + throw taskNotStartableError( + db, + `Task ${task.id} cannot retry from Dispatch ${start.retryOf}.`, + task, + start.retryOf + ) + } + } else if (start.retryOf) { + const prior = db.getDispatchContextById(start.retryOf) + const priorWorker = db.getWorkerDispatch(start.retryOf) + const latest = db.getDispatchContext(task.id) + if (prior?.task_id === task.id && prior.status === 'circuit_broken') { + throw taskNotStartableError( + db, + `Task ${task.id} failed ${prior.failure_count} times, so Orca will not retry it again (last error: ${prior.last_failure ?? 'unknown'}). Report the failure to the user instead of retrying.`, + task, + start.retryOf, + prior.failure_count + ) + } + // Context-only Dispatches have no worker row; read settlement from the Dispatch itself. + const priorSettled = priorWorker + ? ['failed', 'stopped', 'abandoned'].includes(priorWorker.state) + : prior?.status === 'failed' + if ( + !prior || + prior.task_id !== task.id || + latest?.id !== prior.id || + // A later attempt on a paired server, not the local one named, is the Task's latest. + placement?.dispatch_id != null || + !priorSettled || + !['failed', 'blocked'].includes(task.status) + ) { + throw taskNotStartableError( + db, + `Task ${task.id} cannot retry from Dispatch ${start.retryOf}.`, + task, + start.retryOf + ) + } + // Only a retry chain inherits failures; a fresh start after a worker exit keeps its own count. + priorFailures = prior.failure_count + } else { + requireReadyTask(db, task) + } + retireRemotePlacement(db, task.id) + return { priorFailures } +} + +function requireReadyTask(db: OrchestrationDb, task: TaskRow): void { + if (task.status !== 'ready') { + throw taskNotStartableError( + db, + `Task ${task.id} is ${task.status}; only a ready Task can start.`, + task + ) + } +} diff --git a/src/main/runtime/orchestration/db/tasks/task-status-transition.ts b/src/main/runtime/orchestration/db/tasks/task-status-transition.ts index 5020f9490d8..04c1edf0d97 100644 --- a/src/main/runtime/orchestration/db/tasks/task-status-transition.ts +++ b/src/main/runtime/orchestration/db/tasks/task-status-transition.ts @@ -2,6 +2,7 @@ import { OrchestrationError } from '../../orchestration-error' import type { TaskRow, TaskStatus } from '../orchestration-records' import { settleActiveDispatchesForTask } from '../dispatch-context/dispatch-completion' import type { OrchestrationDb } from '../orchestration-db' +import { remoteHoldOnTask } from '../remote-owned/remote-placements' import { beginLifecycleWriteTransaction, commitLifecycleWriteTransaction, @@ -28,18 +29,22 @@ export function updateTaskStatus( commitLifecycleWriteTransaction(this.db, transaction) return undefined } - const active = this.db + const localActive = this.db .prepare( `SELECT id FROM dispatch_contexts WHERE task_id = ? AND status IN ('pending', 'dispatched') ORDER BY rowid DESC LIMIT 1` ) .get(id) as { id: string } | undefined + // A Task placed on a paired server is held by its attempt there exactly as by a local one. + const remote = remoteHoldOnTask(this, id) + const remoteDispatch = { id: remote?.dispatchId ?? '(a start on a paired server)' } + const active = localActive ?? (remote?.active ? remoteDispatch : undefined) // A live supervised worker forbids Task reopening; a dispatched no-op remains legal (#16904). const reopensUnderWorker = requiresActiveDispatch && task.status !== 'dispatched' const activeWorker = terminalStatus || reopensUnderWorker - ? (this.db + ? ((this.db .prepare( `SELECT active.id FROM dispatch_contexts active @@ -48,7 +53,8 @@ export function updateTaskStatus( AND worker.state NOT IN ('failed', 'succeeded', 'stopped', 'abandoned') ORDER BY active.rowid DESC LIMIT 1` ) - .get(id) as { id: string } | undefined) + .get(id) as { id: string } | undefined) ?? + (remote?.liveWorker ? remoteDispatch : undefined)) : undefined if (activeWorker) { throw new OrchestrationError( diff --git a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts index f45cf6677e0..c253eac1a57 100644 --- a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts +++ b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts @@ -7,10 +7,8 @@ import type { OrchestrationDb } from '../orchestration-db' import { insertStartingDispatchContextRow } from '../dispatch-row-writer' import { recordedCreatorIdentity, type DispatchCreator } from '../dispatch-depth' import { transitionLifecycleWithDb } from '../lifecycle-transition' -import { - taskNotFoundError, - taskNotStartableError -} from '../../coordinator/dispatch/task-dispatch-refusal' +import { taskNotFoundError } from '../../coordinator/dispatch/task-dispatch-refusal' +import { claimTaskForStart } from '../tasks/task-start-claim' import { getFollowUpDispatch, takeFollowUpMail } from '../dispatch-context/worker-follow-up-lineage' export function createStartingWorkerDispatch( @@ -127,47 +125,7 @@ export function createStartingWorkerDispatch( { effectsApplied: false } ) } - let priorFailures = 0 - if (params.retryOf) { - const prior = this.getDispatchContextById(params.retryOf) - const priorWorker = this.getWorkerDispatch(params.retryOf) - const latest = this.getDispatchContext(task.id) - if (prior?.task_id === task.id && prior.status === 'circuit_broken') { - throw taskNotStartableError( - this, - `Task ${task.id} failed ${prior.failure_count} times, so Orca will not retry it again (last error: ${prior.last_failure ?? 'unknown'}). Report the failure to the user instead of retrying.`, - task, - params.retryOf, - prior.failure_count - ) - } - // Context-only Dispatches have no worker row; read settlement from the Dispatch itself. - const priorSettled = priorWorker - ? ['failed', 'stopped', 'abandoned'].includes(priorWorker.state) - : prior?.status === 'failed' - if ( - !prior || - prior.task_id !== task.id || - latest?.id !== prior.id || - !priorSettled || - !['failed', 'blocked'].includes(task.status) - ) { - throw taskNotStartableError( - this, - `Task ${task.id} cannot retry from Dispatch ${params.retryOf}.`, - task, - params.retryOf - ) - } - // Only a retry chain inherits failures; a fresh start after a worker exit keeps its own count. - priorFailures = prior.failure_count - } else if (task.status !== 'ready') { - throw taskNotStartableError( - this, - `Task ${task.id} is ${task.status}; only a ready Task can start.`, - task - ) - } + const { priorFailures } = claimTaskForStart(this, task, { retryOf: params.retryOf }) const id = generateId('ctx') const creatorDispatchId = this.resolveCreatorDispatchId(params.creator) diff --git a/src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.ts b/src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.ts index ea4ba3036eb..64a58fd6fe6 100644 --- a/src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.ts +++ b/src/main/runtime/orchestration/db/worker-dispatch/worker-terminal-recovery.ts @@ -1,5 +1,4 @@ import type { - TaskStatus, DispatchStatus, WorkerDispatchRow, LegacyWorkerTerminalRecoveryRow @@ -7,7 +6,10 @@ import type { import { OrchestrationError } from '../../orchestration-error' import { DISPATCH_CIRCUIT_BREAK_FAILURES } from '../dispatch-context/dispatch-circuit-breaker' import type { OrchestrationDb } from '../orchestration-db' -import { reconcileTaskAfterDispatchInterruption } from '../dispatch-context/task-dispatch-reconciliation' +import { + reconcileTaskAfterDispatchInterruption, + settleTaskAfterLostWorker +} from '../dispatch-context/task-dispatch-reconciliation' import { transitionLifecycleWithDb } from '../lifecycle-transition' export function listLegacyWorkerTerminalRecoveryRows( @@ -70,26 +72,12 @@ export function reconcileMissingWorkerTerminal( } }) if (!stopWasPending) { - const taskStatus: TaskStatus = dispatchStatus === 'circuit_broken' ? 'failed' : 'ready' reconcileTaskAfterDispatchInterruption(this, dispatch.task_id, dispatchId) - const task = this.getTask(dispatch.task_id) - if ( - task && - ['dispatched', 'blocked'].includes(task.status) && - !this.db - .prepare( - "SELECT 1 FROM dispatch_contexts WHERE task_id = ? AND status IN ('pending', 'dispatched')" - ) - .get(dispatch.task_id) - ) { - transitionLifecycleWithDb(this.db, { - entity: 'task', - id: dispatch.task_id, - from: task.status, - to: taskStatus, - projection: { completed_at: taskStatus === 'failed' ? new Date().toISOString() : null } - }) - } + settleTaskAfterLostWorker( + this, + dispatch.task_id, + dispatchStatus === 'circuit_broken' ? 'failed' : 'ready' + ) } this.closeQuestionsForDispatch(dispatchId) } diff --git a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts index e2ac481adc8..b6409bab3bd 100644 --- a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts +++ b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts @@ -7,6 +7,20 @@ import type { MessageRow } from '../../db/orchestration-records' import { federationRelayRetryDelayMs } from '../relay/federation-relay-scheduler' import type { OrchestrationEnvironmentTransport } from '../environment-transport' import { peerMailLocalRecipient } from './peer-mail-delivery' +import { presentImportedPeerItem } from '../../mailbox/formatting/imported-peer-item-presentation' +import { importRemoteOwnedItem } from '../../db/remote-owned/remote-owned-import' +import { + closeRemoteRunLinksOfChangedPairing, + closeRemoteRunLinksOfRemovedServer, + dueRemoteResendsNow, + getRemoteRunLink, + listLiveRemoteRunLinkEnvironments, + noteRemoteRunLinkError, + remoteServerPin +} from '../../db/remote-owned/remote-run-links' +import { resendOwedRemoteActions } from '../remote-owned/remote-owed-actions' +import { remoteServerName } from '../remote-owned/remote-owned-reads' +import { isRemoteServerUnreachable } from '../remote-owned/remote-server-unreachable' // Under the relay edge's idle cutoff, so an idle pull ends by itself instead of being dropped. const PULL_WAIT_MS = 20_000 @@ -18,17 +32,32 @@ const PulledPeerMail = z.object({ conversationId: z.string(), sequence: z.number().int().positive(), messageId: z.string(), + kind: z.string().optional(), payload: z.string() }) ) }) -type Loop = { db: OrchestrationDb; stopped: boolean } +/** What this Orca's pull loop last heard from a paired server; nothing until its first pull settles. */ +export type PeerServerAnswerStatus = { + /** When the server last answered a pull (an idle pull answers after its wait). */ + answeredAt?: number + /** Set while pulls get no answer at all; cleared by the next answer. */ + unreachableSince?: number +} -/** One pull loop per paired server this Orca opened conversations with. The server never dials - * back: each pull waits there for a reply, stores it as local mail, then acknowledges it. */ +type Loop = { + db: OrchestrationDb + stopped: boolean + resending: boolean +} + +/** One pull loop per paired server this Orca opened conversations with or coordinates Runs on. The + * server never dials back: each pull waits there for queued items, imports them, then acknowledges + * them. Stops and cancels this Orca owes the server go out on the same loop. */ export class PeerMailRelay { private readonly loops = new Map() + private readonly answers = new Map() constructor( private readonly runtime: OrcaRuntimeService, @@ -40,17 +69,25 @@ export class PeerMailRelay { return } const db = this.runtime.getOrchestrationDb() - for (const environmentId of db.listHomePeerMailEnvironments()) { + const environments = new Set([ + ...db.listHomePeerMailEnvironments(), + ...listLiveRemoteRunLinkEnvironments(db) + ]) + for (const environmentId of environments) { const current = this.loops.get(environmentId) if (current && !current.stopped && current.db === db) { continue } - const loop: Loop = { db, stopped: false } + const loop: Loop = { db, stopped: false, resending: false } this.loops.set(environmentId, loop) void this.run(environmentId, loop) } } + answerStatus(environmentId: string): PeerServerAnswerStatus | undefined { + return this.answers.get(environmentId) + } + stop(): void { for (const loop of this.loops.values()) { loop.stopped = true @@ -68,13 +105,33 @@ export class PeerMailRelay { private async run(environmentId: string, loop: Loop): Promise { let failures = 0 + // Named while it is still paired, so a removal can say which server went. + const serverName = remoteServerName(this.runtime, environmentId) while (this.isCurrent(environmentId, loop)) { try { await this.pullOnce(environmentId, loop) + if (failures > 0) { + // The server answers again: what this Orca owes it goes out now, not after its backoff. + dueRemoteResendsNow(loop.db, environmentId) + this.resendOwed(environmentId, loop) + } failures = 0 } catch { if (this.isEnvironmentRemoved(environmentId)) { - // A removed server cannot answer; the next ensure re-arms it if it is added back. + // A removed server cannot answer for its Runs' work again; their Tasks here fail with why. + try { + closeRemoteRunLinksOfRemovedServer( + loop.db, + environmentId, + `${serverName} was removed from this Orca's paired servers.`, + (handle, type) => this.runtime.notifyMessageArrived(handle, type) + ) + } catch (error) { + console.warn( + `[orchestration] Settling the Runs on removed server ${environmentId} failed:`, + error + ) + } break } failures += 1 @@ -98,12 +155,33 @@ export class PeerMailRelay { } private async pullOnce(environmentId: string, loop: Loop): Promise { - const response = await this.runtime.callOrchestrationWorkerServer( - environmentId, - 'orchestration.peerMailPull', - { waitMs: PULL_WAIT_MS }, - PULL_TIMEOUT_MS + // A re-pair is noticed here, not only by the next call through a link: its held Tasks fail now. + const server = this.runtime.resolveOrchestrationWorkerServer(environmentId) + closeRemoteRunLinksOfChangedPairing( + loop.db, + remoteServerPin(server), + server.name, + (handle, type) => this.runtime.notifyMessageArrived(handle, type) ) + this.resendOwed(environmentId, loop) + const response = await this.runtime + .callOrchestrationWorkerServer( + environmentId, + 'orchestration.peerMailPull', + { waitMs: PULL_WAIT_MS }, + PULL_TIMEOUT_MS + ) + .catch((error: unknown) => { + if (isRemoteServerUnreachable(error)) { + const known = this.answers.get(environmentId) + this.answers.set(environmentId, { + ...known, + unreachableSince: known?.unreachableSince ?? Date.now() + }) + } + throw error + }) + this.answers.set(environmentId, { answeredAt: Date.now() }) if (!this.isCurrent(environmentId, loop)) { return } @@ -112,28 +190,82 @@ export class PeerMailRelay { return } const through = new Map() + const stuck = new Map() for (const item of items) { - const stored = this.importReply(loop.db, environmentId, item) - // Wake before the ack: a replay after a failed ack finds the row stored and stays quiet. - if (stored) { - this.runtime.notifyMessageArrived(stored.to_handle, stored.type) + // An item that cannot be read holds back its own conversation only; the others keep moving. + if (stuck.has(item.conversationId)) { + continue + } + try { + const stored = this.importItem(loop.db, environmentId, item) + // Wake before the ack: a replay after a failed ack finds the row stored and stays quiet. + if (stored) { + this.runtime.notifyMessageArrived(stored.to, stored.type) + } + } catch (error) { + stuck.set(item.conversationId, error) + noteRemoteRunLinkError(loop.db, item.conversationId, error) + continue } through.set( item.conversationId, Math.max(through.get(item.conversationId) ?? 0, item.sequence) ) } - await this.runtime.callOrchestrationWorkerServer( - environmentId, - 'orchestration.peerMailAck', - { - acknowledgments: [...through].map(([conversationId, throughSequence]) => ({ - conversationId, - throughSequence - })) - }, - 15_000 - ) + if (through.size > 0) { + await this.runtime.callOrchestrationWorkerServer( + environmentId, + 'orchestration.peerMailAck', + { + acknowledgments: [...through].map(([conversationId, throughSequence]) => ({ + conversationId, + throughSequence + })) + }, + 15_000 + ) + } + const [failure] = stuck.values() + if (failure !== undefined) { + console.warn( + `[orchestration] Stopped reading ${stuck.size} conversation(s) from ${environmentId}:`, + failure instanceof Error ? failure.message : failure + ) + // Backs the loop off, so a server that keeps returning the same unreadable item is not re-pulled hot. + throw failure + } + } + + /** Stops and cancels owed to the server go out beside the pull, one batch at a time, so a slow answer never holds mail back. */ + private resendOwed(environmentId: string, loop: Loop): void { + if (loop.resending) { + return + } + loop.resending = true + void resendOwedRemoteActions(this.runtime, loop.db, environmentId) + .catch((error: unknown) => { + console.warn(`[orchestration] Owed actions for ${environmentId} failed:`, error) + }) + .finally(() => { + loop.resending = false + }) + } + + /** A Run this Orca coordinates there owns its conversation's items; any other is a peer-mail reply. */ + private importItem( + db: OrchestrationDb, + environmentId: string, + item: z.infer['items'][number] + ): { to: string; type: MessageRow['type'] } | undefined { + if (getRemoteRunLink(db, item.conversationId)) { + const server = this.runtime.resolveOrchestrationWorkerServer(environmentId) + return importRemoteOwnedItem(db, remoteServerPin(server), item, { + name: server.name, + notify: (handle, type) => this.runtime.notifyMessageArrived(handle, type) + }) + } + const stored = this.importReply(db, environmentId, item) + return stored ? { to: stored.to_handle, type: stored.type } : undefined } /** Stores a pulled reply once; a replay after a crash before the ack finds the stored row. */ @@ -157,15 +289,20 @@ export class PeerMailRelay { } const handle = peerMailLocalRecipient(this.runtime, conversation) const recipient = resolveBareOrchestrationRecipient({ runtime: this.runtime, db, handle }) + const presented = presentImportedPeerItem({ + kind: 'peer_mail', + senderLabel: payload.data.senderLabel, + body: payload.data.body + }) const stored = db.insertPeerMailMessage({ conversationId: conversation.conversation_id, remoteParty: payload.data.fromAddress, message: { id: item.messageId, - from: payload.data.senderLabel, + from: presented.from, to: recipient.ok ? recipient.to : handle, subject: payload.data.subject, - body: payload.data.body, + body: presented.body, threadId: payload.data.threadId ?? undefined, runId: recipient.ok ? recipient.runId : undefined } diff --git a/src/main/runtime/orchestration/federation/remote-owned/re-paired-run-list.ts b/src/main/runtime/orchestration/federation/remote-owned/re-paired-run-list.ts new file mode 100644 index 00000000000..821e720f275 --- /dev/null +++ b/src/main/runtime/orchestration/federation/remote-owned/re-paired-run-list.ts @@ -0,0 +1,26 @@ +import { OrchestrationError } from '../../orchestration-error' +import type { OrchestrationDb } from '../../db/orchestration-db' +import type { RemoteRunLinkRow } from '../../db/remote-owned/remote-run-links' + +/** The Run's newest link to the server: open, closed by a re-pair, or owing a reset's cancel. */ +export function latestRunLink( + db: OrchestrationDb, + runId: string, + environmentId: string +): RemoteRunLinkRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table returns exactly its row shape. + return db.db + .prepare( + 'SELECT * FROM remote_run_links WHERE run_id = ? AND environment_id = ? ORDER BY rowid DESC' + ) + .get(runId, environmentId) as RemoteRunLinkRow | undefined +} + +/** A re-pair is not recovered: the Run's earlier workers there are shown only from this Orca's record. */ +export function repairedListError(serverName: string): OrchestrationError { + return new OrchestrationError( + 'server_pairing_changed', + `${serverName} was re-paired; workers started before that are no longer listed here. worker-show still shows them from this computer's record.`, + { server: serverName } + ) +} diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-forward-caller.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-forward-caller.ts new file mode 100644 index 00000000000..f109be72c77 --- /dev/null +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-forward-caller.ts @@ -0,0 +1,46 @@ +import type { OrcaRuntimeService } from '../../../orca-runtime' +import type { RpcContext } from '../../../rpc/core' +import { remoteForwardRequestId } from './remote-owned-calls' + +/** + * Who is asking, as a retry of the same request must find it again: the caller's session, else + * its terminal's pane, which survives a restart, else the person at this Orca outside any terminal. + * Never one shared identity for every terminal, so two callers reusing an ID never collide. + */ +export function remoteForwardCallerNamespace( + runtime: Pick, + ctx: Pick, + callerHandle: string | undefined +): string { + const session = ctx.orchestrationCaller?.orcaSessionId + if (session) { + return `session:${session}` + } + const handle = callerHandle ?? ctx.orchestrationCompatibilityEvidence?.terminalHandle + const pane = + ctx.orchestrationCompatibilityEvidence?.paneKey ?? + (handle ? runtime.getTerminalPaneKey(handle) : null) + return pane + ? `pane:${pane}` + : `local:${runtime.getOrchestrationDb().getOrCreateLocalMutationCallerFingerprint()}` +} + +/** The key a forwarded call goes out under, and how to say it back in the caller's own terms. */ +export type RemoteForwardKey = { key: string; requestId: string } + +export function remoteForwardKey( + runtime: Pick, + ctx: Pick, + callerHandle: string | undefined, + requestId: string | undefined +): RemoteForwardKey | undefined { + return requestId + ? { + key: remoteForwardRequestId( + remoteForwardCallerNamespace(runtime, ctx, callerHandle), + requestId + ), + requestId + } + : undefined +} diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-owed-actions.test.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-owed-actions.test.ts new file mode 100644 index 00000000000..29cdbc4549b --- /dev/null +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-owed-actions.test.ts @@ -0,0 +1,482 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY, + ORCHESTRATION_CONTRACT_VERSION +} from '../../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { + RuntimeOrchestrationEnvelope, + RuntimeRpcResponse +} from '../../../../../shared/runtime-rpc-envelope' +import { OrcaRuntimeService } from '../../../orca-runtime' +import { RpcDispatcher } from '../../../rpc/dispatcher' +import { ORCHESTRATION_METHODS } from '../../../rpc/methods/orchestration/orchestration' +import { OrchestrationDb } from '../../db/orchestration-db' +import type { RunRow } from '../../db/orchestration-records' +import { + getRemoteDispatch, + oweRemoteDispatchStop +} from '../../db/remote-owned/remote-dispatch-records' +import { recordRemoteStart, reserveRemotePlacement } from '../../db/remote-owned/remote-placements' +import { importRemoteOwnedItem } from '../../db/remote-owned/remote-owned-import' +import { + getRemoteRunLink, + openRemoteRunLink, + remoteServerPin, + type RemoteRunLinkRow +} from '../../db/remote-owned/remote-run-links' +import type { + OrchestrationEnvironmentTransport, + OrchestrationWorkerServer +} from '../environment-transport' +import { resendOwedRemoteActions, sendOwedRemoteStop } from './remote-owed-actions' + +vi.mock('../relay/federation-relay-scheduler', async (original) => ({ + ...(await original()), + federationRelayRetryDelayMs: () => 5 +})) + +const COORDINATOR_PANE = 'tab_coord:11111111-1111-4111-8111-111111111111' + +type Sent = { method: string; params: unknown; envelope: RuntimeOrchestrationEnvelope | undefined } +type Answer = { result: unknown } | { error: string } + +const STOPPED = { + dispatchId: 'ctx_b1', + state: 'stopped', + alreadySettled: false, + processAction: 'closed_agent_terminal' +} + +describe('what the coordinating Orca owes a paired server', () => { + let db: OrchestrationDb + let runtime: OrcaRuntimeService + let run: RunRow + let link: RemoteRunLinkRow + let server: OrchestrationWorkerServer + let sent: Sent[] + let answers: Record + let beforeSend: () => Promise + let now: number + + // One per test: a stopped loop from an earlier test still finishing its pull must not take this one's items. + const createTransport = ( + sent: Sent[], + answers: Record, + pulls: unknown[][] + ): OrchestrationEnvironmentTransport => ({ + resolve: () => server, + hasEnvironment: () => true, + call: async (_selector, method, params, _timeout, envelope, _revision, send) => { + const ok = (result: unknown): RuntimeRpcResponse => ({ + id: method, + ok: true, + result, + _meta: { runtimeId: 'runtime_b' } + }) + if (method === 'status.get') { + return ok({ capabilities: [ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY] }) + } + if (method === 'orchestration.peerMailPull') { + await new Promise((resolve) => setImmediate(resolve)) + return ok({ items: pulls.shift() ?? [] }) + } + await beforeSend() + // The socket's own preparation runs last, as it does just before a real frame leaves. + const prepared = send?.prepareRequest?.({ params, envelope, measure: () => 0 }) + sent.push({ + method, + params: prepared?.params ?? params, + envelope: prepared?.envelope ?? envelope + }) + const answer = answers[method]?.shift() ?? { error: 'remote_runtime_unavailable' } + return 'result' in answer + ? ok(answer.result) + : { id: method, ok: false, error: { code: answer.error, message: answer.error } } + } + }) + let pulls: unknown[][] + + beforeEach(() => { + sent = [] + answers = {} + pulls = [] + db = new OrchestrationDb(':memory:') + runtime = new OrcaRuntimeService(null, undefined, { + orchestrationEnvironmentTransport: createTransport(sent, answers, pulls) + }) + vi.spyOn(runtime, 'readMachineName').mockReturnValue('Mac A') + runtime.setOrchestrationDb(db) + server = { + environmentId: 'env_b', + name: 'devB', + peerFingerprint: 'host_b', + homePeerFingerprint: 'cred_a', + pairingRevision: 1 + } + beforeSend = async () => undefined + now = 1_000_000 + vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => + handle === 'term_coord' ? COORDINATOR_PANE : null + ) + run = db.createRun({ + objective: 'Ship', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: COORDINATOR_PANE + }) + link = openRemoteRunLink(db, run.id, server) + }) + + afterEach(() => { + runtime.stopOrchestrationFederationRelay() + db.close() + }) + + function startedOnB(taskId = 'task_t', dispatchId = 'ctx_b1') { + reserveRemotePlacement(db, { + link, + taskId, + requestKey: `key_${taskId}`, + create: { spec: 'work' } + }) + recordRemoteStart(db, { + conversationId: link.conversation_id, + taskId, + dispatchId, + requestKey: `key_${taskId}` + }) + return getRemoteDispatch(db, dispatchId)! + } + + const owed = () => getRemoteDispatch(db, 'ctx_b1')! + const terminalItem = (sequence: number) => ({ + conversationId: link.conversation_id, + sequence, + messageId: `state_${sequence}`, + kind: 'worker_state', + payload: JSON.stringify({ + v: 1, + id: `state_${sequence}`, + homeRunId: run.id, + peerRunId: 'run_on_b', + dispatch: { + id: 'ctx_b1', + taskId: 'task_t', + status: 'completed', + workerState: 'succeeded', + lastFailure: null, + agent: null + }, + task: { status: 'completed', result: 'done' }, + correctedUnobservedPrompt: false, + removed: null + }) + }) + const stopKeys = () => + sent + .filter((s) => s.method === 'orchestration.workerStop') + .map((s) => s.envelope?.orchestrationRequestId) + const resend = () => + resendOwedRemoteActions(runtime, db, 'env_b', { + now: () => (now += 120_000) + }) + + describe('#2 owed stop', () => { + it('reuses the key while the server does not answer, so its pending receipt completes the same stop', async () => { + startedOnB() + oweRemoteDispatchStop(db, 'ctx_b1', 'intent_1') + await resend() + await resend() + answers['orchestration.workerStop'] = [{ result: STOPPED }] + await resend() + expect(stopKeys()).toEqual(['stop-1.0:ctx_b1', 'stop-1.0:ctx_b1', 'stop-1.0:ctx_b1']) + expect(owed().stop_owed).toBe(0) + }) + + it('keeps the debt on a completed stop_unknown and runs the stop again under a fresh key', async () => { + startedOnB() + oweRemoteDispatchStop(db, 'ctx_b1', 'intent_1') + answers['orchestration.workerStop'] = [ + { result: { ...STOPPED, state: 'stop_unknown' } }, + { error: 'dispatch_inactive' }, + { result: STOPPED } + ] + await resend() + await resend() + expect(owed().stop_owed).toBe(1) + await resend() + expect(stopKeys()).toEqual(['stop-1.0:ctx_b1', 'stop-1.1:ctx_b1', 'stop-1.2:ctx_b1']) + expect(owed().stop_owed).toBe(0) + }) + + it('keeps the debt while a helper is starting or unconfirmed', async () => { + startedOnB() + oweRemoteDispatchStop(db, 'ctx_b1', 'intent_1') + for (const outcome of ['starting', 'unconfirmed'] as const) { + answers['orchestration.workerStop'] = [ + { + result: { + ...STOPPED, + helpers: [{ dispatchId: 'ctx_h', creatorDispatchId: 'ctx_b1', outcome }] + } + } + ] + await resend() + expect(owed().stop_owed).toBe(1) + } + answers['orchestration.workerStop'] = [ + { + result: { + ...STOPPED, + helpers: [{ dispatchId: 'ctx_h', creatorDispatchId: 'ctx_b1', outcome: 'kept_open' }] + } + } + ] + await resend() + expect(owed().stop_owed).toBe(0) + }) + + it('counts one intent once, and lets an older stop finishing late clear nothing newer or change the record', async () => { + startedOnB() + oweRemoteDispatchStop(db, 'ctx_b1', 'intent_1') + oweRemoteDispatchStop(db, 'ctx_b1', 'intent_1') + expect(owed().stop_count).toBe(1) + let release!: () => void + beforeSend = () => new Promise((resolve) => (release = resolve)) + answers['orchestration.workerStop'] = [{ result: STOPPED }] + const older = sendOwedRemoteStop(runtime, owed()) + await vi.waitFor(() => expect(release).toBeDefined()) + oweRemoteDispatchStop(db, 'ctx_b1', 'intent_2') + release() + await older + expect(owed()).toMatchObject({ + stop_owed: 1, + stop_count: 2, + status: 'pending', + worker_state: null + }) + }) + }) + + describe('#2 stop intents', () => { + it('owes a stop of a finished worker, whose helpers may still run, until the server proves it', async () => { + startedOnB() + importRemoteOwnedItem(db, remoteServerPin(server), terminalItem(1)) + expect(oweRemoteDispatchStop(db, 'ctx_b1', 'intent_1')?.stopCount).toBe(1) + expect(owed().stop_owed).toBe(1) + answers['orchestration.workerStop'] = [ + { + result: { + ...STOPPED, + alreadySettled: true, + helpers: [{ dispatchId: 'ctx_h', creatorDispatchId: 'ctx_b1', outcome: 'stopped' }] + } + } + ] + await resend() + expect(owed().stop_owed).toBe(0) + }) + + it('treats a terminal state item as a cue to resend, not as proof', async () => { + startedOnB() + oweRemoteDispatchStop(db, 'ctx_b1', 'intent_1') + answers['orchestration.workerStop'] = [{ result: { ...STOPPED, state: 'stop_unknown' } }] + await sendOwedRemoteStop(runtime, owed()) + expect(owed().stop_retry_at).not.toBeNull() + importRemoteOwnedItem(db, remoteServerPin(server), terminalItem(1)) + expect(owed()).toMatchObject({ stop_owed: 1, stop_retry_at: null }) + }) + + it('gives a retried older intent its own count instead of a new one', () => { + startedOnB() + expect(oweRemoteDispatchStop(db, 'ctx_b1', 'k1')?.stopCount).toBe(1) + expect(oweRemoteDispatchStop(db, 'ctx_b1', 'k2')?.stopCount).toBe(2) + expect(oweRemoteDispatchStop(db, 'ctx_b1', 'k1')?.stopCount).toBe(1) + expect(owed().stop_count).toBe(2) + }) + }) + + describe('#1 Run cancel', () => { + it('sends nothing once a reset lands while a forward waits for the socket', async () => { + startedOnB() + oweRemoteDispatchStop(db, 'ctx_b1', 'intent_1') + let release!: () => void + beforeSend = () => new Promise((resolve) => (release = resolve)) + const pending = sendOwedRemoteStop(runtime, owed()) + await vi.waitFor(() => expect(release).toBeDefined()) + db.resetTasks() + release() + await expect(pending).rejects.toMatchObject({ code: 'remote_link_closed' }) + expect(sent).toEqual([]) + }) + + it('resends a lost reply under the same key, a partial stop under a new attempt, until none remain', async () => { + startedOnB() + db.resetAll() + const key = getRemoteRunLink(db, link.conversation_id)!.cancel_key! + expect(key).toMatch(/^cancel:/) + answers['orchestration.peerRunCancel'] = [ + { error: 'runtime_timeout' }, + { result: { remaining: 1 } }, + { result: { remaining: 0 } } + ] + await resend() + await resend() + await resend() + const cancels = sent.filter((s) => s.method === 'orchestration.peerRunCancel') + expect(cancels.map((s) => s.envelope?.orchestrationRequestId)).toEqual([ + `${key}.0`, + `${key}.0`, + `${key}.1` + ]) + expect(cancels[0]!.envelope?.orchestrationPeerRun).toEqual({ + runId: run.id, + conversationId: link.conversation_id, + label: 'Mac A' + }) + expect(getRemoteRunLink(db, link.conversation_id)?.state).toBe('closed') + await resend() + expect(sent.filter((s) => s.method === 'orchestration.peerRunCancel')).toHaveLength(3) + }) + + it('gives a later start its own link and a fresh cancel key', async () => { + db.resetTasks() + const first = getRemoteRunLink(db, link.conversation_id)!.cancel_key + const next = openRemoteRunLink(db, run.id, server) + db.resetTasks() + expect(getRemoteRunLink(db, next.conversation_id)!.cancel_key).not.toBe(first) + expect(getRemoteRunLink(db, link.conversation_id)!.cancel_key).toBe(first) + }) + + it('re-arms the pull loop on reset, so the cancel goes out without another command', async () => { + const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) + answers['orchestration.peerRunCancel'] = [{ result: { remaining: 0 } }] + await dispatcher.dispatch({ + id: 'reset', + authToken: 'local', + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationRequestId: 'reset_1', + method: 'orchestration.reset', + params: { tasks: true } + }) + await vi.waitFor(() => + expect(getRemoteRunLink(db, link.conversation_id)?.state).toBe('closed') + ) + }) + }) + + describe('S7 pairing pin', () => { + it('sends nothing for links made under an earlier pairing', async () => { + startedOnB() + oweRemoteDispatchStop(db, 'ctx_b1', 'intent_1') + server = { ...server, homePeerFingerprint: 'cred_a_new', pairingRevision: 2 } + await resend() + expect(getRemoteRunLink(db, link.conversation_id)?.state).toBe('closed') + expect(db.updateTaskStatus('task_t', 'failed', 'unreachable')?.status).toBe('failed') + await resend() + expect(sent).toEqual([]) + }) + + it('ends a cancel owed under an earlier pairing without sending it', async () => { + db.resetTasks() + server = { ...server, homePeerFingerprint: 'cred_a_new', pairingRevision: 2 } + await resend() + expect(sent).toEqual([]) + expect(getRemoteRunLink(db, link.conversation_id)?.state).toBe('closed') + }) + }) + + describe('S7 re-pair while a send waits', () => { + it('closes the link and sends nothing when the pairing changes before the frame leaves', async () => { + startedOnB() + oweRemoteDispatchStop(db, 'ctx_b1', 'intent_1') + let release!: () => void + beforeSend = () => new Promise((resolve) => (release = resolve)) + const pending = sendOwedRemoteStop(runtime, owed()) + await vi.waitFor(() => expect(release).toBeDefined()) + server = { ...server, peerFingerprint: 'host_b_new' } + release() + await expect(pending).rejects.toMatchObject({ code: 'server_pairing_changed' }) + expect(sent).toEqual([]) + expect(getRemoteRunLink(db, link.conversation_id)?.state).toBe('closed') + expect(owed().stop_owed).toBe(0) + }) + it('names the re-pair, not a reset, when another path closed the link while a send waited', async () => { + startedOnB() + oweRemoteDispatchStop(db, 'ctx_b1', 'intent_1') + let release!: () => void + beforeSend = () => new Promise((resolve) => (release = resolve)) + const pending = sendOwedRemoteStop(runtime, owed()) + await vi.waitFor(() => expect(release).toBeDefined()) + server = { ...server, peerFingerprint: 'host_b_new' } + openRemoteRunLink(db, run.id, server) + release() + await expect(pending).rejects.toMatchObject({ + code: 'remote_link_closed', + message: `The pairing with devB was re-made, so it no longer runs Run ${run.id}'s workers. No effects were applied.` + }) + expect(sent).toEqual([]) + }) + }) + + describe('S8 pull loop', () => { + it('acknowledges what it imported before an unreadable item, and never that item', async () => { + startedOnB() + const state = (seq: number, payload?: string) => ({ + conversationId: link.conversation_id, + sequence: seq, + messageId: `state_${seq}`, + kind: 'worker_state', + payload: + payload ?? + JSON.stringify({ + v: 1, + id: `state_${seq}`, + homeRunId: run.id, + peerRunId: 'run_on_b', + dispatch: { + id: 'ctx_b1', + taskId: 'task_t', + status: 'dispatched', + workerState: 'ready', + lastFailure: null, + agent: null + }, + task: { status: 'dispatched', result: null }, + correctedUnobservedPrompt: false, + removed: null + }) + }) + const otherRun = db.createRun({ + objective: 'Other', + coordinatorHandle: null, + coordinatorPaneKey: null + }) + const other = openRemoteRunLink(db, otherRun.id, server) + const otherItem = { + ...state(7), + conversationId: other.conversation_id, + payload: state(7).payload.replace(run.id, otherRun.id) + } + pulls.push([state(1), { ...state(2), kind: 'worker_future' }, state(3), otherItem]) + answers['orchestration.peerMailAck'] = [{ result: { acknowledged: 1 } }] + runtime.ensureOrchestrationFederationRelay() + await vi.waitFor(() => + expect(sent.some((s) => s.method === 'orchestration.peerMailAck')).toBe(true) + ) + runtime.stopOrchestrationFederationRelay() + const acks = sent.filter((s) => s.method === 'orchestration.peerMailAck') + expect(acks.map((s) => s.params)).toEqual([ + { + acknowledgments: [ + { conversationId: link.conversation_id, throughSequence: 1 }, + { conversationId: other.conversation_id, throughSequence: 7 } + ] + } + ]) + expect(getRemoteRunLink(db, link.conversation_id)).toMatchObject({ + last_imported_sequence: 1, + last_error: expect.stringContaining('kind worker_future') + }) + }) + }) +}) diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-owed-actions.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-owed-actions.ts new file mode 100644 index 00000000000..39f58781451 --- /dev/null +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-owed-actions.ts @@ -0,0 +1,216 @@ +import { z } from 'zod' +import { mapWithConcurrency } from '../../../../../shared/map-with-concurrency' +import { HelperStopOutcome } from '../../../../../shared/orchestration/workers/orchestration-worker-stop-receipt' +import { PeerRunCancelResult } from '../../../../../shared/orchestration/remote-owned-wire' +import { OrchestrationError } from '../../orchestration-error' +import type { OrchestrationDb } from '../../db/orchestration-db' +import { + deferRemoteDispatchStop, + listOwedRemoteStops, + remoteResendRetryAt, + remoteStopKey, + settleRemoteDispatchStop, + type RemoteDispatchRow +} from '../../db/remote-owned/remote-dispatch-records' +import { + closeRemoteRunLink, + getRemoteRunLink, + listOwedRemoteRunCancels, + remoteRunLinkPinMatches, + remoteServerPin, + type RemoteRunLinkRow +} from '../../db/remote-owned/remote-run-links' +import { callRemoteOwnedServer, type RemoteOwnedRuntime } from './remote-owned-calls' +import { REMOTE_SERVER_UNREACHABLE_CODES } from './remote-server-unreachable' + +const STOP_TIMEOUT_MS = 60_000 +const CANCEL_TIMEOUT_MS = 120_000 +// Enough to keep one slow server from holding every other owed action back. +const RESEND_CONCURRENCY = 4 + +/** Codes that mean the server never answered, or this Orca never sent: a resend keeps its key. */ +const NO_ANSWER_CODES = new Set([ + ...REMOTE_SERVER_UNREACHABLE_CODES, + 'invalid_runtime_response', + 'peer_changed', + 'runtime_environment_changed', + 'server_required', + 'server_pairing_changed', + 'remote_link_closed' +]) + +/** Whether the server got the call and answered it, rather than this Orca never reaching it. */ +export function serverAnswered(error: unknown): boolean { + return error instanceof OrchestrationError && !NO_ANSWER_CODES.has(error.code) +} + +/** The server answers for that link's work only under the pairing it was made with; a re-pair ends it. */ +function closeOnPairingChange( + runtime: RemoteOwnedRuntime, + link: RemoteRunLinkRow, + error: unknown +): boolean { + if ( + error instanceof OrchestrationError && + (error.code === 'server_pairing_changed' || error.code === 'runtime_environment_changed') + ) { + const now = runtime.resolveOrchestrationWorkerServer(link.environment_id) + if (!remoteRunLinkPinMatches(link, remoteServerPin(now))) { + closeRemoteRunLink( + runtime.getOrchestrationDb(), + link.conversation_id, + `The pairing with ${now.name} was re-made.`, + (handle, type) => runtime.notifyMessageArrived(handle, type) + ) + return true + } + } + return false +} + +const StopReceipt = z.object({ + state: z.string(), + alreadySettled: z.boolean(), + helperStopError: z.string().optional(), + helpers: z.array(HelperStopOutcome).optional() +}) + +/** Proof a stop is done: the worker stopped or had already settled, and so did every helper, unless the user kept it open. */ +export function isRemoteStopProof(receipt: unknown): boolean { + const parsed = StopReceipt.safeParse(receipt) + return ( + parsed.success && + (parsed.data.state === 'stopped' || parsed.data.alreadySettled) && + parsed.data.helperStopError === undefined && + (parsed.data.helpers ?? []).every((helper) => + ['stopped', 'already_finished', 'kept_open'].includes(helper.outcome) + ) + ) +} + +/** + * Sends the stop owed for a remote Dispatch under its current key and returns the server's receipt. + * Only proof for the count it was sent under clears the debt; anything else leaves it owed. + */ +export async function sendOwedRemoteStop( + runtime: RemoteOwnedRuntime, + record: RemoteDispatchRow, + now: () => number = Date.now +): Promise { + const db = runtime.getOrchestrationDb() + const link = getRemoteRunLink(db, record.conversation_id) + if (!link) { + return undefined + } + try { + const receipt = await callRemoteOwnedServer(runtime, link, { + method: 'orchestration.workerStop', + params: { dispatch: record.dispatch_id }, + timeoutMs: STOP_TIMEOUT_MS, + requestId: remoteStopKey(record), + whileLink: ['open'] + }) + if (isRemoteStopProof(receipt)) { + settleRemoteDispatchStop(runtime.getOrchestrationDb(), record.dispatch_id, record.stop_count) + } else { + deferRemoteDispatchStop(runtime.getOrchestrationDb(), record, { + answered: true, + error: 'The server has not proven the stop yet.', + retryAt: remoteResendRetryAt(record.stop_retries, now()) + }) + } + return receipt + } catch (error) { + if (!closeOnPairingChange(runtime, link, error)) { + deferRemoteDispatchStop(runtime.getOrchestrationDb(), record, { + answered: serverAnswered(error), + error: error instanceof Error ? error.message : String(error), + retryAt: remoteResendRetryAt(record.stop_retries, now()) + }) + } + throw error + } +} + +/** + * Sends the cancel an A reset owes the server for one link. B closes the peer Run and runs its + * ordinary stop on each live worker; the debt ends when it answers that none remain. + */ +export async function sendOwedRemoteRunCancel( + runtime: RemoteOwnedRuntime, + link: RemoteRunLinkRow, + now: () => number = Date.now +): Promise { + if (!link.cancel_key) { + return + } + const settle = (update: { closed: boolean; answered: boolean; error: string | null }): void => { + runtime + .getOrchestrationDb() + .db.prepare( + `UPDATE remote_run_links SET + state = CASE WHEN ? THEN 'closed' ELSE state END, + cancel_attempt = CASE WHEN ? THEN cancel_attempt + 1 ELSE cancel_attempt END, + cancel_retries = cancel_retries + 1, + cancel_retry_at = CASE WHEN ? THEN NULL ELSE ? END, + last_error = ? + WHERE conversation_id = ? AND state = 'cancel_owed' AND cancel_key = ? AND cancel_attempt = ?` + ) + .run( + update.closed ? 1 : 0, + update.answered && !update.closed ? 1 : 0, + update.closed ? 1 : 0, + remoteResendRetryAt(link.cancel_retries, now()), + update.error, + link.conversation_id, + link.cancel_key, + link.cancel_attempt + ) + } + try { + const answer = PeerRunCancelResult.parse( + await callRemoteOwnedServer(runtime, link, { + method: 'orchestration.peerRunCancel', + params: {}, + timeoutMs: CANCEL_TIMEOUT_MS, + requestId: `${link.cancel_key}.${link.cancel_attempt}`, + whileLink: ['cancel_owed'] + }) + ) + settle({ + closed: answer.remaining === 0, + answered: true, + error: + answer.remaining === 0 ? null : `${answer.remaining} workers there are not proven stopped.` + }) + } catch (error) { + if (closeOnPairingChange(runtime, link, error)) { + return + } + settle({ + closed: false, + answered: serverAnswered(error), + error: error instanceof Error ? error.message : String(error) + }) + } +} + +/** Everything this Orca owes one server, resent from its pull loop until the server answers for it. */ +export async function resendOwedRemoteActions( + runtime: RemoteOwnedRuntime, + db: OrchestrationDb, + environmentId: string, + options: { now?: () => number } = {} +): Promise { + const now = options.now ?? Date.now + const due = (retryAt: number | null) => retryAt === null || retryAt <= now() + const actions: (() => Promise)[] = [ + ...listOwedRemoteStops(db, environmentId, now()).map( + (record) => () => sendOwedRemoteStop(runtime, record, now) + ), + ...listOwedRemoteRunCancels(db, environmentId) + .filter((link) => due(link.cancel_retry_at)) + .map((link) => () => sendOwedRemoteRunCancel(runtime, link, now)) + ] + await mapWithConcurrency(actions, RESEND_CONCURRENCY, (action) => action().catch(() => undefined)) +} diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-answers.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-answers.ts new file mode 100644 index 00000000000..776079f16aa --- /dev/null +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-answers.ts @@ -0,0 +1,66 @@ +import { OrchestrationError } from '../../orchestration-error' +import { serverAnswered } from './remote-owed-actions' +import type { RemoteForwardKey } from './remote-forward-caller' + +/** The server got nothing, or never answered, so whatever the call did there is unknown here. */ +export function serverNeverAnswered(error: unknown): boolean { + return !serverAnswered(error) +} + +export function errorData(error: unknown): Record | undefined { + const data = error instanceof Error && 'data' in error ? error.data : undefined + return data && typeof data === 'object' && !Array.isArray(data) + ? // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a non-array object's own fields, read as unknowns. + (data as Record) + : undefined +} + +/** What the server's answer says that this Orca says otherwise. */ +export type ServerTerms = { + server: string + forward?: RemoteForwardKey + /** The link the call went under: the server's Run for it is this Orca's Run here. */ + link?: { peer_run_id: string | null; run_id: string } +} + +/** + * The server's answer, or its error, in the caller's own terms: the caller knows its request ID, + * not the scoped key the server saw, and its own Run, not the server's; an error names the server + * it came from so recovery (`request-show --on`) asks there. + */ +export function inServerTerms(value: T, { server, forward, link }: ServerTerms): T { + const pairs: [string, string][] = [] + if (forward) { + pairs.push([forward.key, forward.requestId]) + } + if (link?.peer_run_id) { + pairs.push([link.peer_run_id, link.run_id]) + } + const swap = (item: unknown): unknown => { + if (typeof item === 'string') { + return pairs.reduce((text, [from, to]) => text.split(from).join(to), item) + } + if (Array.isArray(item)) { + return item.map(swap) + } + if (item && typeof item === 'object') { + return Object.fromEntries(Object.entries(item).map(([field, inner]) => [field, swap(inner)])) + } + return item + } + if (value instanceof Error) { + const code = 'code' in value && typeof value.code === 'string' ? value.code : 'runtime_error' + const data = Object.entries(errorData(value) ?? {}).map(([field, inner]) => [ + field, + swap(inner) + ]) + const error = new OrchestrationError(code, String(swap(value.message)), { + ...Object.fromEntries(data), + server + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: an error answer stays an error, with the same code. + return error as T + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only string contents change; every shape is kept. + return swap(value) as T +} diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-calls.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-calls.ts new file mode 100644 index 00000000000..b0e77d56562 --- /dev/null +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-calls.ts @@ -0,0 +1,99 @@ +import { createHash } from 'node:crypto' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import { OrchestrationError } from '../../orchestration-error' +import { + closeRemoteRunLink, + getRemoteRunLink, + remoteRunLinkPinMatches, + remoteServerPin, + type RemoteRunLinkRow +} from '../../db/remote-owned/remote-run-links' + +export type RemoteOwnedRuntime = Pick< + OrcaRuntimeService, + | 'getOrchestrationDb' + | 'resolveOrchestrationWorkerServer' + | 'callOrchestrationWorkerServer' + | 'readMachineName' + | 'getRuntimeId' + | 'notifyMessageArrived' +> + +/** + * Every call this Orca makes about a Run it coordinates on a paired server: as that Run's + * coordinator, only under the pairing the link was made with, and only while the link is still in + * one of `whileLink` when the request reaches the socket, so nothing leaves after a reset. + */ +export async function callRemoteOwnedServer( + runtime: RemoteOwnedRuntime, + link: RemoteRunLinkRow, + call: { + method: string + params: unknown + timeoutMs: number + requestId?: string + whileLink: readonly RemoteRunLinkRow['state'][] + } +): Promise { + const db = runtime.getOrchestrationDb() + const server = runtime.resolveOrchestrationWorkerServer(link.environment_id) + // Run again on the socket just before the frame leaves: a reset or re-pair while it waited stops it. + const requireLink = (): void => { + const current = getRemoteRunLink(db, link.conversation_id) + const now = runtime.resolveOrchestrationWorkerServer(link.environment_id) + if ( + current && + current.state !== 'closed' && + !remoteRunLinkPinMatches(current, remoteServerPin(now)) + ) { + closeRemoteRunLink( + db, + current.conversation_id, + `The pairing with ${now.name} was re-made.`, + (handle, type) => runtime.notifyMessageArrived(handle, type) + ) + throw new OrchestrationError( + 'server_pairing_changed', + `The pairing with ${now.name} was re-made, so it no longer runs Run ${link.run_id}'s workers. No effects were applied.`, + { effectsApplied: false, server: now.name } + ) + } + if (!current || !call.whileLink.includes(current.state)) { + // Only a re-made pairing closes a link; a reset leaves it owing a cancel. + const why = + current?.state === 'closed' + ? `The pairing with ${server.name} was re-made, so it no longer runs Run ${link.run_id}'s workers.` + : `Run ${link.run_id} was reset on this Orca, so nothing more goes to ${server.name} for it.` + throw new OrchestrationError('remote_link_closed', `${why} No effects were applied.`, { + effectsApplied: false + }) + } + } + requireLink() + return runtime.callOrchestrationWorkerServer( + link.environment_id, + call.method, + call.params, + call.timeoutMs, + { + ...(call.requestId ? { orchestrationRequestId: call.requestId } : {}), + orchestrationPeerRun: { + runId: link.run_id, + conversationId: link.conversation_id, + label: runtime.readMachineName() + } + }, + { + expectedEnvironmentPairingRevision: link.pairing_revision ?? undefined, + prepareRequest: (request) => { + requireLink() + return { params: request.params, envelope: request.envelope } + } + } + ) +} + +/** The server sees every caller here as one pairing, so the key is scoped to the caller first: two callers reusing an ID never collide there, and one caller retrying gets its first answer. */ +export function remoteForwardRequestId(callerNamespace: string, requestId: string): string { + return `fwd:${createHash('sha256').update(`${callerNamespace}\n${requestId}`).digest('hex').slice(0, 40)}` +} diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-reads.test.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-reads.test.ts new file mode 100644 index 00000000000..f9b71ee2c62 --- /dev/null +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-reads.test.ts @@ -0,0 +1,288 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { OrchestrationDb } from '../../db/orchestration-db' +import '../../db/contract-constants' +import '../../db/messages/mailbox-routing-page' +import '../../db/dispatch-row-writer' +import '../../db/attempt-outcome-projection' +import type { RunRow } from '../../db/orchestration-records' +import { OrcaRuntimeService } from '../../../orca-runtime' +import type { OrchestrationWorkerServer } from '../environment-transport' +import { OrchestrationError } from '../../orchestration-error' +import { + getRemoteDispatch, + oweRemoteDispatchStop, + recordRemoteDispatchReport, + recordRemoteDispatchState +} from '../../db/remote-owned/remote-dispatch-records' +import { recordRemoteStart, reserveRemotePlacement } from '../../db/remote-owned/remote-placements' +import { + closeRemoteRunLink, + noteRemoteRunLinkError, + openRemoteRunLink +} from '../../db/remote-owned/remote-run-links' +import { ORCHESTRATION_WORKER_LIST_METHOD } from '../../../rpc/methods/orchestration/worker/worker-list-method' +import { remoteWorkerShow } from './remote-owned-reads' +import { explainRemoteServerFailure } from './remote-server-unreachable' + +const SERVER: OrchestrationWorkerServer = { + environmentId: 'env_b', + name: 'devB', + peerFingerprint: 'host_b', + homePeerFingerprint: 'cred_a', + pairingRevision: 1 +} +const LAST_HEARD = '2026-11-09 08:30:00' + +describe('reads of workers a paired server runs, from this Orca’s records', () => { + let db: OrchestrationDb + let runtime: OrcaRuntimeService + let run: RunRow + + beforeEach(() => { + db = new OrchestrationDb(':memory:') + runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db) + vi.spyOn(runtime, 'resolveOrchestrationWorkerServer').mockImplementation((selector) => { + if (selector !== SERVER.environmentId) { + throw new OrchestrationError('server_not_found', `No server ${selector}.`) + } + return SERVER + }) + run = db.createRun({ + objective: 'Ship', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: null + }) + }) + + afterEach(() => { + vi.useRealTimers() + db.close() + }) + + /** A worker devB started for Task `taskId`, as devB last reported it at LAST_HEARD. */ + function remoteWorker(taskId: string, dispatchId: string, environmentId = SERVER.environmentId) { + const link = openRemoteRunLink(db, run.id, { ...SERVER, environmentId }) + reserveRemotePlacement(db, { + link, + taskId, + requestKey: `key_${taskId}`, + create: { spec: `do ${taskId}` } + }) + recordRemoteStart(db, { + conversationId: link.conversation_id, + taskId, + dispatchId, + requestKey: `key_${taskId}`, + peerRunId: 'run_on_b' + }) + recordRemoteDispatchState(db, dispatchId, { + status: 'dispatched', + worker_state: 'ready', + last_failure: null, + agent: 'claude' + }) + recordRemoteDispatchReport(db, dispatchId, 'Halfway: tests written.') + db.db.prepare('UPDATE remote_dispatches SET updated_at = ?').run(LAST_HEARD) + return getRemoteDispatch(db, dispatchId)! + } + + type ListedWorkers = { + workers: { dispatchId: string; server?: Record }[] + page: { total: number; hasMore: boolean; nextCursor: string | null } + warnings?: string[] + } + + async function listWorkers(params: Record): Promise { + const parsed = ORCHESTRATION_WORKER_LIST_METHOD.params?.parse(params) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the method returns the list shape the CLI reads. + return (await ORCHESTRATION_WORKER_LIST_METHOD.handler(parsed, { + runtime + } as never)) as ListedWorkers + } + + it('shows a remote worker in the ordinary shape, labelled with its server, record time and last report', () => { + const shown = remoteWorkerShow(runtime, remoteWorker('task_1', 'ctx_w1')) + + expect(shown).toMatchObject({ + dispatch: { id: 'ctx_w1', taskId: 'task_1', runId: run.id, status: 'dispatched' }, + worker: { dispatchId: 'ctx_w1', state: 'ready', stage: 'server_record' }, + server: { name: 'devB', asOf: '2026-11-09T08:30:00Z' }, + lastReport: 'Halfway: tests written.' + }) + expect(shown.server).not.toHaveProperty('reachable') + expect(shown.observation.reason).toBe( + "devB's state as of 2026-11-09T08:30:00Z. Its output is kept only on devB." + ) + }) + + it('adds what the pull loop last heard from the server, and says unreachable only when it knows', () => { + const record = remoteWorker('task_1', 'ctx_w1') + const now = Date.parse('2026-11-10T12:00:00Z') + vi.useFakeTimers({ toFake: ['Date'], now }) + const heard = vi.spyOn(runtime, 'getPeerServerAnswerStatus') + heard.mockReturnValue({ answeredAt: now - 12_000 }) + const live = remoteWorkerShow(runtime, record) + expect(live.server).toMatchObject({ reachable: true }) + expect(live.observation.reason).toContain('devB last answered 12 s ago.') + + heard.mockReturnValue({ answeredAt: now - 40_000, unreachableSince: now - 5_000 }) + const asleep = remoteWorkerShow(runtime, record) + expect(asleep.server).toMatchObject({ reachable: false }) + expect(asleep.observation.reason).toContain( + 'devB could not be reached; it last answered 40 s ago.' + ) + }) + + it('keeps the time devB last reported when this Orca only owes it a stop', () => { + const record = remoteWorker('task_1', 'ctx_w1') + oweRemoteDispatchStop(db, record.dispatch_id, 'intent_1') + + const shown = remoteWorkerShow(runtime, getRemoteDispatch(db, 'ctx_w1')!) + expect(shown.server.asOf).toBe('2026-11-09T08:30:00Z') + expect(shown.observation.reason).toContain('A stop is owed') + }) + + it('says a re-made pairing, not an unreachable server, left the record', async () => { + const record = remoteWorker('task_1', 'ctx_w1') + closeRemoteRunLink(db, record.conversation_id, 'The pairing with devB was re-made.') + // A later unreadable item on the closed link does not replace why it closed. + noteRemoteRunLinkError(db, record.conversation_id, new Error('Queue item x was not imported.')) + + const shown = remoteWorkerShow(runtime, record) + expect(shown.server).toMatchObject({ name: 'devB', repaired: true }) + expect(shown.observation.reason).toContain('The pairing with devB was re-made') + const listed = await listWorkers({ run: run.id, paginate: true }) + expect(listed.workers).toEqual([ + expect.objectContaining({ + dispatchId: 'ctx_w1', + server: expect.objectContaining({ name: 'devB', repaired: true }) + }) + ]) + }) + + it('keeps remote rows within the page limit and counts the rest in the total', async () => { + remoteWorker('task_1', 'ctx_w1') + remoteWorker('task_2', 'ctx_w2') + + const page = await listWorkers({ run: run.id, paginate: true, limit: 1 }) + expect(page.workers.map((worker) => worker.dispatchId)).toEqual(['ctx_w2']) + expect(page.page).toMatchObject({ total: 2 }) + expect(page.warnings).toEqual(['Showing the newest 1 of 2 workers on paired servers.']) + }) + + it('names a server removed since by the name it had, and says it was removed', () => { + const record = remoteWorker('task_1', 'ctx_w1', 'env_gone') + closeRemoteRunLink( + db, + record.conversation_id, + "devB was removed from this Orca's paired servers." + ) + + const shown = remoteWorkerShow(runtime, record) + expect(shown.server.name).toBe('devB') + expect(shown.observation.reason).toBe( + "devB was removed from this Orca's paired servers. It no longer reports this worker here; this is devB's state as of 2026-11-09T08:30:00Z. Its output is kept only on devB." + ) + }) + + it('lists remote workers on the first page beside local ones, named by their server, and nowhere else', async () => { + remoteWorker('task_1', 'ctx_w1') + remoteWorker('task_2', 'ctx_w2') + + const first = await listWorkers({ run: run.id, paginate: true }) + expect(first.workers.map((worker) => worker.dispatchId)).toEqual(['ctx_w2', 'ctx_w1']) + expect(first.page).toMatchObject({ total: 2, hasMore: false }) + expect(first.workers[0]).toMatchObject({ + dispatchId: 'ctx_w2', + workerState: 'ready', + server: { name: 'devB', asOf: '2026-11-09T08:30:00Z' } + }) + + // A later page follows this Orca's own cursor and repeats none of them. + for (let index = 0; index < 101; index += 1) { + const task = db.createTask({ spec: `local ${index}`, runId: run.id }) + db.db + .prepare( + `INSERT INTO dispatch_contexts (id, run_id, task_id, assignee_handle, status, created_at) + VALUES (?, ?, ?, ?, 'dispatched', '2026-11-01 00:00:00')` + ) + .run(`ctx_local_${String(index).padStart(3, '0')}`, run.id, task.id, `term_${index}`) + } + const mixed = await listWorkers({ run: run.id, paginate: true }) + expect(mixed.workers).toHaveLength(102) + expect(mixed.workers.slice(-2).map((worker) => worker.dispatchId)).toEqual(['ctx_w2', 'ctx_w1']) + expect(mixed.page).toMatchObject({ total: 103, hasMore: true }) + const next = await listWorkers({ run: run.id, paginate: true, cursor: mixed.page?.nextCursor }) + expect(next.page).toMatchObject({ total: 103 }) + expect(next.workers.map((worker) => worker.dispatchId)).toEqual([ + expect.stringMatching(/^ctx_local_/) + ]) + + // Only devB knows their terminals; another Run's list has none of them. + const filtered = await listWorkers({ run: run.id, paginate: true, terminalState: 'retained' }) + expect(filtered.workers.map((worker) => worker.dispatchId)).not.toContain('ctx_w1') + expect(filtered.page).toMatchObject({ total: 101 }) + const other = db.createRun({ + objective: 'Other', + coordinatorHandle: 'term_other', + coordinatorPaneKey: null + }) + expect((await listWorkers({ run: other.id, paginate: true })).workers).toEqual([]) + }) + + it('says a server that never answered cannot confirm a change, and passes its own unknown outcome through', () => { + const offline = new OrchestrationError( + 'remote_runtime_unavailable', + 'Could not connect to the remote Orca runtime.' + ) + const change = explainRemoteServerFailure(offline, { + server: 'devB', + method: 'orchestration.workerRelease', + params: { dispatch: 'ctx_w1' }, + dispatchId: 'ctx_w1' + }) + expect(change).toMatchObject({ + code: 'remote_runtime_unavailable', + data: { server: 'devB', reachable: false } + }) + expect(change).toHaveProperty( + 'message', + expect.stringContaining( + 'devB did not answer (Could not connect to the remote Orca runtime.), so this Orca cannot tell whether the command reached it.' + ) + ) + expect(change).toHaveProperty( + 'message', + expect.stringContaining('Retry only with the same request ID (--retry-request)') + ) + + const read = explainRemoteServerFailure( + new OrchestrationError('runtime_timeout', 'Timed out.'), + { + server: 'devB', + method: 'orchestration.workerRead', + params: { dispatch: 'ctx_w1' }, + dispatchId: 'ctx_w1' + } + ) + expect(read).toMatchObject({ code: 'runtime_timeout' }) + expect(read).toHaveProperty( + 'message', + expect.stringContaining('devB could not be reached (Timed out.)') + ) + expect(read).toHaveProperty( + 'message', + expect.stringContaining('its output is kept only on devB') + ) + + const unknown = new OrchestrationError('operation_unknown', 'The stop is still pending.') + expect( + explainRemoteServerFailure(unknown, { + server: 'devB', + method: 'orchestration.workerStop', + params: { dispatch: 'ctx_w1' } + }) + ).toBe(unknown) + }) +}) diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-reads.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-reads.ts new file mode 100644 index 00000000000..9737a034207 --- /dev/null +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-reads.ts @@ -0,0 +1,201 @@ +import type { OrcaRuntimeService } from '../../../orca-runtime' +import { exposeUtcTimestamp } from '../../db/utc-timestamp' +import { + countRemoteDispatches, + listRemoteDispatches, + type RemoteDispatchRow +} from '../../db/remote-owned/remote-dispatch-records' +import { getRemoteRunLink } from '../../db/remote-owned/remote-run-links' +import type { PeerServerAnswerStatus } from '../peer-mail/peer-mail-relay' + +type ReadsRuntime = Pick< + OrcaRuntimeService, + 'getOrchestrationDb' | 'resolveOrchestrationWorkerServer' | 'getPeerServerAnswerStatus' +> + +/** + * A remote worker's server as this Orca names it. `asOf` is when this Orca recorded the server's + * latest state for the worker; `repaired` means the pairing was re-made since, so the server no + * longer reports this worker here. + */ +export type RemoteWorkerServer = { + environmentId: string + name: string + asOf: string + repaired?: true +} + +function remoteWorkerServer( + record: RemoteDispatchRow, + linkState: string | null | undefined, + name: (environmentId: string) => string +): RemoteWorkerServer { + return { + environmentId: record.environment_id, + name: name(record.environment_id), + asOf: exposeUtcTimestamp(record.updated_at) ?? record.updated_at, + ...(linkState === 'closed' ? { repaired: true as const } : {}) + } +} + +/** The paired server's name; one removed from this Orca since keeps the name a link recorded, else its environment ID. */ +export function remoteServerName( + runtime: ReadsRuntime, + environmentId: string, + recorded?: string | null +): string { + try { + return runtime.resolveOrchestrationWorkerServer(environmentId).name + } catch { + return recorded ?? environmentId + } +} + +/** + * worker-show for a worker a paired server runs: always this Orca's record, never a call there, so + * it answers at once whether the server is awake, asleep or off, and agrees with worker-list. The + * note says when the record is from and what the pull loop last heard from the server. Metadata + * only: the worker's output stays on its server (worker-read), and a prompt wait arrives as mail. + */ +export function remoteWorkerShow(runtime: ReadsRuntime, record: RemoteDispatchRow) { + const link = getRemoteRunLink(runtime.getOrchestrationDb(), record.conversation_id) + const server = remoteWorkerServer(record, link?.state, (id) => + remoteServerName(runtime, id, link?.server_name) + ) + const heard = server.repaired + ? undefined + : runtime.getPeerServerAnswerStatus(record.environment_id) + const reachable = heard?.unreachableSince ? false : heard?.answeredAt ? true : undefined + const closedBecause = link?.state === 'closed' ? link.last_error : null + const owedStop = record.stop_owed + ? ` A stop is owed; this Orca sends it when ${server.name} answers.` + : '' + return { + dispatch: { + id: record.dispatch_id, + runId: record.run_id, + taskId: record.task_id, + task_id: record.task_id, + status: record.status, + lastFailure: record.last_failure, + followUpOf: null + }, + worker: { + dispatchId: record.dispatch_id, + state: record.worker_state ?? record.status, + stage: 'server_record', + agentTerminalHandle: null, + worktreeId: null, + lastError: record.last_failure, + updatedAt: server.asOf + }, + projection: null, + terminal: null, + terminalResource: null, + observation: { + status: 'unverifiable' as const, + exactWorker: false, + reason: `${recordNote(server, heard, closedBecause)} Its output is kept only on ${server.name}.${owedStop}` + }, + server: { + ...server, + ...(reachable === undefined ? {} : { reachable }), + ...(heard?.answeredAt ? { lastAnsweredAt: new Date(heard.answeredAt).toISOString() } : {}) + }, + lastReport: record.last_report, + autoReleaseAt: null + } +} + +function recordNote( + server: RemoteWorkerServer, + heard: PeerServerAnswerStatus | undefined, + closedBecause: string | null +): string { + if (server.repaired) { + // Why the link closed (a re-made pairing, or the server removed), as recorded when it closed. + const why = closedBecause ?? `The pairing with ${server.name} was re-made.` + return `${why} It no longer reports this worker here; this is ${server.name}'s state as of ${server.asOf}.` + } + const state = `${server.name}'s state as of ${server.asOf}.` + const ago = heard?.answeredAt + ? `${Math.max(0, Math.round((Date.now() - heard.answeredAt) / 1000))} s ago` + : undefined + if (heard?.unreachableSince) { + return `${state} ${server.name} could not be reached${ago ? `; it last answered ${ago}` : ''}.` + } + return ago ? `${state} ${server.name} last answered ${ago}.` : state +} + +export type RemoteWorkerListRow = ReturnType + +function remoteWorkerListRow( + record: ReturnType[number], + name: (environmentId: string) => string +) { + return { + dispatchId: record.dispatch_id, + taskId: record.task_id, + runId: record.run_id, + workerState: record.worker_state ?? record.status, + dispatchStatus: record.status, + agentTerminalHandle: null, + terminalState: null, + resource: null, + server: remoteWorkerServer(record, record.link_state, name) + } +} + +type WorkerListPage = { + workers: readonly unknown[] + page: { total: number } + warnings?: string[] +} + +/** + * Workers paired servers run for the listed Runs join the first page after this Orca's own, newest + * first, at most `maxRows` of them and as each server last reported them; no server is asked. So + * the first page can hold up to twice its limit, and nothing is pushed past it. Every page's `total` counts + * them. Later pages follow this Orca's own cursor, and a terminal-state filter leaves them out, + * since only their server knows their terminals. + */ +export function withRemoteWorkerRows( + runtime: ReadsRuntime, + params: { run?: string; cursor?: string; terminalState?: string }, + page: Page, + maxRows: number +): Page { + if (params.terminalState) { + return page + } + const db = runtime.getOrchestrationDb() + const total = countRemoteDispatches(db, params.run) + if (total === 0) { + return page + } + if (params.cursor) { + return { ...page, page: { ...page.page, total: page.page.total + total } } + } + const names = new Map() + const name = (id: string): string => { + const known = names.get(id) ?? remoteServerName(runtime, id) + names.set(id, known) + return known + } + const rows = listRemoteDispatches(db, { runId: params.run, limit: Math.max(0, maxRows) }).map( + (record) => remoteWorkerListRow(record, name) + ) + const warnings = + rows.length < total + ? [ + ...(page.warnings ?? []), + `Showing the newest ${rows.length} of ${total} workers on paired servers.` + ] + : page.warnings + return { + ...page, + workers: [...page.workers, ...rows], + page: { ...page.page, total: page.page.total + total }, + ...(warnings ? { warnings } : {}) + } +} diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-route.test.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-route.test.ts new file mode 100644 index 00000000000..a15e147cd5f --- /dev/null +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-route.test.ts @@ -0,0 +1,890 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY, + ORCHESTRATION_CONTRACT_VERSION, + ORCHESTRATION_REMOTE_OWNED_WORKERS_RUNTIME_CAPABILITY +} from '../../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { + RuntimeOrchestrationEnvelope, + RuntimeRpcResponse +} from '../../../../../shared/runtime-rpc-envelope' +import { WorkerStartParams } from '../../../../../shared/rpc-contract/orchestration-worker-start-params' +import { OrcaRuntimeService } from '../../../orca-runtime' +import { RpcDispatcher } from '../../../rpc/dispatcher' +import type { RpcResponse } from '../../../rpc/core' +import { ORCHESTRATION_METHODS } from '../../../rpc/methods/orchestration/orchestration' +import { OrchestrationDb } from '../../db/orchestration-db' +import { getRemoteDispatch } from '../../db/remote-owned/remote-dispatch-records' +import { importRemoteOwnedItem } from '../../db/remote-owned/remote-owned-import' +import { getRemotePlacement } from '../../db/remote-owned/remote-placements' +import { + closeRemoteRunLink, + OWE_REMOTE_RUN_CANCELS_SQL, + remoteServerPin +} from '../../db/remote-owned/remote-run-links' +import type { + OrchestrationEnvironmentTransport, + OrchestrationWorkerServer +} from '../environment-transport' + +const COORDINATOR_PANE = 'tab_coord:11111111-1111-4111-8111-111111111111' +const OTHER_PANE = 'tab_other:22222222-2222-4222-8222-222222222222' +const REQUEST = '6f1c2f1e-3a7b-4d55-9c1e-0a1b2c3d4e5f' + +type Sent = { + method: string + params: Record + envelope?: RuntimeOrchestrationEnvelope +} +type Answer = { result: unknown } | { error: string; data?: unknown } | 'unreachable' + +function record(value: unknown): Record { + return value && typeof value === 'object' ? { ...value } : {} +} + +describe('commands about a worker a paired server owns', () => { + let db: OrchestrationDb + let runtime: OrcaRuntimeService + let dispatcher: RpcDispatcher + let sent: Sent[] + let answers: Record + let capabilities: string[] + let whileSending: () => Promise + let sleeping: boolean + let pulls: unknown[][] + let paired: boolean + let pullFailures: number + let sequence = 0 + const DEV_B: OrchestrationWorkerServer = { + environmentId: 'env_b', + name: 'devB', + peerFingerprint: 'host_b', + homePeerFingerprint: 'cred_a', + pairingRevision: 1 + } + let server = DEV_B + + const transport = (): OrchestrationEnvironmentTransport => ({ + resolve: () => server, + hasEnvironment: () => paired, + call: async (_selector, method, params, timeoutMs, envelope, _revision, send) => { + const ok = (result: unknown): RuntimeRpcResponse => ({ + id: method, + ok: true, + result, + _meta: { runtimeId: 'runtime_b' } + }) + if (!paired) { + throw new Error('Unknown environment: env_b') + } + if (sleeping) { + // A sleeping laptop keeps its socket open, so only each call's own timeout ends the wait. + return new Promise((_, reject) => + setTimeout( + () => + reject( + Object.assign(new Error('The remote Orca runtime timed out.'), { + code: 'runtime_timeout' + }) + ), + timeoutMs + ) + ) + } + if (method === 'status.get') { + return ok({ runtimeId: 'runtime_b', capabilities }) + } + if (method === 'orchestration.peerMailPull') { + if (pullFailures > 0) { + pullFailures -= 1 + throw Object.assign(new Error('Could not connect to the remote Orca runtime.'), { + code: 'remote_runtime_unavailable' + }) + } + const items = pulls.shift() + if (!items) { + // A real pull waits there for mail; yielding keeps the loop from starving timers. + await new Promise((resolve) => setImmediate(resolve)) + } + return ok({ items: items ?? [] }) + } + if (method === 'orchestration.peerMailAck') { + return ok({}) + } + const prepared = send?.prepareRequest?.({ params, envelope, measure: () => 0 }) + sent.push({ + method, + params: record(prepared?.params ?? params), + envelope: prepared?.envelope ?? envelope + }) + await whileSending() + const answer = answers[method]?.shift() ?? 'unreachable' + if (answer === 'unreachable') { + throw Object.assign(new Error('Could not connect to the remote Orca runtime.'), { + code: 'remote_runtime_unavailable' + }) + } + return 'result' in answer + ? ok(answer.result) + : { + id: method, + ok: false, + error: { code: answer.error, message: answer.error, data: answer.data } + } + } + }) + + beforeEach(() => { + server = { ...DEV_B } + sent = [] + answers = {} + whileSending = async () => undefined + sleeping = false + pulls = [] + paired = true + pullFailures = 0 + capabilities = [ + ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY, + ORCHESTRATION_REMOTE_OWNED_WORKERS_RUNTIME_CAPABILITY + ] + db = new OrchestrationDb(':memory:') + runtime = new OrcaRuntimeService(null, undefined, { + orchestrationEnvironmentTransport: transport() + }) + vi.spyOn(runtime, 'readMachineName').mockReturnValue('Mac A') + const panes: Record = { term_coord: COORDINATOR_PANE, term_other: OTHER_PANE } + vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => panes[handle] ?? null) + vi.spyOn(runtime, 'getLiveTerminalPaneKey').mockImplementation( + (handle) => panes[handle] ?? null + ) + runtime.setOrchestrationDb(db) + dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) + }) + + afterEach(() => { + vi.useRealTimers() + runtime.stopOrchestrationFederationRelay() + db.close() + vi.restoreAllMocks() + }) + + function call( + method: string, + params: Record, + { pane = COORDINATOR_PANE, requestId }: { pane?: string; requestId?: string } = {} + ): Promise { + sequence += 1 + return dispatcher.dispatch({ + id: `call_${sequence}`, + authToken: 'token', + method, + params, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationCompatibilityEvidence: { paneKey: pane }, + ...(requestId ? { orchestrationRequestId: requestId } : {}) + }) + } + + const started = (dispatchId = 'ctx_b1'): Answer => ({ + result: { dispatchId, runId: 'run_on_b', run: { id: 'run_on_b' }, state: 'ready' } + }) + + async function startOnB(requestId = REQUEST) { + answers['orchestration.workerStart'] = [started()] + const response = await call( + 'orchestration.workerStart', + { from: 'term_coord', on: 'devB', spec: 'build it', worktree: 'new-top-level' }, + { requestId } + ) + if (!response.ok) { + throw new Error(response.error.message) + } + const receipt = record(response.result) + return { + taskId: String(receipt.taskId), + runId: String(receipt.runId), + dispatchId: String(receipt.dispatchId) + } + } + + it("starts the worker on a server that owns its workers, then records it under this Orca's Task", async () => { + const receipt = await startOnB() + + const start = sent.find((s) => s.method === 'orchestration.workerStart')! + expect(start.params).toMatchObject({ spec: 'build it', adoptTaskId: receipt.taskId }) + expect(start.params).not.toHaveProperty('from') + expect(start.envelope?.orchestrationPeerRun?.label).toBe('Mac A') + expect(receipt.runId).not.toBe('run_on_b') + expect(db.getTask(receipt.taskId)).toMatchObject({ + run_id: receipt.runId, + status: 'dispatched' + }) + expect(getRemoteDispatch(db, 'ctx_b1')).toMatchObject({ task_id: receipt.taskId }) + }) + + it("keeps today's remote attachment for a server without the capability", async () => { + capabilities = [ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY] + await call( + 'orchestration.workerStart', + { from: 'term_coord', on: 'devB', spec: 'build it', worktree: 'new-top-level' }, + { requestId: REQUEST } + ) + + expect(sent.some((s) => s.method === 'orchestration.workerStart')).toBe(false) + expect(db.db.prepare('SELECT COUNT(*) AS n FROM remote_placements').get()).toEqual({ n: 0 }) + }) + + it('fails the Task when the server refuses the start, and keeps it fenced when the answer is lost', async () => { + answers['orchestration.workerStart'] = [ + { error: 'invalid_argument', data: { effectsApplied: false } } + ] + let dependent: string | undefined + whileSending = async () => { + // Another caller lists the reserved Task and depends on it while its start waits. + const reserved = db.getTask(String(sent[0].params.adoptTaskId))! + dependent = db.createTask({ + spec: 'after it', + deps: [reserved.id], + runId: reserved.run_id + }).id + } + await call( + 'orchestration.workerStart', + { from: 'term_coord', on: 'devB', spec: 'refused', worktree: 'current' }, + { requestId: REQUEST } + ) + whileSending = async () => undefined + const refusedTask = String(sent[0].params.adoptTaskId) + expect(getRemotePlacement(db, refusedTask)).toBeUndefined() + // As a local start that fails after creating its Task leaves it failed, so its dependent keeps it. + expect(db.getTask(refusedTask)?.status).toBe('failed') + expect(db.getTask(dependent!)?.deps).toContain(refusedTask) + + const lost = await call( + 'orchestration.workerStart', + { from: 'term_coord', on: 'devB', spec: 'lost', worktree: 'new-top-level' }, + { requestId: 'a3f1e9d2-5b6c-4d7e-8f90-1a2b3c4d5e6f' } + ) + expect(lost.ok ? undefined : lost.error.code).toBe('remote_runtime_unavailable') + const lostTask = String(sent[1].params.adoptTaskId) + expect(getRemotePlacement(db, lostTask)).toMatchObject({ state: 'reserved' }) + }) + + it("adopts a start whose answer was lost from the server's queue item alone", async () => { + const lost = await call( + 'orchestration.workerStart', + { from: 'term_coord', on: 'devB', spec: 'lost', worktree: 'new-top-level' }, + { requestId: REQUEST } + ) + expect(lost.ok ? undefined : lost.error.code).toBe('remote_runtime_unavailable') + const start = sent.find((s) => s.method === 'orchestration.workerStart')! + const taskId = String(start.params.adoptTaskId) + const link = record(db.db.prepare('SELECT * FROM remote_run_links').get()) + // The server's insert trigger queued the Dispatch it created; nothing answers a lookup. + pulls.push([ + { + conversationId: link.conversation_id, + sequence: 1, + messageId: 'state_1', + kind: 'worker_state', + payload: JSON.stringify({ + v: 1, + id: 'state_1', + homeRunId: link.run_id, + peerRunId: 'run_on_b', + dispatch: { + id: 'ctx_lost', + taskId, + status: 'pending', + workerState: 'starting', + lastFailure: null, + agent: 'claude' + }, + task: { status: 'dispatched', result: null }, + correctedUnobservedPrompt: false, + removed: null + }) + } + ]) + runtime.ensureOrchestrationFederationRelay(String(link.run_id)) + + await vi.waitFor(() => + expect(getRemotePlacement(db, taskId)).toMatchObject({ + state: 'accepted', + dispatch_id: 'ctx_lost' + }) + ) + expect(sent.map((s) => s.method)).not.toContain('orchestration.dispatchShow') + }) + + it('keeps a lost start reserved for the queue, and never asks the server about it', async () => { + const now = Date.parse('2026-11-10T12:00:00Z') + vi.useFakeTimers({ toFake: ['Date'], now }) + await call( + 'orchestration.workerStart', + { from: 'term_coord', on: 'devB', spec: 'lost', worktree: 'new-top-level' }, + { requestId: REQUEST } + ) + const taskId = String( + sent.find((s) => s.method === 'orchestration.workerStart')?.params.adoptTaskId + ) + // Well past any interval a lookup would wait, with the pull loop still going round. + vi.setSystemTime(now + 120_000) + await vi.waitFor(() => + expect(runtime.getPeerServerAnswerStatus('env_b')?.answeredAt).toBeGreaterThan(now + 60_000) + ) + + expect(sent.map((s) => s.method)).not.toContain('orchestration.dispatchShow') + expect(getRemotePlacement(db, taskId)).toMatchObject({ state: 'reserved' }) + }) + + it('records nothing for a start the server answers after the Run was reset, and says so', async () => { + whileSending = async () => { + db.resetTasks() + } + answers['orchestration.workerStart'] = [started()] + const response = await call( + 'orchestration.workerStart', + { from: 'term_coord', on: 'devB', spec: 'late', worktree: 'new-top-level' }, + { requestId: REQUEST } + ) + + expect(response.ok ? undefined : response.error.code).toBe('run_not_found') + expect(getRemoteDispatch(db, 'ctx_b1')).toBeUndefined() + }) + + it('keeps the start fenced when the server says its outcome is unknown', async () => { + answers['orchestration.workerStart'] = [{ error: 'operation_unknown' }] + await call( + 'orchestration.workerStart', + { from: 'term_coord', on: 'devB', spec: 'unknown', worktree: 'new-top-level' }, + { requestId: REQUEST } + ) + + const task = String(sent[0].params.adoptTaskId) + expect(getRemotePlacement(db, task)).toMatchObject({ state: 'reserved' }) + }) + + it('never sends a start that names a remote Dispatch to retry without --on', async () => { + const receipt = await startOnB() + const retry = await call('orchestration.workerStart', { + from: 'term_coord', + task: receipt.taskId, + retryOf: 'ctx_b1', + agent: 'claude' + }) + + expect(retry.ok).toBe(false) + expect(sent.filter((s) => s.method === 'orchestration.workerStart')).toHaveLength(1) + }) + + it("retries a failed remote worker with --on as the server's ordinary retry of its Task", async () => { + const receipt = await startOnB() + importState(receipt.runId, receipt.taskId, 1, { + status: 'failed', + workerState: 'failed', + taskStatus: 'failed' + }) + answers['orchestration.workerStart'] = [started('ctx_b2')] + + const retry = await call('orchestration.workerStart', { + from: 'term_coord', + on: 'devB', + task: receipt.taskId, + retryOf: 'ctx_b1', + worktree: 'new-top-level' + }) + + expect(retry.ok ? null : retry.error).toBeNull() + const forwarded = sent.findLast((s) => s.method === 'orchestration.workerStart')! + // The server binds --from to the pairing's address at admission. + const onServer = WorkerStartParams.safeParse({ ...forwarded.params, from: 'peer' }) + expect(onServer.error?.issues).toBeUndefined() + expect(forwarded.params).toMatchObject({ task: receipt.taskId, retryOf: 'ctx_b1' }) + }) + + it('fails the Task when the pairing is re-made while its start waits', async () => { + whileSending = async () => { + server.pairingRevision = 2 + closeRemoteRunLink( + db, + String( + record(db.db.prepare('SELECT conversation_id FROM remote_run_links').get()) + .conversation_id + ), + 're-paired' + ) + } + answers['orchestration.workerStart'] = [started()] + const response = await call( + 'orchestration.workerStart', + { from: 'term_coord', on: 'devB', spec: 'repaired', worktree: 'new-top-level' }, + { requestId: REQUEST } + ) + + expect(response.ok).toBe(false) + const taskId = String(sent[0].params.adoptTaskId) + expect(db.getTask(taskId)?.status).toBe('failed') + // Kept, so a later start of this Task there is refused here rather than by the server. + expect(getRemotePlacement(db, taskId)).toMatchObject({ task_id: taskId }) + }) + + it("shows this Orca's record of a worker whose pairing was re-made", async () => { + await startOnB() + closeRemoteRunLink( + db, + String( + record(db.db.prepare('SELECT conversation_id FROM remote_run_links').get()).conversation_id + ), + 're-paired' + ) + const show = await call('orchestration.workerShow', { dispatch: 'ctx_b1' }) + + expect(show.ok ? record(show.result).server : undefined).toMatchObject({ name: 'devB' }) + }) + + it("shows a remote worker from this Orca's record without calling its server", async () => { + const { runId } = await startOnB() + // devB is live and would say something newer; show still reads the record list reads. + answers['orchestration.workerShow'] = [ + { result: { worker: { dispatchId: 'ctx_b1', state: 'running', stage: 'working' } } } + ] + await vi.waitFor(() => expect(runtime.getPeerServerAnswerStatus('env_b')).toBeDefined()) + const calls = sent.length + const show = await call('orchestration.workerShow', { dispatch: 'ctx_b1' }) + const list = await call('orchestration.workerList', { run: runId, paginate: true }) + + expect(sent.slice(calls).map((s) => s.method)).not.toContain('orchestration.workerShow') + // What the pull loop last heard from devB, which answers its pulls. + expect(record(record(show.ok ? show.result : undefined).server).reachable).toBe(true) + const shown = record(show.ok ? show.result : undefined) + const workers = record(list.ok ? list.result : undefined).workers + const listed = (Array.isArray(workers) ? workers : []) + .map(record) + .find((worker) => worker.dispatchId === 'ctx_b1') + expect({ + state: record(shown.worker).state, + asOf: record(shown.server).asOf + }).toEqual({ state: listed?.workerState, asOf: record(listed?.server).asOf }) + }) + + it("gives up a worker-read within seconds when the server sleeps, in the server's terms", async () => { + await startOnB() + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + sleeping = true + let read: RpcResponse | undefined + void call('orchestration.workerRead', { dispatch: 'ctx_b1' }).then((answer) => { + read = answer + }) + await vi.advanceTimersByTimeAsync(10_000) + vi.useRealTimers() + + expect(read?.ok ? undefined : read?.error.code).toBe('runtime_timeout') + }) + + it('scopes the retry key to the caller: two terminals reusing an ID never collide, one retrying gets its own key', async () => { + const receipt = await startOnB() + answers['orchestration.workerRelease'] = [ + { result: { state: 'released' } }, + { result: { state: 'released' } }, + { result: { state: 'released' } } + ] + const release = (pane: string) => + call('orchestration.workerRelease', { dispatch: 'ctx_b1' }, { pane, requestId: REQUEST }) + await release(COORDINATOR_PANE) + await release(COORDINATOR_PANE) + await release(OTHER_PANE) + + const keys = sent + .filter((s) => s.method === 'orchestration.workerRelease') + .map((s) => s.envelope?.orchestrationRequestId) + expect(keys[0]).toBe(keys[1]) + expect(keys[2]).not.toBe(keys[0]) + expect(keys[0]).not.toBe(REQUEST) + expect(receipt.dispatchId).toBe('ctx_b1') + }) + + it("answers in the caller's terms: its own request ID and its own Run, never the server's", async () => { + const receipt = await startOnB() + const key = () => + sent.findLast((s) => s.method === 'orchestration.workerRelease')?.envelope + ?.orchestrationRequestId + answers['orchestration.workerRelease'] = [{ result: { state: 'released' } }] + await call('orchestration.workerRelease', { dispatch: 'ctx_b1' }, { requestId: REQUEST }) + answers['orchestration.workerRelease'] = [ + { + error: 'operation_unknown', + data: { requestId: key(), runId: 'run_on_b' } + } + ] + const unknown = await call( + 'orchestration.workerRelease', + { dispatch: 'ctx_b1' }, + { requestId: REQUEST } + ) + + expect(unknown.ok ? undefined : unknown.error.data).toMatchObject({ + requestId: REQUEST, + runId: receipt.runId, + server: 'devB' + }) + }) + + it("answers a remote worker's question only from its Run's coordinator, as a local one is", async () => { + const receipt = await startOnB() + const link = record(db.db.prepare('SELECT conversation_id FROM remote_run_links').get()) + importRemoteOwnedItem(db, remoteServerPin(server), { + conversationId: String(link.conversation_id), + sequence: 1, + messageId: 'msg_q1', + kind: 'worker_mail', + payload: JSON.stringify({ + v: 1, + id: 'msg_q1', + homeRunId: receipt.runId, + peerRunId: 'run_on_b', + message: { + from: 'term_w', + type: 'question', + subject: 'Which color?', + body: 'Which color?', + payload: null, + priority: 'normal', + threadId: null + }, + dispatchId: 'ctx_b1', + taskId: receipt.taskId + }) + }) + answers['orchestration.reply'] = [{ result: { messageId: 'msg_a1' } }] + + const stranger = await call( + 'orchestration.reply', + { id: 'msg_q1', body: 'red', from: 'term_other' }, + { pane: OTHER_PANE } + ) + const coordinator = await call('orchestration.reply', { + id: 'msg_q1', + body: 'teal', + from: 'term_coord' + }) + + expect(stranger.ok).toBe(false) + expect(coordinator.ok).toBe(true) + expect( + sent.filter((s) => s.method === 'orchestration.reply').map((s) => s.params.body) + ).toEqual(['teal']) + }) + + it('owes a stop the server did not answer and says so', async () => { + await startOnB() + const stop = await call('orchestration.workerStop', { dispatch: 'ctx_b1' }) + + expect(stop.ok ? stop.result : undefined).toMatchObject({ state: 'stop_requested' }) + expect(getRemoteDispatch(db, 'ctx_b1')).toMatchObject({ stop_owed: 1 }) + }) + + it("updates this Orca's own Task here by the local rule, and never sends the update to its server", async () => { + const { taskId, runId } = await startOnB() + importState(runId, taskId, 1, { + status: 'dispatched', + workerState: 'ready', + taskStatus: 'dispatched' + }) + + const held = await call('orchestration.taskUpdate', { + id: taskId, + status: 'completed', + result: 'by hand', + callerTerminalHandle: 'term_coord' + }) + expect(held.ok ? undefined : held.error.message).toContain( + `Task ${taskId} cannot move to completed while supervised Dispatch ctx_b1 is active` + ) + + await call('orchestration.workerStop', { dispatch: 'ctx_b1' }) + const updated = await call('orchestration.taskUpdate', { + id: taskId, + status: 'failed', + result: 'given up', + callerTerminalHandle: 'term_coord' + }) + expect(updated.ok).toBe(true) + expect(db.getTask(taskId)?.status).toBe('failed') + expect(sent.map((s) => s.method)).not.toContain('orchestration.taskUpdate') + }) + + it('fails the Task a worker held when its pairing is re-made, with the reason', async () => { + const { taskId, runId } = await startOnB() + server = { ...server, homePeerFingerprint: 'cred_a_new', pairingRevision: 2 } + + await call('orchestration.workerRead', { dispatch: 'ctx_b1' }) + expect(db.getTask(taskId)).toMatchObject({ + status: 'failed', + result: 'The pairing with devB was re-made. Its worker may still run there.' + }) + // As a local worker's failure, the Run's coordinator is told. + expect( + db.db + .prepare(`SELECT type, body FROM messages WHERE to_handle = ? AND type = 'escalation'`) + .get(`run:${runId}`) + ).toMatchObject({ body: expect.stringContaining('The pairing with devB was re-made.') }) + }) + + it('fails the Task a worker held when its pairing is re-made, with no call through its link', async () => { + const { taskId, runId } = await startOnB() + runtime.ensureOrchestrationFederationRelay(runId) + server = { ...server, homePeerFingerprint: 'cred_a_new', pairingRevision: 2 } + + await vi.waitFor(() => + expect(db.getTask(taskId)).toMatchObject({ + status: 'failed', + result: 'The pairing with devB was re-made. Its worker may still run there.' + }) + ) + }) + + it('refuses here to start a Task placed through an earlier pairing, and a new Task starts there', async () => { + const { taskId } = await startOnB() + server = { ...server, homePeerFingerprint: 'cred_a_new', pairingRevision: 2 } + await call('orchestration.workerRead', { dispatch: 'ctx_b1' }) + await call('orchestration.taskUpdate', { + id: taskId, + status: 'ready', + callerTerminalHandle: 'term_coord' + }) + const startsBefore = sent.filter((s) => s.method === 'orchestration.workerStart').length + + answers['orchestration.workerStart'] = [started('ctx_b2')] + const again = await call('orchestration.workerStart', { + from: 'term_coord', + on: 'devB', + task: taskId, + worktree: 'new-top-level' + }) + expect(again.ok ? undefined : again.error.message).toBe( + `Task ${taskId} was placed through a pairing with devB that was re-made or removed; create a new task to run it there. No effects were applied.` + ) + expect(sent.filter((s) => s.method === 'orchestration.workerStart')).toHaveLength(startsBefore) + + const fresh = await call('orchestration.workerStart', { + from: 'term_coord', + on: 'devB', + spec: 'build it again', + worktree: 'new-top-level' + }) + expect(fresh.ok ? undefined : fresh.error.message).toBeUndefined() + // Only that server is refused: the same Task starts on another one as it does today. + server = { ...server, environmentId: 'env_c', name: 'devC', peerFingerprint: 'host_c' } + answers['orchestration.workerStart'] = [started('ctx_c1')] + const elsewhere = await call('orchestration.workerStart', { + from: 'term_coord', + on: 'devC', + task: taskId, + worktree: 'new-top-level' + }) + expect(elsewhere.ok ? undefined : elsewhere.error.message).toBeUndefined() + }) + + it('says plainly that a re-pair ended the listing of its Run on the server', async () => { + const { runId, taskId } = await startOnB() + server = { ...server, homePeerFingerprint: 'cred_a_new', pairingRevision: 2 } + await call('orchestration.workerRead', { dispatch: 'ctx_b1' }) + await call('orchestration.workerStart', { from: 'term_coord', on: 'devB', task: taskId }) // refused, writes no link + const listed = await call('orchestration.workerList', { on: 'devB', run: runId }) + expect(listed.ok ? undefined : listed.error.code).toBe('server_pairing_changed') + expect(listed.ok ? undefined : listed.error.message).toBe( + "devB was re-paired; workers started before that are no longer listed here. worker-show still shows them from this computer's record." + ) + // A reset since then is not a re-pair: the Run lists nothing there. + await startOnB('7a1c2f1e-3a7b-4d55-9c1e-0a1b2c3d4e5f') + db.db.exec(OWE_REMOTE_RUN_CANCELS_SQL) + const afterReset = await call('orchestration.workerList', { on: 'devB', run: runId }) + expect(afterReset.ok ? record(afterReset.result).workers : afterReset.error).toEqual([]) + }) + + it("readies the Task here when the server's restart lost its worker, even after a stop it never proved", async () => { + const { taskId, runId } = await startOnB() + importState(runId, taskId, 1, { + status: 'dispatched', + workerState: 'ready', + taskStatus: 'dispatched' + }) + await call('orchestration.workerStop', { dispatch: 'ctx_b1' }) + expect(db.getTask(taskId)?.status).toBe('blocked') + + importState(runId, taskId, 2, { + status: 'failed', + workerState: 'abandoned', + taskStatus: 'ready' + }) + expect(db.getTask(taskId)?.status).toBe('ready') + }) + + it('fails a Task an unanswered stop blocked when its pairing is re-made, and tells the coordinator', async () => { + const { taskId, runId } = await startOnB() + importState(runId, taskId, 1, { + status: 'dispatched', + workerState: 'ready', + taskStatus: 'dispatched' + }) + await call('orchestration.workerStop', { dispatch: 'ctx_b1' }) + expect(db.getTask(taskId)?.status).toBe('blocked') + server = { ...server, homePeerFingerprint: 'cred_a_new', pairingRevision: 2 } + + await call('orchestration.workerRead', { dispatch: 'ctx_b1' }) + expect(db.getTask(taskId)).toMatchObject({ + status: 'failed', + result: 'The pairing with devB was re-made. Its worker may still run there.' + }) + expect( + db.db + .prepare(`SELECT 1 FROM messages WHERE to_handle = ? AND type = 'escalation'`) + .get(`run:${runId}`) + ).toBeDefined() + }) + + it('keeps a Task an abandon blocked as it is when its pairing is re-made', async () => { + const { taskId, runId } = await startOnB() + importState(runId, taskId, 1, { + status: 'dispatched', + workerState: 'ready', + taskStatus: 'dispatched' + }) + await call('orchestration.workerAbandon', { dispatch: 'ctx_b1' }) + server = { ...server, homePeerFingerprint: 'cred_a_new', pairingRevision: 2 } + + await call('orchestration.workerRead', { dispatch: 'ctx_b1' }) + expect(db.getTask(taskId)?.status).toBe('blocked') + }) + + it("fails the Task when the server's reset removes an attempt whose Task it had readied", async () => { + const { taskId, runId } = await startOnB() + importState(runId, taskId, 1, { + status: 'dispatched', + workerState: 'ready', + taskStatus: 'dispatched' + }) + importState(runId, taskId, 2, { + status: 'failed', + workerState: 'abandoned', + taskStatus: 'ready', + removed: 'devB was reset.' + }) + expect(db.getTask(taskId)).toMatchObject({ status: 'failed', result: 'devB was reset.' }) + }) + + it('fails the Task a worker held once its server is removed from this Orca', async () => { + const { taskId, runId } = await startOnB() + paired = false + runtime.ensureOrchestrationFederationRelay(runId) + + await vi.waitFor(() => + expect(db.getTask(taskId)).toMatchObject({ + status: 'failed', + result: "devB was removed from this Orca's paired servers. Its worker may still run there." + }) + ) + }) + + it('sends a stop it owes as soon as its server answers again, not after its backoff', async () => { + const { taskId, runId } = await startOnB() + importState(runId, taskId, 1, { + status: 'dispatched', + workerState: 'ready', + taskStatus: 'dispatched' + }) + await call('orchestration.workerStop', { dispatch: 'ctx_b1' }) + db.db.prepare('UPDATE remote_dispatches SET stop_retry_at = ?').run(Date.now() + 600_000) + const stops = () => sent.filter((s) => s.method === 'orchestration.workerStop').length + const before = stops() + + answers['orchestration.workerStop'] = [{ result: { state: 'stopped', alreadySettled: false } }] + pullFailures = 1 + await vi.waitFor(() => expect(stops()).toBe(before + 1), { timeout: 8_000 }) + }) + + /** devB's queue item saying where its Dispatch and Task now stand. */ + function importState( + runId: string, + taskId: string, + sequence: number, + state: { + status: string + workerState: string + taskStatus: string + result?: string + removed?: string + } + ) { + const link = record(db.db.prepare('SELECT conversation_id FROM remote_run_links').get()) + importRemoteOwnedItem(db, remoteServerPin(server), { + conversationId: String(link.conversation_id), + sequence, + messageId: `state_${sequence}`, + kind: 'worker_state', + payload: JSON.stringify({ + v: 1, + id: `state_${sequence}`, + homeRunId: runId, + peerRunId: 'run_on_b', + dispatch: { + id: 'ctx_b1', + taskId, + status: state.status, + workerState: state.workerState, + lastFailure: null, + agent: 'claude' + }, + task: { status: state.taskStatus, result: state.result ?? null }, + correctedUnobservedPrompt: false, + removed: state.removed ? { reason: state.removed } : null + }) + }) + } + + for (const method of ['orchestration.workerStop', 'orchestration.workerAbandon']) { + it(`settles the Task here at once when the server does not answer ${method}, and the first result stands`, async () => { + const { taskId, runId } = await startOnB() + importState(runId, taskId, 1, { + status: 'dispatched', + workerState: 'ready', + taskStatus: 'dispatched' + }) + + const stopped = await call(method, { dispatch: 'ctx_b1' }) + // A stop stays owed; an abandon, as a local one, stops nothing. + const stop = method === 'orchestration.workerStop' + expect(stopped.ok ? stopped.result : undefined).toMatchObject({ + state: stop ? 'stop_requested' : 'abandoned' + }) + expect(getRemoteDispatch(db, 'ctx_b1')).toMatchObject({ stop_owed: stop ? 1 : 0 }) + // As a local stop leaves it: blocked, so it can be retried. + expect(db.getTask(taskId)?.status).toBe('blocked') + + // devB finished before it got the stop; its late result changes only its record here. + importState(runId, taskId, 2, { + status: 'completed', + workerState: 'succeeded', + taskStatus: 'completed', + result: 'done' + }) + expect(db.getTask(taskId)?.status).toBe('blocked') + expect(getRemoteDispatch(db, 'ctx_b1')).toMatchObject({ + status: 'completed', + worker_state: 'succeeded', + task_settled_here: stop ? 1 : 2 + }) + + answers['orchestration.workerStart'] = [started('ctx_b2')] + const retry = await call('orchestration.workerStart', { + from: 'term_coord', + on: 'devB', + task: taskId, + retryOf: 'ctx_b1', + worktree: 'new-top-level' + }) + expect(retry.ok).toBe(true) + }) + } +}) diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-route.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-route.ts new file mode 100644 index 00000000000..c41daaf0f39 --- /dev/null +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-route.ts @@ -0,0 +1,322 @@ +import { randomUUID } from 'node:crypto' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import type { RpcContext, RpcMethod, RpcRequest } from '../../../rpc/core' +import { + checkDeclaredOrchestrationAccess, + type OrchestrationMethodAccessDeclaration +} from '../../../rpc/methods/orchestration/access/orchestration-method-access' +import { emptyWorkerListPage } from '../../../rpc/methods/orchestration/worker/worker-list-method' +import { ORCHESTRATION_FLEET_PAGE_MAX } from '../../../../../shared/orchestration/fleet/orchestration-fleet-projection' +import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../../../shared/orca-session-address-prefix' +import { WorkerStartParams } from '../../../../../shared/rpc-contract/orchestration-worker-start-params' +import { isOrchestrationMutation } from '../../../../../shared/orchestration/orchestration-rpc-contract' +import type { OrchestrationDb } from '../../db/orchestration-db' +import { runLifecycleWriteTransaction } from '../../db/lifecycle-write-transaction-runner' +import { + getRemoteDispatch, + getRemoteOwnedQuestion +} from '../../db/remote-owned/remote-dispatch-records' +import { adoptRemoteAttempt } from '../../db/remote-owned/remote-placements' +import { + getOpenRemoteRunLink, + getRemoteRunLink, + type RemoteRunLinkRow +} from '../../db/remote-owned/remote-run-links' +import { callRemoteOwnedServer } from './remote-owned-calls' +import { remoteForwardKey, type RemoteForwardKey } from './remote-forward-caller' +import { inServerTerms, serverNeverAnswered } from './remote-owned-answers' +import { remoteWorkerShow, remoteServerName } from './remote-owned-reads' +import { OrchestrationError } from '../../orchestration-error' +import { latestRunLink, repairedListError } from './re-paired-run-list' +import { explainRemoteServerFailure } from './remote-server-unreachable' +import { serverOwnsPlacedWorkers, startRemoteOwnedWorker } from './remote-owned-start' +import { settleUnansweredAbandon, stopRemoteWorker } from './remote-owned-stop' + +type Routed = { handled: false } | { handled: true; result: unknown } + +const LOCAL: Routed = { handled: false } +// Long enough for a send that starts a follow-up worker there and waits for it to be ready. +const FORWARD_TIMEOUT_MS = 180_000 +// A read gives up soon on a sleeping server, whose socket stays open. +const READ_TIMEOUT_MS = 5_000 +// What `--on ` sends there; send and reply --on stay peer mail. +const SERVER_CALLS: ReadonlySet = new Set([ + 'orchestration.workerStart', + 'orchestration.workerList', + 'orchestration.requestShow' +]) + +type Values = Record + +/** + * Before this Orca's receipts: a command about a worker a paired server owns runs there, by that + * server's ordinary handler, as its Run's coordinator. The worker is found from the subjects the + * method declares; the caller passes the method's one access check here first, as it would for a + * worker of its own. A paired Orca's calls always run here: pairing is one-way. + */ +export async function routeRemoteOwnedCall( + runtime: OrcaRuntimeService, + method: RpcMethod, + request: RpcRequest, + params: unknown, + ctx: RpcContext +): Promise { + const access = method.orchestrationAccess + if (!access || access.kind === 'localOnly' || ctx.orchestrationCaller?.kind === 'peer') { + return LOCAL + } + const values: Values = params && typeof params === 'object' ? { ...params } : {} + const db = runtime.getOrchestrationDb() + // A start goes to a server only by --on; a remote Dispatch it names (--retry-of) stays this Orca's claim to check. + const subject = + request.method === 'orchestration.workerStart' ? undefined : remoteSubject(db, access, values) + if (!subject) { + const on = access.server && stringField(values, access.server) + return on === undefined ? LOCAL : routeServerCall(runtime, request, access, values, ctx, on) + } + checkDeclaredOrchestrationAccess(access, params, ctx) + const record = subject.dispatchId ? getRemoteDispatch(db, subject.dispatchId) : undefined + if (request.method === 'orchestration.workerShow' && record) { + // A status read is this Orca's record, never a call there: instant whatever the server is doing. + return { handled: true, result: remoteWorkerShow(runtime, record) } + } + const forward = remoteForwardKey( + runtime, + ctx, + access.caller && stringField(values, access.caller), + request.orchestrationRequestId + ) + if (request.method === 'orchestration.workerStop' && subject.dispatchId) { + return { + handled: true, + result: await stopRemoteWorker(runtime, subject.link, subject.dispatchId, forward) + } + } + if (request.method === 'orchestration.workerAbandon' && subject.dispatchId) { + try { + return { + handled: true, + result: await forwardToLink(runtime, subject, request.method, access, values, forward) + } + } catch (error) { + if (!serverNeverAnswered(error) || !getOpenRemoteRunLink(db, subject.link.conversation_id)) { + throw error + } + return { + handled: true, + result: settleUnansweredAbandon(runtime, subject.link, subject.dispatchId) + } + } + } + return { + handled: true, + result: await forwardToLink(runtime, subject, request.method, access, values, forward) + } +} + +/** `--on `: a start, a list, or a receipt lookup there; send and reply --on to anything else stay peer mail. */ +async function routeServerCall( + runtime: OrcaRuntimeService, + request: RpcRequest, + access: OrchestrationMethodAccessDeclaration, + values: Values, + ctx: RpcContext, + on: string +): Promise { + // A chat named by its session ID is refused by the ordinary start before any server is asked. + if (!SERVER_CALLS.has(request.method) || isSessionAddress(values.terminal)) { + return LOCAL + } + checkDeclaredOrchestrationAccess(access, values, ctx) + const server = runtime.resolveOrchestrationWorkerServer(on) + const db = runtime.getOrchestrationDb() + if (request.method === 'orchestration.workerStart') { + if ( + holdsLocalReceipt(db, ctx, request.orchestrationRequestId) || + !(await serverOwnsPlacedWorkers(runtime, server)) + ) { + // An older server: today's remote attachment, the one legacy branch for new work. + return LOCAL + } + return { + handled: true, + result: await startRemoteOwnedWorker( + runtime, + WorkerStartParams.parse(values), + ctx, + request.orchestrationRequestId + ) + } + } + if (request.method === 'orchestration.workerList') { + const runId = stringField(values, 'run') + // A Run lists what it placed there, as its coordinator; no Run lists the server as a whole. + const latest = runId ? latestRunLink(db, runId, server.environmentId) : undefined + if (latest?.state === 'closed') { + throw repairedListError(server.name) + } + const link = latest?.state === 'open' ? latest : undefined + if (runId && !link) { + return { + handled: true, + result: emptyWorkerListPage(numberField(values, 'limit') ?? ORCHESTRATION_FLEET_PAGE_MAX) + } + } + const forwarded = paramsForServer(access, values) + try { + return { + handled: true, + result: link + ? await forwardToLink(runtime, { link }, request.method, access, values) + : await runtime.callOrchestrationWorkerServer( + server.environmentId, + request.method, + forwarded, + READ_TIMEOUT_MS, + undefined, + { expectedEnvironmentPairingRevision: server.pairingRevision } + ) + } + } catch (error) { + const closed = link && getRemoteRunLink(db, link.conversation_id)?.state === 'closed' + if ( + closed || + (error instanceof OrchestrationError && error.code === 'server_pairing_changed') + ) { + throw repairedListError(server.name) + } + throw error + } + } + { + // The server keyed the request by this caller's scoped key, as the forward that sent it did. + const forward = remoteForwardKey( + runtime, + ctx, + undefined, + stringField(values, 'request') ?? randomUUID() + )! + const answer = await runtime.callOrchestrationWorkerServer( + server.environmentId, + request.method, + { request: forward.key }, + READ_TIMEOUT_MS, + undefined, + { expectedEnvironmentPairingRevision: server.pairingRevision } + ) + return { handled: true, result: inServerTerms(answer, { server: server.name, forward }) } + } +} + +type RemoteSubject = { link: RemoteRunLinkRow; dispatchId?: string } + +/** The worker or question a call names, when a paired server owns it. Tasks stay in this Orca's graph. */ +function remoteSubject( + db: OrchestrationDb, + access: OrchestrationMethodAccessDeclaration, + values: Values +): RemoteSubject | undefined { + for (const [field, kind] of Object.entries(access.targets)) { + const value = stringField(values, field) + const dispatchId = + kind === 'dispatch' + ? value + : kind === 'party' && value?.startsWith('dispatch:') + ? value.slice('dispatch:'.length) + : undefined + const record = dispatchId ? getRemoteDispatch(db, dispatchId) : undefined + const question = kind === 'message' && value ? getRemoteOwnedQuestion(db, value) : undefined + const conversationId = record?.conversation_id ?? question?.conversation_id + const link = conversationId ? getRemoteRunLink(db, conversationId) : undefined + if (link) { + return { link, dispatchId: record?.dispatch_id } + } + } + return undefined +} + +/** This Orca's caller, Run and server fields mean nothing there: the server names the caller itself. */ +function paramsForServer(access: OrchestrationMethodAccessDeclaration, values: Values): Values { + const local = new Set( + [ + access.caller, + access.callerPane, + access.server, + ...Object.entries(access.targets) + .filter(([, kind]) => kind === 'run') + .map(([field]) => field) + ].filter((field): field is string => field !== undefined) + ) + return Object.fromEntries(Object.entries(values).filter(([field]) => !local.has(field))) +} + +async function forwardToLink( + runtime: OrcaRuntimeService, + { link, dispatchId }: RemoteSubject, + method: string, + access: OrchestrationMethodAccessDeclaration, + values: Values, + forward?: RemoteForwardKey +): Promise { + const db = runtime.getOrchestrationDb() + const server = remoteServerName(runtime, link.environment_id) + const params = paramsForServer(access, values) + try { + const answer = await callRemoteOwnedServer(runtime, link, { + method, + params, + timeoutMs: isOrchestrationMutation(method, params) ? FORWARD_TIMEOUT_MS : READ_TIMEOUT_MS, + ...(forward ? { requestId: forward.key } : {}), + whileLink: ['open'] + }) + seedNamedDispatches(db, link, answer) + return inServerTerms(answer, { server, forward, link }) + } catch (error) { + throw inServerTerms(explainRemoteServerFailure(error, { server, method, params, dispatchId }), { + server, + forward, + link + }) + } +} + +/** A Dispatch the server's answer names (a follow-up it started) is its; record it so commands about it route there. */ +function seedNamedDispatches(db: OrchestrationDb, link: RemoteRunLinkRow, answer: unknown): void { + const named: Values = answer && typeof answer === 'object' ? { ...answer } : {} + const dispatchId = stringField(named, 'dispatchId') + const taskId = stringField(named, 'taskId') + if (!dispatchId || !taskId || getRemoteDispatch(db, dispatchId)) { + return + } + runLifecycleWriteTransaction(db.db, 'seed_remote_dispatch', () => { + const open = getOpenRemoteRunLink(db, link.conversation_id) + if (open) { + adoptRemoteAttempt(db, open, { taskId, dispatchId }) + } + }) +} + +/** A retry of a start this Orca already took on today's path stays there, whatever the server runs now. */ +function holdsLocalReceipt( + db: OrchestrationDb, + ctx: RpcContext, + requestId: string | undefined +): boolean { + const caller = + ctx.authenticatedCallerFingerprint ?? db.getOrCreateLocalMutationCallerFingerprint() + return requestId !== undefined && db.getMutationReceipt(caller, requestId) !== undefined +} + +function isSessionAddress(value: unknown): boolean { + return typeof value === 'string' && value.startsWith(ORCA_SESSION_ADDRESS_PREFIX) +} + +function stringField(values: Values, field: string): string | undefined { + const value = values[field] + return typeof value === 'string' && value !== '' ? value : undefined +} + +function numberField(values: Values, field: string): number | undefined { + const value = values[field] + return typeof value === 'number' ? value : undefined +} diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-start.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-start.ts new file mode 100644 index 00000000000..195beb02ca8 --- /dev/null +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-start.ts @@ -0,0 +1,226 @@ +import { createHash, randomUUID } from 'node:crypto' +import { z } from 'zod' +import type { WorkerStartParams } from '../../../../../shared/rpc-contract/orchestration-worker-start-params' +import { ORCHESTRATION_REMOTE_OWNED_WORKERS_RUNTIME_CAPABILITY } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' +import { ORCHESTRATION_CONTRACT_PREFLIGHT_TIMEOUT_MS } from '../../../../../shared/orchestration/orchestration-timing-budgets' +import type { RuntimeStatus } from '../../../../../shared/runtime-session-contracts' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import type { RpcContext } from '../../../rpc/core' +import { prepareWorkerStart } from '../../../rpc/methods/orchestration/worker/workers' +import { resolveFederatedWorkerStartBudgets } from '../../../rpc/methods/orchestration/worker/worker-start-budgets' +import { OrchestrationError } from '../../orchestration-error' +import { prepareWorkerStartCard } from '../../workers/launch/worker-start-card' +import { getOrchestrationPeerCapabilityCache } from '../orchestration-peer-capability-cache' +import type { OrchestrationWorkerServer } from '../environment-transport' +import { + recordRemoteStart, + releaseRemotePlacement, + reserveRemotePlacement +} from '../../db/remote-owned/remote-placements' +import { refuseTaskOfClosedPairing } from '../../db/remote-owned/remote-placement-hold' +import { openRemoteRunLink } from '../../db/remote-owned/remote-run-links' +import { callRemoteOwnedServer } from './remote-owned-calls' +import { remoteForwardKey } from './remote-forward-caller' +import { errorData, inServerTerms, serverNeverAnswered } from './remote-owned-answers' + +type StartParams = z.infer +type StartContext = Pick< + RpcContext, + 'runtime' | 'orchestrationCompatibilityEvidence' | 'orchestrationCaller' +> + +/** Whether the server runs the workers placed on it as its own; an older one keeps today's remote attachments. */ +export async function serverOwnsPlacedWorkers( + runtime: OrcaRuntimeService, + server: OrchestrationWorkerServer +): Promise { + const decision = await getOrchestrationPeerCapabilityCache(runtime).resolve({ + peerFingerprint: server.peerFingerprint, + expectedRuntimeEpoch: null, + capability: ORCHESTRATION_REMOTE_OWNED_WORKERS_RUNTIME_CAPABILITY, + probe: async () => + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: status.get answers RuntimeStatus; the cache reads only its capabilities and runtime ID. + (await runtime.callOrchestrationWorkerServer( + server.environmentId, + 'status.get', + undefined, + ORCHESTRATION_CONTRACT_PREFLIGHT_TIMEOUT_MS, + undefined, + { expectedEnvironmentPairingRevision: server.pairingRevision } + )) as RuntimeStatus + }) + return decision.supported +} + +/** One ID for the Task here and the start there, from the start's retry key, so a retry finds both. */ +function adoptedTaskId(key: string): string { + return `task_${createHash('sha256').update(`task\n${key}`).digest('hex').slice(0, 12)}` +} + +const StartedOnServer = z.object({ + dispatchId: z.string().min(1), + run: z.object({ id: z.string().min(1) }).optional(), + agent: z.string().nullable().optional() +}) + +/** + * worker-start --on a server that owns its workers: the Task stays in this Orca's graph, and the + * server starts an ordinary worker for it as the Run's coordinator. Synchronous, launch then + * record: the Task is reserved for the server first, and becomes its attempt once it answers. + */ +export async function startRemoteOwnedWorker( + runtime: OrcaRuntimeService, + params: StartParams, + ctx: StartContext, + callerRequestId: string | undefined +): Promise { + if (params.terminal) { + throw new OrchestrationError( + 'invalid_argument', + '--terminal names a terminal on this Orca, so it cannot be used with --on. No effects were applied.', + { effectsApplied: false } + ) + } + const { coordinator, bindRun, taskDeps, existingTask, withRun } = await prepareWorkerStart( + params, + ctx + ) + const db = runtime.getOrchestrationDb() + const server = runtime.resolveOrchestrationWorkerServer(params.on!) + const { run } = bindRun() + // An older CLI sends no request ID; the start still runs, but a retry cannot find it. + const forward = remoteForwardKey(runtime, ctx, params.from, callerRequestId ?? randomUUID())! + const taskId = existingTask?.id ?? adoptedTaskId(forward.key) + const budgets = resolveFederatedWorkerStartBudgets(params.timeoutMs) + // Before any link is written: a Task an earlier pairing with this server placed is not reused there. + refuseTaskOfClosedPairing(db, taskId, server) + const link = openRemoteRunLink(db, run.id, server, (handle, type) => + runtime.notifyMessageArrived(handle, type) + ) + const { task } = reserveRemotePlacement(db, { + link, + taskId, + requestKey: forward.key, + retryOf: params.retryOf, + create: existingTask + ? undefined + : { + spec: params.spec!, + taskTitle: params.taskTitle, + deps: taskDeps, + parentId: params.parent, + createdByTerminalHandle: coordinator?.terminalHandle ?? undefined, + createdByPaneKey: coordinator?.paneKey ?? undefined, + createdByRunGeneration: run.consumer_generation + } + }) + // Its queue has a reader from the start, so mail sent before the answer still comes home. + runtime.ensureOrchestrationFederationRelay(run.id) + const { + from: _from, + run: _run, + on: _on, + task: _task, + deps: _deps, + parent: _parent, + ...options + } = params + let receipt: unknown + try { + receipt = await callRemoteOwnedServer(runtime, link, { + method: 'orchestration.workerStart', + params: { + ...options, + // A retry names the server's existing Task, whose ordinary retry checks refuse a spec. + ...(params.retryOf + ? { task: task.id } + : { spec: task.spec, ...(task.task_title ? { taskTitle: task.task_title } : {}) }), + adoptTaskId: task.id + }, + timeoutMs: budgets.attachDeadlineMs, + requestId: forward.key, + whileLink: ['open'] + }) + } catch (error) { + settleUnansweredStart(runtime, { + conversationId: link.conversation_id, + taskId, + error, + key: forward.key, + createdByStart: !existingTask + }) + throw inServerTerms(error, { server: server.name, forward }) + } + const started = StartedOnServer.safeParse(receipt) + if (started.success) { + const recorded = recordRemoteStart(db, { + conversationId: link.conversation_id, + taskId, + dispatchId: started.data.dispatchId, + requestKey: forward.key, + peerRunId: started.data.run?.id, + agent: started.data.agent ?? null + }) + if (!recorded) { + // A reset already removed the reservation; a re-made pairing keeps it, so a later start of the Task there is refused here. + throw new OrchestrationError( + 'run_not_found', + `Run ${run.id} was reset, or its pairing with ${server.name} re-made, while this start was waiting, so this Orca records nothing for the worker it started there (Dispatch ${started.data.dispatchId}).`, + { server: server.name } + ) + } + prepareWorkerStartCard( + runtime, + ctx.orchestrationCaller + )({ + dispatchId: started.data.dispatchId, + workerAddress: `dispatch:${started.data.dispatchId}`, + task: task.spec, + agent: null + }) + } + const answer = inServerTerms(receipt, { server: server.name, forward }) + return withRun( + answer && typeof answer === 'object' + ? { + ...answer, + // This Orca's Run and Task; the server's own Run for them is named apart. + taskId, + runId: run.id, + runCreated: bindRun().created, + ...(started.data?.run ? { serverRunId: started.data.run.id } : {}) + } + : answer + ) +} + +/** What a start's failure says about its reservation: adopt the Dispatch it names, keep it for the server's queue to answer, or free it. */ +function settleUnansweredStart( + runtime: OrcaRuntimeService, + start: { + conversationId: string + taskId: string + key: string + error: unknown + createdByStart: boolean + } +): void { + const db = runtime.getOrchestrationDb() + const data = errorData(start.error) + const named = typeof data?.dispatchId === 'string' ? data.dispatchId : undefined + // An unknown outcome stays reserved: the queue item for any Dispatch the server created adopts it. + const outcomeUnknown = + (start.error instanceof OrchestrationError && start.error.code === 'operation_unknown') || + (serverNeverAnswered(start.error) && data?.effectsApplied !== false) + if (named) { + recordRemoteStart(db, { + conversationId: start.conversationId, + taskId: start.taskId, + dispatchId: named, + requestKey: start.key + }) + } else if (!outcomeUnknown) { + // The server's ordinary start refused it, which a start that had launched answers with a receipt. + releaseRemotePlacement(db, start.taskId, start.key, { createdByStart: start.createdByStart }) + } +} diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-owned-stop.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-stop.ts new file mode 100644 index 00000000000..b52cbd2fd14 --- /dev/null +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-owned-stop.ts @@ -0,0 +1,81 @@ +import { randomUUID } from 'node:crypto' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import { oweRemoteDispatchStop, remoteStopKey } from '../../db/remote-owned/remote-dispatch-records' +import { getOpenRemoteRunLink, type RemoteRunLinkRow } from '../../db/remote-owned/remote-run-links' +import { settleRemoteAttemptHere } from '../../db/remote-owned/remote-placements' +import { OrchestrationError } from '../../orchestration-error' +import type { RemoteForwardKey } from './remote-forward-caller' +import { inServerTerms, serverNeverAnswered } from './remote-owned-answers' +import { sendOwedRemoteStop } from './remote-owed-actions' +import { remoteServerName } from './remote-owned-reads' + +/** A stop is owed until the server proves it; the ordinary stop answers when it can, and the pull loop resends otherwise. */ +export async function stopRemoteWorker( + runtime: OrcaRuntimeService, + link: RemoteRunLinkRow, + dispatchId: string, + forward: RemoteForwardKey | undefined +): Promise { + const db = runtime.getOrchestrationDb() + const server = remoteServerName(runtime, link.environment_id) + const owed = oweRemoteDispatchStop(db, dispatchId, forward?.key ?? `stop:${randomUUID()}`) + if (!owed) { + throw new OrchestrationError( + 'dispatch_not_found', + `Worker Dispatch ${dispatchId} was not found.` + ) + } + runtime.ensureOrchestrationFederationRelay(link.run_id) + // The server knows this attempt by its stop key; the caller knows only its own request ID. + const stopKey = forward && { key: remoteStopKey(owed.record), requestId: forward.requestId } + try { + return inServerTerms(await sendOwedRemoteStop(runtime, owed.record), { + server, + forward: stopKey, + link: link + }) + } catch (error) { + if (!serverNeverAnswered(error) || !getOpenRemoteRunLink(db, link.conversation_id)) { + throw inServerTerms(error, { server, forward: stopKey, link: link }) + } + return settleUnansweredStop(runtime, link, dispatchId) + } +} + +/** The server did not answer a stop: the Task half runs here at once, as a local stop's does, and the stop stays owed until the server proves it. */ +function settleUnansweredStop( + runtime: OrcaRuntimeService, + link: RemoteRunLinkRow, + dispatchId: string +) { + const server = remoteServerName(runtime, link.environment_id) + settleRemoteAttemptHere(runtime.getOrchestrationDb(), dispatchId, 'stopped') + return { + dispatchId, + state: 'stop_requested', + server, + next: `${server} did not answer, so its worker may still run there. Its Task is settled here, so it can be retried, and the stop is owed: this Orca sends it again until ${server} confirms the worker stopped.` + } +} + +/** + * The server did not answer an abandon: as a local abandon, nothing is stopped; the Task half runs + * here at once, so the Task can be retried, and the worker there is left to run. + */ +export function settleUnansweredAbandon( + runtime: OrcaRuntimeService, + link: RemoteRunLinkRow, + dispatchId: string +) { + const server = remoteServerName(runtime, link.environment_id) + settleRemoteAttemptHere(runtime.getOrchestrationDb(), dispatchId, 'abandoned') + return { + dispatchId, + state: 'abandoned', + alreadySettled: false, + stale: false, + processAction: 'none', + warning: `${server} did not answer, so it was not told and its worker may still run there. The Task is settled here, so it can be retried; no process was stopped.`, + residualResources: [] + } +} diff --git a/src/main/runtime/orchestration/federation/remote-owned/remote-server-unreachable.ts b/src/main/runtime/orchestration/federation/remote-owned/remote-server-unreachable.ts new file mode 100644 index 00000000000..e668755c2cc --- /dev/null +++ b/src/main/runtime/orchestration/federation/remote-owned/remote-server-unreachable.ts @@ -0,0 +1,38 @@ +import { isOrchestrationMutation } from '../../../../../shared/orchestration/orchestration-rpc-contract' +import { OrchestrationError } from '../../orchestration-error' + +/** Off, asleep or off the network: the server gave no answer at all. */ +export const REMOTE_SERVER_UNREACHABLE_CODES = ['remote_runtime_unavailable', 'runtime_timeout'] + +export function isRemoteServerUnreachable(error: unknown): boolean { + return unreachableCode(error) !== undefined +} + +function unreachableCode(error: unknown): string | undefined { + const code = error instanceof Error && 'code' in error ? error.code : undefined + return typeof code === 'string' && REMOTE_SERVER_UNREACHABLE_CODES.includes(code) + ? code + : undefined +} + +/** + * A command about a remote worker that its server never answered, said in terms of that server. A + * change may still have landed there, so its outcome is unknown here. An answer, the server's own + * `operation_unknown` included, is the server's to explain and is returned unchanged. + */ +export function explainRemoteServerFailure( + error: unknown, + call: { server: string; method: string; params: unknown; dispatchId?: string } +): unknown { + const code = unreachableCode(error) + if (!code || !(error instanceof Error)) { + return error + } + const { server, dispatchId } = call + const show = `worker-show${dispatchId ? ` --dispatch ${dispatchId}` : ''}` + const message = isOrchestrationMutation(call.method, call.params) + ? `${server} did not answer (${error.message}), so this Orca cannot tell whether the command reached it. Make sure Orca is running on ${server} and check with ${show}. Retry only with the same request ID (--retry-request); a new command could apply it twice.` + : `${server} could not be reached (${error.message}). Make sure Orca is running on ${server}, then try again.${dispatchId ? ` Meanwhile ${show} gives this Orca's last record of the worker; its output is kept only on ${server}.` : ''}` + const data = 'data' in error && error.data && typeof error.data === 'object' ? error.data : {} + return new OrchestrationError(code, message, { ...data, server, reachable: false }) +} diff --git a/src/main/runtime/orchestration/federation/synchronization/federation-ack-checkpoints.test.ts b/src/main/runtime/orchestration/federation/synchronization/federation-ack-checkpoints.test.ts deleted file mode 100644 index 950c34586cd..00000000000 --- a/src/main/runtime/orchestration/federation/synchronization/federation-ack-checkpoints.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { OrcaRuntimeService } from '../../../orca-runtime' -import { - acquireFederationAckLease, - clearFederationAckCheckpoints, - getFederationAckedThrough, - recordFederationAckCheckpoint, - type FederationAckIdentity -} from '../../legacy-remote-home/federation-ack-checkpoints' - -describe('federation acknowledgment checkpoints', () => { - it('matches checkpoints only to their exact remote identity and never moves backward', () => { - const runtime = {} as OrcaRuntimeService - const identity: FederationAckIdentity = { - environmentId: 'environment_windows', - peerFingerprint: 'windows_peer_fingerprint', - remoteRuntimeEpoch: 'remote_epoch_1' - } - const lease = acquireFederationAckLease(runtime, 'dispatch_remote') - recordFederationAckCheckpoint(runtime, lease, { - ...identity, - throughSequence: 2 - }) - - recordFederationAckCheckpoint(runtime, lease, { - ...identity, - throughSequence: 3 - }) - recordFederationAckCheckpoint(runtime, lease, { - ...identity, - throughSequence: 2 - }) - - expect(getFederationAckedThrough(lease, identity)).toBe(3) - expect( - getFederationAckedThrough(lease, { ...identity, remoteRuntimeEpoch: 'remote_epoch_2' }) - ).toBe(0) - expect( - getFederationAckedThrough(lease, { ...identity, peerFingerprint: 'replacement_peer' }) - ).toBe(0) - expect(getFederationAckedThrough(lease, { ...identity, environmentId: 'replacement' })).toBe(0) - }) - - it('fences delayed writes after runtime reset', () => { - const runtime = {} as OrcaRuntimeService - const identity: FederationAckIdentity = { - environmentId: 'environment_windows', - peerFingerprint: 'windows_peer_fingerprint', - remoteRuntimeEpoch: 'remote_epoch_1' - } - const staleRuntimeLease = acquireFederationAckLease(runtime, 'dispatch_remote') - clearFederationAckCheckpoints(runtime) - recordFederationAckCheckpoint(runtime, staleRuntimeLease, { - ...identity, - throughSequence: 2 - }) - expect( - getFederationAckedThrough(acquireFederationAckLease(runtime, 'dispatch_remote'), identity) - ).toBe(0) - }) -}) diff --git a/src/main/runtime/orchestration/federation/synchronization/federation-sync-capability.test.ts b/src/main/runtime/orchestration/federation/synchronization/federation-sync-capability.test.ts deleted file mode 100644 index d43957bdd3c..00000000000 --- a/src/main/runtime/orchestration/federation/synchronization/federation-sync-capability.test.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { ORCHESTRATION_FEDERATION_RELEASE_ARCHIVE_RUNTIME_CAPABILITY } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' -import { createIdleSyncHarness } from './federation-sync-test-harness' -import { armHomeAutoReleaseForOlderHost } from '../../legacy-remote-home/federation-sync-capability' - -function releasableTerminalWorker() { - const harness = createIdleSyncHarness() - harness.setRemoteCapabilities([ORCHESTRATION_FEDERATION_RELEASE_ARCHIVE_RUNTIME_CAPABILITY]) - const db = harness.runtime.getOrchestrationDb() - const federated = db.getFederatedDispatch('dispatch_remote')! - db.getFederatedDispatch = () => ({ - ...federated, - remote_terminal_handle: 'term_remote_worker', - home_auto_release_state: null - }) - const worker = db.getWorkerDispatch('dispatch_remote')! - db.getWorkerDispatch = () => ({ ...worker, state: 'succeeded', stage: 'reported' }) - db.workerAutoReleaseEnabled = () => true - return { - runtime: harness.runtime, - remoteCall: harness.remoteCall, - dispatchId: federated.dispatch_id, - armedDeadlines: () => db.claimDueFederatedHomeAutoReleases(Date.UTC(2100, 0, 1)) - } -} - -describe('armHomeAutoReleaseForOlderHost', () => { - it('does not arm from a sync the relay stopped while it probed the host', async () => { - const { runtime, remoteCall, dispatchId, armedDeadlines } = releasableTerminalWorker() - const answer = remoteCall.getMockImplementation()! - let noteProbe!: () => void - let releaseProbe!: () => void - const probing = new Promise((resolve) => (noteProbe = resolve)) - const released = new Promise((resolve) => (releaseProbe = resolve)) - remoteCall.mockImplementation(async (...args) => { - if (args[1] === 'status.get') { - noteProbe() - await released - } - return answer(...args) - }) - let current = true - - const arming = armHomeAutoReleaseForOlderHost(runtime, dispatchId, 1, () => current) - await probing - current = false - releaseProbe() - await arming - - expect(armedDeadlines()).toEqual([]) - }) -}) diff --git a/src/main/runtime/orchestration/mailbox/formatting/imported-peer-item-presentation.ts b/src/main/runtime/orchestration/mailbox/formatting/imported-peer-item-presentation.ts new file mode 100644 index 00000000000..7747351ab69 --- /dev/null +++ b/src/main/runtime/orchestration/mailbox/formatting/imported-peer-item-presentation.ts @@ -0,0 +1,13 @@ +/** Mail a paired Orca sent here, by the queue item kind it arrived as. */ +export type ImportedPeerItem = + /** A reply in a peer-mail conversation this Orca opened. */ + | { kind: 'peer_mail'; senderLabel: string; body: string } + /** A message filed in the mailbox of a Run this Orca coordinates on that server. */ + | { kind: 'worker_mail'; from: string; body: string } + +/** The one place that decides how an imported peer item is stored: its sender label and body. */ +export function presentImportedPeerItem(item: ImportedPeerItem): { from: string; body: string } { + return item.kind === 'peer_mail' + ? { from: item.senderLabel, body: item.body } + : { from: item.from, body: item.body } +} diff --git a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-completion-title.spec.ts b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-completion-title.spec.ts deleted file mode 100644 index d9b975358a8..00000000000 --- a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-completion-title.spec.ts +++ /dev/null @@ -1,192 +0,0 @@ -import { rmSync } from 'node:fs' -import { afterEach, describe, expect, it, vi } from 'vitest' -import '../../../../../shared/agent-status/contracts/agent-status-freshness' -import type { AgentStatusIpcPayload } from '../../../../../shared/agent-status/contracts/agent-status-ipc-payload' -import { settledWriteStub } from '../../../../providers/settled-pty-write-stub' -import { MAILBOX_POINTER_WRITE_ATTEMPTED } from '../../db/messages/mailbox-pointer-enter-state' -import { - createBoundRun, - createDatabase, - createRuntime, - insertDirectRunMessage, - LEAF_ID, - PANE_KEY, - PTY_ID, - TAB_ID, - TERMINAL_HANDLE, - temporaryDirectories, - WORKTREE_ID -} from './orchestration-mailbox-notification-test-harness' - -function completionFixture(delayMs = 0, presence?: 'unverifiable') { - const db = createDatabase('orca-codex-completion-title-') - const hook: AgentStatusIpcPayload = { - paneKey: PANE_KEY, - terminalHandle: TERMINAL_HANDLE, - agentType: 'codex', - state: 'done', - prompt: '', - connectionId: null, - receivedAt: Date.now(), - stateStartedAt: Date.now() - } - const { runtime } = createRuntime(db, { - getAgentStatusSnapshot: () => [hook], - // Why: a Codex hook row has presence but no process id, so the store cannot answer. - ...(presence ? { checkHookAgentPresence: async () => presence } : {}) - }) - const write = vi.fn((_ptyId: string, _data: string) => true) - const getForegroundProcess = vi.fn(async (): Promise => { - if (delayMs) { - await new Promise((resolve) => setTimeout(resolve, delayMs)) - } - return 'codex' - }) - runtime.setPtyController({ - write, - writeWithSettlement: settledWriteStub(write), - kill: vi.fn(), - getForegroundProcess - }) - const run = createBoundRun(db, 'Completion title Run') - function completeWithNativeTitles(): void { - runtime.ingestSyntheticTitleFrame(PTY_ID, '\x1b]0;Codex ready\x07') - runtime.onPtyData(PTY_ID, '\x1b]0;⠋ mobile-rearch\x07', 1) - runtime.onPtyData(PTY_ID, '\x1b]0;mobile-rearch\x07', 2) - } - return { db, runtime, write, run, hook, getForegroundProcess, completeWithNativeTitles } -} - -describe('Codex completion title mailbox delivery', () => { - afterEach(() => { - vi.useRealTimers() - for (const directory of temporaryDirectories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } - }) - - it('does not restore idle over a permission title received during the host probe', async () => { - vi.useFakeTimers() - const { db, runtime, write, run, completeWithNativeTitles } = completionFixture(750) - await runtime.listTerminals() - insertDirectRunMessage(db, run.id, 'Worker progress') - completeWithNativeTitles() - runtime.onPtyData(PTY_ID, '\x1b]0;Codex waiting for permission\x07', 3) - await vi.advanceTimersByTimeAsync(1500) - expect(write.mock.calls.map(([, data]) => data)).toEqual([ - expect.stringContaining('You have 1 orchestration message') - ]) - db.close() - }) - - it('keeps an unverified staged pointer pending and submits it once readiness returns', async () => { - vi.useFakeTimers() - const { db, runtime, write, run, getForegroundProcess, completeWithNativeTitles } = - completionFixture() - getForegroundProcess.mockResolvedValue(null) - await runtime.listTerminals() - const message = insertDirectRunMessage(db, run.id, 'Worker progress') - completeWithNativeTitles() - await vi.advanceTimersByTimeAsync(10 * 60_000) - expect(write.mock.calls.map(([, data]) => data)).toEqual([ - expect.stringContaining('You have 1 orchestration message') - ]) - expect(db.getMessageById(message.id)).toMatchObject({ - read: 0, - delivered_at: null, - pointer_enter_pending: MAILBOX_POINTER_WRITE_ATTEMPTED - }) - - runtime.ingestSyntheticTitleFrame(PTY_ID, '\x1b]0;Codex ready\x07') - await vi.advanceTimersByTimeAsync(1000) - expect(write.mock.calls.map(([, data]) => data)).toEqual([ - expect.stringContaining('You have 1 orchestration message'), - '\r' - ]) - expect(db.getMessageById(message.id)).toMatchObject({ pointer_enter_pending: 0 }) - db.close() - }) - - it('rechecks a repeated neutral title before resuming the staged Enter', async () => { - vi.useFakeTimers() - const { db, runtime, write, run, completeWithNativeTitles } = completionFixture(750) - await runtime.listTerminals() - insertDirectRunMessage(db, run.id, 'Worker progress') - completeWithNativeTitles() - await vi.advanceTimersByTimeAsync(100) - runtime.onPtyData(PTY_ID, '\x1b]0;mobile-rearch\x07', 3) - await vi.advanceTimersByTimeAsync(700) - expect(write).not.toHaveBeenCalledWith(PTY_ID, '\r') - await vi.advanceTimersByTimeAsync(1500) - expect(write.mock.calls.map(([, data]) => data)).toEqual([ - expect.stringContaining('You have 1 orchestration message'), - '\r' - ]) - db.close() - }) - - it('does not restore a completed hook after a new turn starts during the probe', async () => { - vi.useFakeTimers() - const { db, runtime, write, run, hook, completeWithNativeTitles } = completionFixture(750) - await runtime.listTerminals() - completeWithNativeTitles() - hook.state = 'working' - insertDirectRunMessage(db, run.id, 'Worker progress') - runtime.notifyMessageArrived(`run:${run.id}`, 'status') - await vi.advanceTimersByTimeAsync(1500) - expect(write).not.toHaveBeenCalled() - db.close() - }) - - it('does not restore completion into a replacement process using the same PTY id', async () => { - vi.useFakeTimers() - const { db, runtime, write, run, completeWithNativeTitles } = completionFixture(750) - await runtime.listTerminals() - completeWithNativeTitles() - runtime.registerPty(PTY_ID, WORKTREE_ID, null, { - tabId: TAB_ID, - leafId: LEAF_ID, - incarnationId: 'replacement-incarnation' - }) - insertDirectRunMessage(db, run.id, 'Worker progress') - runtime.notifyMessageArrived(`run:${run.id}`, 'status') - await vi.advanceTimersByTimeAsync(1500) - expect(write).not.toHaveBeenCalled() - db.close() - }) - - it('does not reuse a completion hook from before a provider generation reset', async () => { - vi.useFakeTimers() - const { db, runtime, write, run } = completionFixture() - await runtime.listTerminals() - runtime.ingestSyntheticTitleFrame(PTY_ID, '\x1b]0;Codex ready\x07') - await vi.advanceTimersByTimeAsync(10) - runtime.synchronizePtyOutputSequenceFromProvider(PTY_ID, { value: 0, generation: 'reset' }) - runtime.onPtyData(PTY_ID, '\x1b]0;⠋ mobile-rearch\x07', 1) - runtime.onPtyData(PTY_ID, '\x1b]0;mobile-rearch\x07', 2) - await vi.advanceTimersByTimeAsync(100) - insertDirectRunMessage(db, run.id, 'Worker progress') - runtime.notifyMessageArrived(`run:${run.id}`, 'status') - await vi.advanceTimersByTimeAsync(1000) - expect(write).not.toHaveBeenCalled() - db.close() - }) - - it('discards a foreground probe spanning a generation reset even with a newer done hook', async () => { - vi.useFakeTimers() - const { db, runtime, write, run, hook, completeWithNativeTitles } = completionFixture(750) - await runtime.listTerminals() - completeWithNativeTitles() - await vi.advanceTimersByTimeAsync(100) - runtime.synchronizePtyOutputSequenceFromProvider(PTY_ID, { value: 0, generation: 'reset' }) - await vi.advanceTimersByTimeAsync(1) - hook.receivedAt = Date.now() - hook.stateStartedAt = Date.now() - await vi.advanceTimersByTimeAsync(1000) - insertDirectRunMessage(db, run.id, 'Worker progress') - runtime.notifyMessageArrived(`run:${run.id}`, 'status') - await vi.advanceTimersByTimeAsync(1000) - expect(write).not.toHaveBeenCalled() - db.close() - }) -}) diff --git a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-cursor-native-title.spec.ts b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-cursor-native-title.spec.ts deleted file mode 100644 index 32ff156a737..00000000000 --- a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-cursor-native-title.spec.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { rmSync } from 'node:fs' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { settledWriteStub } from '../../../../providers/settled-pty-write-stub' -import { - createBoundRun, - createDatabase, - createRuntime, - insertDirectRunMessage, - PTY_ID, - temporaryDirectories -} from './orchestration-mailbox-notification-test-harness' - -describe('mail to a Cursor worker under its own status title', () => { - afterEach(() => { - vi.useRealTimers() - for (const directory of temporaryDirectories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } - }) - - // cursor-agent titles its pane ` -