Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
28f1482
refactor(reasons): declare the daemon reasons in ReasonTable rows
thymikee Nov 21, 2026
478859b
chore(gates): read the device-claim reasons from their table and re-p…
thymikee Nov 21, 2026
4c95ad3
Merge remote-tracking branch 'origin/main' into t3/daemon-typed-reasons
thymikee Nov 22, 2026
7f08fae
docs(reasons): fold duplicate JSDoc into row summaries and assert spa…
thymikee Nov 22, 2026
27357da
test(daemon): cover focus and type sparse-capture find refusals
thymikee Nov 22, 2026
6667e3c
docs(reasons): recommend the pinned ref only when the refusal carries…
thymikee Nov 22, 2026
f4361e5
Merge remote-tracking branch 'origin/main' into t3/daemon-typed-reasons
thymikee Nov 22, 2026
f236a3d
Merge remote-tracking branch 'origin/main' into t3/daemon-typed-reasons
thymikee Nov 22, 2026
ca3f928
fix(replay): keep a sparse find refusal's scrubbed verdict in replay …
thymikee Nov 22, 2026
7c07d79
refactor(replay): split the cause-detail projection to stay under the…
thymikee Nov 22, 2026
35245ab
refactor(replay): pass the sparse verdict code through unchanged, scr…
thymikee Nov 22, 2026
11c415c
docs(reasons): the upload deadline covers processing after the body a…
thymikee Nov 22, 2026
6868952
docs(reasons): human control refuses state-changing commands until th…
thymikee Nov 22, 2026
12fb86c
Merge remote-tracking branch 'origin/main' into t3/daemon-typed-reasons
thymikee Nov 22, 2026
b109944
docs(reasons): describe the bounded-composite refusal by its fields; …
thymikee Nov 22, 2026
58847f4
revert(daemon): keep the pinned HTTP status mapper unchanged
thymikee Nov 22, 2026
31ede65
docs(reasons): session_cleanup_incomplete may keep the session; the h…
thymikee Nov 22, 2026
dcaa56d
docs(reasons): an expired ref frame refuses mutations; reads with evi…
thymikee Nov 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/capture-kit/src/snapshot-quality-verdict.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { ReasonTable } from '@agent-device/kernel/errors';
import type { SnapshotQualityState, SnapshotQualityVerdict } from '@agent-device/kernel/snapshot';
import { SNAPSHOT_QUALITY_BACKEND_CAPABILITIES } from './snapshot-quality-backend-capabilities.ts';

Expand Down Expand Up @@ -93,6 +94,15 @@ function readCustomActionCoverage(
};
}

/**
* Why `find` refuses a capture whose verdict is sparse. The daemon and command-runtime `find`
* paths both raise it; the runner's own wording moves to `details.verdictReason`.
*/
export const FIND_READ_REASONS = {
// The capture came back sparse, so no selector could be resolved against it.
snapshotUnreadable: { reason: 'find_snapshot_unreadable' },
} as const satisfies ReasonTable<'find'>;

export function isSparseSnapshotQualityVerdict(
verdict: SnapshotQualityVerdict | undefined,
): verdict is SnapshotQualityVerdict {
Expand Down
4 changes: 2 additions & 2 deletions packages/command-registry/src/batch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
import {
AppError,
asAppError,
BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON,
BOUNDED_COMPOSITE_REASONS,
type DaemonError,
} from '@agent-device/kernel/errors';
import { isRecord } from '@agent-device/kernel/record';
Expand Down Expand Up @@ -172,7 +172,7 @@ function batchStepFailure(
...(error.details ?? {}),
...(progress.executedSteps.some(stepMayMutateApp) &&
!(
error.details?.reason === BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON &&
error.details?.reason === BOUNDED_COMPOSITE_REASONS.resourceUnsupported.reason &&
error.details.dispatched === 'no'
)
? { dispatched: 'unknown' }
Expand Down
9 changes: 0 additions & 9 deletions packages/contracts/src/alert-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,6 @@ export const ALERT_ACTION_RETRY_MS = 2_000;
*/
export const MAX_ALERT_WINDOW_MS = 2_147_483_647;

/**
* `alert wait` was given a window longer than the command can honour. The request envelope is a
* timer too, and it is armed above the window with the daemon-result margin, so past that ceiling
* the wait would be cut off mid-window or misfire at 1 ms. The command refuses the window before
* anything runs, with `details.maxWaitWindowMs` naming what it will accept; it never shortens the
* window the caller asked for.
*/
export const ALERT_WAIT_WINDOW_TOO_LONG_REASON = 'alert-wait-window-too-long';

/**
* The one alert failure the family retries on: the backend looked and there was no alert *yet*.
* Both Apple backends state it in typed form — the XCTest runner as this `ErrorPayload.code`
Expand Down
25 changes: 15 additions & 10 deletions packages/contracts/src/device-inventory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
type DeviceTarget,
type PlatformSelector,
} from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
import { AppError, type ReasonTable } from '@agent-device/kernel/errors';

export const LOCAL_DEVICE_INVENTORY_PLATFORM_SELECTORS = [
'android',
Expand Down Expand Up @@ -107,19 +107,24 @@ function deviceInventoryGroupForDevice(device: DeviceInfo): DeviceInventoryGroup
* The refusal reasons a host-local device claim can answer with when another owner holds the
* device. Replay reads them to tell an infrastructure conflict from a script failure.
*/
export const DEVICE_CLAIM_CONFLICT_REASONS = {
// A live session in another workspace or daemon owns the device.
liveOwner: { reason: 'DEVICE_CLAIM_LIVE_OWNER' },
// The recorded owner is gone and its resources still need settling before the claim is released.
recoveryPending: { reason: 'DEVICE_CLAIM_RECOVERY_PENDING' },
// A claim exists, but its owner cannot be verified as live or gone.
ownerUncertain: { reason: 'DEVICE_CLAIM_OWNER_UNCERTAIN' },
} as const satisfies ReasonTable<'device claims'>;

export type DeviceClaimConflictReason =
| 'DEVICE_CLAIM_LIVE_OWNER'
| 'DEVICE_CLAIM_RECOVERY_PENDING'
| 'DEVICE_CLAIM_OWNER_UNCERTAIN';
(typeof DEVICE_CLAIM_CONFLICT_REASONS)[keyof typeof DEVICE_CLAIM_CONFLICT_REASONS]['reason'];

const DEVICE_CLAIM_CONFLICT_REASONS = new Set<DeviceClaimConflictReason>([
'DEVICE_CLAIM_LIVE_OWNER',
'DEVICE_CLAIM_RECOVERY_PENDING',
'DEVICE_CLAIM_OWNER_UNCERTAIN',
]);
const DEVICE_CLAIM_CONFLICT_REASON_VALUES = new Set<string>(
Object.values(DEVICE_CLAIM_CONFLICT_REASONS).map((row) => row.reason),
);

export function isDeviceClaimConflictReason(value: unknown): value is DeviceClaimConflictReason {
return DEVICE_CLAIM_CONFLICT_REASONS.has(value as DeviceClaimConflictReason);
return typeof value === 'string' && DEVICE_CLAIM_CONFLICT_REASON_VALUES.has(value);
}

/** A provider connection that has no live instance: none was allocated, or the last one ended. */
Expand Down
1 change: 1 addition & 0 deletions packages/contracts/src/facades/device.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export { assertResolvedAppsFilter, resolveAppsFilter } from '../app-inventory.ts
export type { AppsFilter } from '../app-inventory.ts';
export type { AppStateCommandResult } from '../app-state.ts';
export {
DEVICE_CLAIM_CONFLICT_REASONS,
LOCAL_DEVICE_INVENTORY_PLATFORM_SELECTORS,
WEB_DESKTOP_DEVICE,
countDeviceInventoryByGroup,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {
DAEMON_LIFECYCLE_REASONS,
DAEMON_SHUTTING_DOWN_REASON,
buildDaemonLifecycleRequest,
readDaemonLifecycleCensus,
type DaemonPaths,
Expand Down Expand Up @@ -98,7 +97,7 @@ function judgeRefusedAnswer(
}
if (
refusal.reason === DAEMON_LIFECYCLE_REASONS.instanceMismatch.reason ||
refusal.reason === DAEMON_SHUTTING_DOWN_REASON
refusal.reason === DAEMON_LIFECYCLE_REASONS.shuttingDown.reason
) {
return { outcome: 'gone' };
}
Expand Down
5 changes: 2 additions & 3 deletions packages/daemon-contracts/src/daemon-resolution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,9 +315,6 @@ export function readDaemonOwnership(value: unknown): DaemonOwnership {
/** Stop if idle: refuses while the detached daemon holds work. */
export const DAEMON_QUIESCE_COMMAND = 'daemon_quiesce';

/** The reason a daemon gives every request it refuses once it has begun to leave. */
export const DAEMON_SHUTTING_DOWN_REASON = 'daemon_shutting_down';

/** Why a daemon refuses a lifecycle request: one entry per rule the admission seam enforces. */
export const DAEMON_LIFECYCLE_REASONS = {
// The daemon still holds work, so it refused to leave; `details` counts that work.
Expand All @@ -326,6 +323,8 @@ export const DAEMON_LIFECYCLE_REASONS = {
instanceMismatch: { reason: 'daemon-instance-mismatch' },
// A live host process owns this daemon and ends it through its own `close()`.
ownerEmbedded: { reason: 'daemon-owner-embedded' },
// The daemon has begun to leave, so it refuses every new request; retry against a new daemon.
shuttingDown: { reason: 'daemon_shutting_down' },
} as const satisfies ReasonTable<'daemon lifecycle'>;

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
import fs from 'node:fs';
import { test } from 'vitest';
import { AppError } from '@agent-device/kernel/errors';
import { DAEMON_SHUTTING_DOWN_REASON } from '@agent-device/daemon-contracts/daemon-resolution';
import { DAEMON_LIFECYCLE_REASONS } from '@agent-device/daemon-contracts/daemon-resolution';
import {
makeSession,
makeRepairCompleteSession,
Expand Down Expand Up @@ -130,7 +130,9 @@ test('shutdown closes draft admission while allowing the current lifetime to set
store.closeAdmission();
assert.throws(
() => store.publish('late-draft', makeSession('late-draft')),
(error) => error instanceof AppError && error.details?.reason === DAEMON_SHUTTING_DOWN_REASON,
(error) =>
error instanceof AppError &&
error.details?.reason === DAEMON_LIFECYCLE_REASONS.shuttingDown.reason,
);
store.update(ref, { appName: 'Settled' });
assert.equal(store.requireCurrent(ref).appName, 'Settled');
Expand Down
10 changes: 8 additions & 2 deletions packages/daemon/src/core/daemon-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,20 @@ import {
isHostScopedDeviceOf,
type DeviceInfo,
} from '@agent-device/kernel/device';
import { AppError, isRequestCanceledError } from '@agent-device/kernel/errors';
import { AppError, isRequestCanceledError, type ReasonTable } from '@agent-device/kernel/errors';
import {
resolveDaemonPolicyCommandName,
type DaemonPolicy,
type DaemonPolicyCapability,
} from '@agent-device/daemon-contracts/daemon-policy-file';
import type { DaemonRequest } from './daemon-request.ts';

const DAEMON_POLICY_REASONS = {
// The daemon operator's policy denies this command, device, capability, or lease; `details.rule`
// names which.
denied: { reason: 'DAEMON_POLICY_DENIED' },
} as const satisfies ReasonTable<'daemon policy'>;

/**
* ADR 0029 enforcement: every request the daemon admits, including `batch` steps and `replay`
* actions, which re-enter request admission rather than the HTTP edge. The policy file itself is
Expand Down Expand Up @@ -181,7 +187,7 @@ function policyDenied(
): AppError {
return new AppError('UNAUTHORIZED', message, {
...details,
reason: 'DAEMON_POLICY_DENIED',
reason: DAEMON_POLICY_REASONS.denied.reason,
rule,
policyDigest: policy.digest,
retriable: false,
Expand Down
9 changes: 7 additions & 2 deletions packages/daemon/src/core/interactor-resolution.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { runtimeSlot } from '@agent-device/host-kit/runtime-slots';
import type { Interactor, RunnerContext } from '@agent-device/contracts/interactor-types';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
import { AppError, type ReasonTable } from '@agent-device/kernel/errors';

const INTERACTOR_RESOLUTION_REASONS = {
// This process never composed interactor resolution, so it cannot reach a device.
missing: { reason: 'interactor-resolution-missing' },
} as const satisfies ReasonTable<'daemon runtime'>;

/**
* Resolves the interactor that speaks to a device — the provider-owned one when a
Expand All @@ -22,7 +27,7 @@ const NO_INTERACTOR_RESOLUTION: InteractorResolution = {
'COMMAND_FAILED',
'Interactor resolution is not composed for this process.',
{
reason: 'interactor-resolution-missing',
reason: INTERACTOR_RESOLUTION_REASONS.missing.reason,
},
);
},
Expand Down
7 changes: 2 additions & 5 deletions packages/daemon/src/core/lease-context.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import type { DaemonRequest } from './daemon-request.ts';
import { getRequestExecutionDeadlineMs } from '@agent-device/host-kit/request';
import {
AppError,
BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON,
} from '@agent-device/kernel/errors';
import { AppError, BOUNDED_COMPOSITE_REASONS } from '@agent-device/kernel/errors';
import { INTERNAL_COMMANDS, PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog';
import { resolveCommandStandaloneProjection } from '@agent-device/command-registry/registry';
import type { LeaseBackend } from '@agent-device/kernel/contracts';
Expand All @@ -23,7 +20,7 @@ export type { LeaseScope };
export function refuseBoundedCompositeResourceOperation(req: DaemonRequest, shape: string): never {
const commandName = resolveCommandStandaloneProjection(req.command)?.command;
throw new AppError('UNSUPPORTED_OPERATION', `${shape} cannot run within a bounded composite`, {
reason: BOUNDED_COMPOSITE_RESOURCE_UNSUPPORTED_REASON,
reason: BOUNDED_COMPOSITE_REASONS.resourceUnsupported.reason,
shape,
...(commandName ? { standaloneCommandName: commandName } : {}),
hint: `Run the original ${commandName ?? 'refused'} operation separately with its original arguments and options, the same --session value, and the same private CLI context. Inspect completed steps before retrying the batch or replay.`,
Expand Down
31 changes: 22 additions & 9 deletions packages/daemon/src/core/ref-frame.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { SnapshotState } from '@agent-device/contracts/snapshot-model';
import type { ReasonTable } from '@agent-device/kernel/errors';
import {
expiredRefFrame,
issuedRefFrame,
Expand Down Expand Up @@ -37,11 +38,21 @@ const outdatedObservations = new WeakSet<SnapshotState>();
* Typed admission-failure reasons, evaluated in this order so the caller can
* distinguish "capture a complete snapshot" from "use the emitted pinned ref".
*/
export const REF_FRAME_REASONS = {
// A device action since the snapshot expired the ref frame, so a mutation using its refs is
// refused; a read that still has retained evidence answers with a staleness warning instead.
frameExpired: { reason: 'ref_frame_expired' },
// The pinned ref was minted from a snapshot generation that a newer one superseded.
generationMismatch: { reason: 'ref_generation_mismatch' },
// A plain ref needs a complete frame. Retry with the pinned ref in `details.suggestedRef` when
// present; otherwise capture a fresh interactive snapshot or use a stable selector.
plainRefRequiresCompleteFrame: { reason: 'plain_ref_requires_complete_frame' },
// The current ref frame did not issue this ref, so it no longer names a node.
notIssued: { reason: 'ref_not_issued' },
} as const satisfies ReasonTable<'ref frames'>;

export type RefFrameRejectReason =
| 'ref_frame_expired'
| 'ref_generation_mismatch'
| 'plain_ref_requires_complete_frame'
| 'ref_not_issued';
(typeof REF_FRAME_REASONS)[keyof typeof REF_FRAME_REASONS]['reason'];

export type RefFrameAdmission =
| { admitted: true }
Expand Down Expand Up @@ -225,20 +236,20 @@ export function admitRefMutation(params: {
const { session, refBody, mintedGeneration } = params;

if (refFrameState(session) === 'expired') {
return { admitted: false, reason: 'ref_frame_expired' };
return { admitted: false, reason: REF_FRAME_REASONS.frameExpired.reason };
}

if (mintedGeneration !== undefined && mintedGeneration !== refFrameEpoch(session)) {
return { admitted: false, reason: 'ref_generation_mismatch' };
return { admitted: false, reason: REF_FRAME_REASONS.generationMismatch.reason };
}

const scope = refFrameScope(session);
if (scope !== 'all') {
if (mintedGeneration === undefined) {
return { admitted: false, reason: 'plain_ref_requires_complete_frame' };
return { admitted: false, reason: REF_FRAME_REASONS.plainRefRequiresCompleteFrame.reason };
}
if (!scope.has(refBody)) {
return { admitted: false, reason: 'ref_not_issued' };
return { admitted: false, reason: REF_FRAME_REASONS.notIssued.reason };
}
}

Expand All @@ -253,6 +264,8 @@ export function admitRefMutation(params: {
*/
export function admitRefRead(session: SessionState, refBody: string): RefFrameAdmission {
const scope = refFrameScope(session);
if (scope !== 'all' && !scope.has(refBody)) return { admitted: false, reason: 'ref_not_issued' };
if (scope !== 'all' && !scope.has(refBody)) {
return { admitted: false, reason: REF_FRAME_REASONS.notIssued.reason };
}
return { admitted: true };
}
12 changes: 9 additions & 3 deletions packages/daemon/src/core/runtime-admission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
} from '@agent-device/contracts/platform-runtime';
import type { PlatformRuntimeOperations } from '@agent-device/contracts/platform-runtime-operations';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
import { AppError, type ReasonTable } from '@agent-device/kernel/errors';
import type {
BindDeviceRuntime,
InspectDeviceRuntimeFacts,
Expand All @@ -19,6 +19,12 @@ import type { DaemonCommandContext } from './context.ts';
import type { ResolvedGenericExecution } from './generic-leaf-execution.ts';
import { type DaemonFailureResponse, errorResponse } from '@agent-device/kernel/contracts';

export const RUNTIME_GATEWAY_REASONS = {
// The daemon was composed without the runtime gateway, admission ledger, or diagnostics service
// this command needs.
missing: { reason: 'runtime-gateway-missing' },
} as const satisfies ReasonTable<'daemon runtime'>;

/** Builds the failure a command reports when its exact device cell does not admit an operation. */
export type UnavailableRuntimeResponse = (
unavailable: RuntimeOperationUnavailability,
Expand Down Expand Up @@ -166,13 +172,13 @@ function requireFactsInspection(
): InspectDeviceRuntimeFacts {
if (inspectFacts) return inspectFacts;
throw new AppError('COMMAND_FAILED', 'Device runtime facts inspection is unavailable.', {
reason: 'runtime-gateway-missing',
reason: RUNTIME_GATEWAY_REASONS.missing.reason,
});
}

function requireDeviceBinding(bindDevice: BindDeviceRuntime | undefined): BindDeviceRuntime {
if (bindDevice) return bindDevice;
throw new AppError('COMMAND_FAILED', 'Device runtime binding is unavailable.', {
reason: 'runtime-gateway-missing',
reason: RUNTIME_GATEWAY_REASONS.missing.reason,
});
}
8 changes: 7 additions & 1 deletion packages/daemon/src/core/session-recovery-hints.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import type { ReasonTable } from '@agent-device/kernel/errors';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { shellQuoteIfNeeded } from '@agent-device/kernel/device-shell';
import type { SessionRef, SessionState } from './session-state.ts';
import { errorResponse, type DaemonFailureResponse } from '@agent-device/kernel/contracts';

const WORKSPACE_SESSION_REASONS = {
// A session in another workspace already uses the device; `details.session` names it.
scopeConflict: { reason: 'WORKSPACE_SESSION_SCOPE_CONFLICT' },
} as const satisfies ReasonTable<'sessions'>;

export type SessionRecoveryContext = 'device-in-use' | 'selector-conflict';

export type SessionRecoveryOptions = {
Expand Down Expand Up @@ -78,7 +84,7 @@ export function buildForeignWorkspaceSessionConflict(
'DEVICE_IN_USE',
`Device is already in use by workspace session "${inUse.address}".`,
{
reason: 'WORKSPACE_SESSION_SCOPE_CONFLICT',
reason: WORKSPACE_SESSION_REASONS.scopeConflict.reason,
session: inUse.address,
deviceId: device.id,
deviceName: device.name,
Expand Down
6 changes: 3 additions & 3 deletions packages/daemon/src/core/session-runtime-admission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { AppError } from '@agent-device/kernel/errors';
import type { BindDeviceRuntime, InspectDeviceRuntimeFacts } from './request-runtime-binding.ts';
import type { SessionStore } from './session-store.ts';
import type { DaemonRequest } from './daemon-request.ts';
import { unsupportedOperationResponse } from './runtime-admission.ts';
import { RUNTIME_GATEWAY_REASONS, unsupportedOperationResponse } from './runtime-admission.ts';

export type RuntimeCommandHandlerParams = Readonly<{
host: HostEnvironment;
Expand Down Expand Up @@ -41,7 +41,7 @@ export function requireRuntimeFacts(
): InspectDeviceRuntimeFacts {
if (inspectFacts) return inspectFacts;
throw new AppError('COMMAND_FAILED', 'Device runtime facts inspection is unavailable.', {
reason: 'runtime-gateway-missing',
reason: RUNTIME_GATEWAY_REASONS.missing.reason,
});
}

Expand Down Expand Up @@ -156,6 +156,6 @@ export function requireRuntimeBinding(
): BindDeviceRuntime {
if (bindDevice) return bindDevice;
throw new AppError('COMMAND_FAILED', 'Device runtime binding is unavailable.', {
reason: 'runtime-gateway-missing',
reason: RUNTIME_GATEWAY_REASONS.missing.reason,
});
}
Loading
Loading