Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
76af116
fix: bind retained artifacts and uploads to lease ownership
thymikee Nov 30, 2026
11218ff
fix: preserve retained recording ownership checks
thymikee Nov 30, 2026
5ed6cfa
fix: admit upload and artifact reads through lease ownership
thymikee Nov 30, 2026
2a473b8
fix: forward lease scope for retained artifact reads
thymikee Nov 30, 2026
c066be4
fix: prune retained lease owners and guide artifact scope
thymikee Nov 30, 2026
1f2dc7a
fix: require run scope for leased uploads
thymikee Nov 30, 2026
a85d6aa
fix: align artifact docs and focused tests with repo guards
thymikee Nov 30, 2026
16637a3
fix: distinguish missing artifact run from ownership refusal
thymikee Nov 30, 2026
8215e4f
fix: document artifact reasons and expect missing-run refusal
thymikee Nov 30, 2026
ee18219
fix: align artifact lease admission and protocol boundary
thymikee Dec 1, 2026
afbd8e2
fix: align protocol fixtures and generated reasons
thymikee Dec 1, 2026
6b702ac
fix: canonicalize lease IDs across artifact owners
thymikee Dec 1, 2026
d132b4a
fix: admit artifact uploads for scoped proxy leases
thymikee Dec 1, 2026
73e4c1b
fix: load lease normalization only for materialized paths
thymikee Dec 1, 2026
66838f9
fix: close lease artifact ownership review gaps
thymikee Dec 1, 2026
229bccd
fix: keep lease regressions within test gates
thymikee Dec 1, 2026
f8b5b23
style: format lease artifact review fixes
thymikee Dec 1, 2026
81c9003
test: assert leased recording access in tenant capture fixture
thymikee Dec 1, 2026
4c1a01a
fix(daemon): reuse the effective lease for source installs
thymikee Dec 1, 2026
9a4e60c
fix(daemon): preserve lease scope through artifact delivery and release
thymikee Dec 1, 2026
f9e6d8f
fix: align lease artifact admission and upload scope
thymikee Dec 1, 2026
93251c2
test(daemon): align lease and recording fixtures with their contracts
thymikee Dec 1, 2026
9ddbd09
fix(daemon): normalize empty tenant for unleased recording recovery
thymikee Dec 2, 2026
b2f9ffe
fix(daemon): require a tenant owner before leased recording
thymikee Dec 2, 2026
b020619
fix(daemon): validate recording ownership at start admission
thymikee Dec 2, 2026
1d90912
fix(artifacts): normalize recording owner and document historical lookup
thymikee Dec 2, 2026
d29aea5
test(artifacts): use a mutable daemon response fixture
thymikee Dec 2, 2026
6a00dd9
fix(leases): prune retained artifact owners during expiry sweeps
thymikee Dec 2, 2026
71aede7
fix(artifacts): preserve explicit lookup scope and empty lease absence
thymikee Dec 2, 2026
422c807
fix: keep artifact scope within CLI and test limits
thymikee Dec 2, 2026
f8a376b
test(cli): expect artifacts in command dispatch checks
thymikee Dec 2, 2026
dba25f7
fix(cli): preserve operator scope for historical artifacts
thymikee Dec 2, 2026
bfdf5ce
test(cli): follow artifact command check into option resolution
thymikee Dec 2, 2026
8d5cf14
fix(cli): restore provider artifact scope for named connections
thymikee Dec 2, 2026
46a98d5
refactor(cli): separate artifact run scope resolution
thymikee Dec 2, 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
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,36 @@ test('a completed manifest with no surviving video serves nothing', async () =>
await completeRecording(harness);
fs.rmSync(harness.videoPath);

expect(resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE })).toEqual(
{ kind: 'none' },
);
expect(
await resolveScreenRecordingStopRecovery({
...harness.params,
device: SESSION_DEVICE,
owner: {},
}),
).toEqual({ kind: 'none' });
});

test('a completed manifest hands back the whole stop response it stored', async () => {
const harness = makeHarness();
const completion = fullCompletion(harness.videoPath);
fs.writeFileSync(harness.videoPath, 'mp4');
writeManifest(harness, encodeScreenRecordingCompletionMetadata(completion));
const owner = { tenantId: 'tenant', leaseId: 'producing-lease' };
writeManifest(harness, {
...encodeScreenRecordingCompletionMetadata(completion),
remoteCaptureTenantId: owner.tenantId,
remoteCaptureLeaseId: owner.leaseId,
});

expect(resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE })).toEqual(
{ kind: 'completed', completion },
);
expect(
await resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner }),
).toEqual({ kind: 'completed', completion });
await expect(
resolveScreenRecordingStopRecovery({
...harness.params,
device: SESSION_DEVICE,
owner: { ...owner, leaseId: 'other-lease' },
}),
).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
expect(screenRecordingManifestIsTerminal(harness.params)).toBe(true);
});

Expand All @@ -70,7 +86,11 @@ test('a completed manifest whose stored response is damaged serves nothing', asy
for (const damaged of damages) {
writeManifest(harness, withStoredCompletion(stored, damaged));
expect(
resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE }),
await resolveScreenRecordingStopRecovery({
...harness.params,
device: SESSION_DEVICE,
owner: {},
}),
).toEqual({ kind: 'none' });
}
});
Expand All @@ -80,19 +100,23 @@ test('a completed manifest with no completion metadata serves nothing', async ()
await completeRecording(harness);
writeManifest(harness, { phase: 'completed' });

expect(resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE })).toEqual(
{ kind: 'none' },
);
expect(
await resolveScreenRecordingStopRecovery({
...harness.params,
device: SESSION_DEVICE,
owner: {},
}),
).toEqual({ kind: 'none' });
});

test('a completed manifest owned by another session is refused', async () => {
const harness = makeHarness();
await completeRecording(harness);
writeManifest(harness, undefined, { sessionId: 'other-session' });

expect(() =>
resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE }),
).toThrowError(expect.objectContaining({ details: { reason: 'runtime-contract-invalid' } }));
await expect(
resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }),
).rejects.toMatchObject({ details: { reason: 'runtime-contract-invalid' } });
});

test('a completed manifest bound to another device is refused', async () => {
Expand All @@ -102,27 +126,35 @@ test('a completed manifest bound to another device is refused', async () => {
device: deviceIdentity({ ...SESSION_DEVICE, id: 'emulator-5556' }),
});

expect(() =>
resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE }),
).toThrowError(expect.objectContaining({ details: { reason: 'runtime-contract-invalid' } }));
await expect(
resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE, owner: {} }),
).rejects.toMatchObject({ details: { reason: 'runtime-contract-invalid' } });
});

test('an open manifest stays available for exact-owner recovery', async () => {
const harness = makeHarness();
writeManifest(harness, { phase: 'active' }, { lifecycle: 'open' });

expect(resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE })).toEqual(
{ kind: 'open', resourcePath: manifestPath(harness.sessionStore) },
);
expect(
await resolveScreenRecordingStopRecovery({
...harness.params,
device: SESSION_DEVICE,
owner: {},
}),
).toEqual({ kind: 'open', resourcePath: manifestPath(harness.sessionStore) });
expect(screenRecordingManifestIsTerminal(harness.params)).toBe(false);
});

test('a session with no recording manifest has nothing to recover', () => {
test('a session with no recording manifest has nothing to recover', async () => {
const harness = makeHarness();

expect(resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE })).toEqual(
{ kind: 'none' },
);
expect(
await resolveScreenRecordingStopRecovery({
...harness.params,
device: SESSION_DEVICE,
owner: {},
}),
).toEqual({ kind: 'none' });
expect(screenRecordingManifestIsTerminal(harness.params)).toBe(false);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,25 @@ type ScreenRecordingManifestParams = Readonly<{
sessionStore: Readonly<{ resolveSessionDir(name: string): string }>;
}>;

export function resolveScreenRecordingStopRecovery(
params: ScreenRecordingManifestParams & Readonly<{ device: DeviceInfo }>,
): ScreenRecordingStopRecovery {
export async function resolveScreenRecordingStopRecovery(
params: ScreenRecordingManifestParams &
Readonly<{
device: DeviceInfo;
owner: Readonly<{ tenantId?: string; leaseId?: string }>;
}>,
): Promise<ScreenRecordingStopRecovery> {
const { resourcePath, record } = readSessionManifest(params);
if (record.status !== 'decoded') return { kind: 'none' };
assertManifestBelongsToRequest(params, record.envelope);
if (
record.envelope.metadata?.remoteCaptureTenantId !== params.owner.tenantId ||
record.envelope.metadata?.remoteCaptureLeaseId !== params.owner.leaseId
) {
const { LEASE_REASONS } = await import('@agent-device/contracts/lease-scope');
throw new AppError('UNAUTHORIZED', 'Screen recording belongs to a different tenant or lease', {
reason: LEASE_REASONS.scopeMismatch.reason,
Comment thread
thymikee marked this conversation as resolved.
Resolved
});
}
Comment thread
thymikee marked this conversation as resolved.
Resolved
if (record.envelope.lifecycle !== 'completed') return { kind: 'open', resourcePath };
const completion = readReplayableStoredCompletion(record.envelope.metadata);
if (completion === undefined) {
Expand Down
23 changes: 23 additions & 0 deletions packages/command-surface/src/management/artifacts.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import assert from 'node:assert/strict';
import { test } from 'vitest';
import { artifactsCommandFacet } from './artifacts.ts';
import type { CliFlags } from '@agent-device/contracts/command';
import { createTestHostEnvironment } from '@agent-device/test-kit';

test('artifacts CLI passes an explicit lease and run through to the daemon command', async () => {
const input = artifactsCommandFacet.cliReader([], {
Comment thread
thymikee marked this conversation as resolved.
Resolved
leaseId: 'lease-a',
runId: 'run-a',
} as CliFlags);
assert.equal(input.leaseId, 'lease-a');
assert.equal(input.runId, 'run-a');
const request = await artifactsCommandFacet.daemonWriter(input, createTestHostEnvironment());
assert.equal(request.options.leaseId, 'lease-a');
assert.equal(request.options.runId, 'run-a');
assert.deepEqual(artifactsCommandFacet.cliSchema.allowedFlags, [
'provider',
'providerSessionId',
'leaseId',
'runId',
]);
});
6 changes: 4 additions & 2 deletions packages/command-surface/src/management/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,15 @@ const artifactsCommandMetadata = defineFieldCommandMetadata(

const artifactsCliSchema = {
usageOverride: 'artifacts [provider-session-id]',
usageFlags: ['provider'],
usageFlags: ['provider', 'leaseId', 'runId'],
positionalArgs: ['provider-session-id?'],
allowedFlags: ['provider', 'providerSessionId'],
allowedFlags: ['provider', 'providerSessionId', 'leaseId', 'runId'],
} as const satisfies CommandSchemaOverride;

const artifactsCliReader: CliReader = (positionals, flags) => ({
...commonInputFromFlags(flags),
runId: flags.runId,
leaseId: flags.leaseId,
provider: flags.provider,
providerSessionId: positionals[0] ?? flags.providerSessionId,
});
Expand Down
1 change: 1 addition & 0 deletions packages/command-surface/src/recording/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ export const recordCommandFacet = defineCommandFacet({
summary: 'Start or stop screen recording',
searchHint: 'mp4',
cliDetail:
'A leased recording requires a tenant owner before it can start. ' +
'MP4 verification setup starts in the background before recording output preparation, without delaying capture. If setup exceeds the stop budget, details.reason is video_validator_compile_timeout (retriable); run record stop again while setup continues. Hosts without xcrun keep container-only MP4 completion. Other compilation failures, or an unavailable validator executable or AVFoundation during verification, return video_validator_unavailable. A Swift helper cache that is not private to this user returns swift_cache_untrusted. When details.ancestor is the configured cache root or a directory above it that the group or other users can write, remove that write access (chmod g-w,o-w) from that directory. When it is v3 or a directory inside it (bin, home or module-cache), do not chmod it: that clears the refusal but keeps whatever was written while it was open. Set AGENT_DEVICE_SWIFT_CACHE_DIR to a new directory only you can write, or remove that directory yourself; agent-device never deletes it. When details.exposure is untrusted_developer_dir, the DEVELOPER_DIR selection is refused; it is checked only when a Swift helper compiles, and a cached helper is reused without checking it: restart the daemon with DEVELOPER_DIR unset, or set DEVELOPER_DIR to an empty value for one local command to select the system default, or point it at an Xcode Contents/Developer directory, given as an absolute path, that root or you own along with every directory above it. Repair the reported failure and retry record stop; a failed compile is retried on the next start or stop. The default --scope app requires an active app session from open <app>; use --scope device/system to explicitly request whole-screen recording where the selected backend supports it. Android record start publishes a durable device manifest, recordings longer than the 180s adb screenrecord limit are returned as multiple MP4 chunks while the daemon stays alive, and daemon-restart recovery uses only manifest-owned chunks. An Android recorder the device refuses at startup returns COMMAND_FAILED with reason android_screenrecord_startup_failed, and details.stderr carries the message the native recorder printed. That message is the verdict of the device policy, so report it to the device manufacturer; agent-device has no alternative Android recording backend. Android screenrecord encodes a frame only when the screen changes, so a clip can end at the last frame the recorder encoded instead of at record stop; durationMs is host wall clock from record start until the export finished, and capturedDurationMs reports the video timeline when it can be measured, with a warning naming how much of the window that video covers. An Android manifest left by an unreachable recording is retired on the next start once its recorders are proven gone; one still owned refuses with non-retriable DEVICE_IN_USE and reason native_recovery_evidence_open naming the session to run record stop for, and a recorder that is still writing an artifact refuses with DEVICE_IN_USE and reason native_recording_artifact_claimed, which clears itself once that recorder ends at the 180s limit. HarmonyOS supports whole-screen recording on physical devices only: use --scope device/system; --fps, --quality, and --hide-touches are unsupported. If a HarmonyOS export goes missing or becomes unreadable while cleanup is pending, retry record stop in the same session to recover it from the device. If stop reports manual-recovery-required, recover the recording before retrying. Use --quality to choose medium or high export quality on supported backends. The touch overlay renders at most 30 frames a second, or at --fps when lower; a lower --fps makes record stop faster on a long recording, and an overlay export that runs past its budget returns the raw video with an overlayWarning. A watchOS simulator records the same way an iOS simulator does: the host runs simctl recordVideo, so the watch needs no runner recorder and the export keeps the resolution of the watch. An iOS simulator host recording lock returns non-retriable DEVICE_IN_USE with reason apple_simulator_recording_busy. Stop the recording in its owning session; if a dead recorder left the host locked, ask the host operator to restart the CoreSimulator stream service. A physical iPhone or iPad on a USB cable of this Mac records the USB screen-capture source of the device near 60 fps when both recording transports belong to this host; otherwise it records runner screenshots (help physical-device). A USB capture recording learns the capture source of a device when every other device with its name has a learned source and the store in ~/.agent-device can be written, and later recordings of that device open that source while it has the device name, and otherwise match by name; only a newer exact match replaces what was learned. When USB capture cannot record, before its first frame, the runner records instead and recorderFallbackReason names why: ios_usb_capture_camera_access_not_authorized (agent-device never asks for camera access), ios_usb_capture_device_name_shared (no capture source is learned for the device, and another Apple device in the inventory of the daemon, cabled or wireless, that has no learned source, or another USB capture source on this Mac that is not learned for another device, has the name, or the inventory could not be read), ios_usb_capture_source_of_another_device (no capture source is learned for the device, and another device learned the capture source that matched its name while it started), ios_usb_capture_device_not_found (neither the source learned for the device nor a source with the device name appeared; the learned source is kept), ios_usb_capture_no_frames (screen asleep or locked), or ios_usb_capture_start_busy (another USB capture recording on this Mac, of any user, held the host-wide start lock). USB capture fails the start with ios_usb_capture_start_lock_unusable (another account owns the start lock file and does not let this user read it). On any backend, record start first settles the open recording records on its device that it would refuse on and whose session this daemon no longer holds: it finishes each one as its own record stop would, so the export lands at the output path of that recording and a later record stop in that session returns it, and runs the exact-owner recovery a daemon restart runs, which discards what that recording left, only for a record that cannot finish. A record it cannot confirm cleaned, or one whose session is still held, refuses the start with reason cleanup-unconfirmed and names that session: stop or close it, then retry. A record that another device left under the same session name is never settled from this device: the start refuses and names that device, so stop it in that session or record under another session name. A record stop that cannot produce its export keeps what a retry reads back — on Android the device-side artifact and the native manifest — leaves the recording manifest of that session open, and returns its own error, so retry record stop in that session; while this daemon holds that session, only closing it disposes them, and once it does not, the next record start on that device settles them as described above. Every stopped recording also reports what became of its recorder and of the file that recorder writes to: recorder is confirmed, or lost when the session holding it died, and nativePathDisposition is retirable while that file still owes a removal or retired once its removal was verified. Both are optional disclosures, not failures; ADR 0024 declares further states (unconfirmed, pending) for the steps that gain those probes, and no stop reports them yet. record contact-sheet <video.mp4> [--out <sheet.png>] is a local report over a file you already exported: it decodes frames out of that MP4 and writes one PNG holding the cells where the screen visibly changed, each labeled with its elapsed time on the clip timeline. It needs no session and no device, rebuilds any past recording, and works for every backend that exports MP4; a WebM recording is refused with reason contact_sheet_container_unsupported. The sample grid is bounded and spread across the whole clip, so it reports coverage rather than a review: a flash that opens and closes entirely between two sample times is not in the sheet, which is why the result also reports how many times it sampled and how many frames came back. Frame decoding is Apple AVFoundation tooling, so the command runs only on macOS hosts and refuses elsewhere with reason contact_sheet_unsupported_host.',
},
metadata: recordCommandMetadata,
Expand Down
13 changes: 10 additions & 3 deletions packages/contracts/src/daemon-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ import type { ReasonTable } from '@agent-device/kernel/errors';
export const DAEMON_HTTP_BASE_PATH = '/agent-device';
export const DAEMON_HTTP_TENANT_HEADER = 'x-agent-device-tenant';
// Names the lease a non-RPC request (upload, artifact download, request diagnostics) belongs to,
// as RPC calls name it in their body. Neither the daemon nor the proxy reads it; it lets a gateway
// in front of many daemons route those requests to the one holding the lease.
// as RPC calls name it in their body. The daemon reads it for lease admission and a gateway
// can route the request to the daemon holding the lease. The header is caller-declared.
export const DAEMON_HTTP_LEASE_HEADER = 'x-agent-device-lease-id';
export const DAEMON_HTTP_RUN_HEADER = 'x-agent-device-run-id';
Comment thread
thymikee marked this conversation as resolved.
Resolved
export const DAEMON_HTTP_NETWORK_ACCESS_HEADER = 'x-agent-device-network-access';
export const DAEMON_HTTP_PUBLIC_NETWORK_ACCESS = 'public-only';

Expand Down Expand Up @@ -120,11 +121,17 @@ export function buildDaemonHttpLeaseHeaders(leaseId: string | undefined): Record
return { [DAEMON_HTTP_LEASE_HEADER]: normalizedLeaseId };
}

export function buildDaemonHttpRunHeaders(runId: string | undefined): Record<string, string> {
const normalizedRunId = runId?.trim();
if (!normalizedRunId) return {};
return { [DAEMON_HTTP_RUN_HEADER]: normalizedRunId };
}

// See docs/adr/0006-daemon-rpc-protocol-version.md before changing this value.
// Enforced, not just documented: `test/wire-compat/` digests the declarations
// that cross this boundary and fails when one changes shape without a bump or
// an acknowledged-compatible entry (#1432).
export const DAEMON_RPC_PROTOCOL_VERSION = 3;
export const DAEMON_RPC_PROTOCOL_VERSION = 4;

/**
* The largest serialized daemon request, in UTF-8 bytes, that any transport reads: the socket
Expand Down
3 changes: 2 additions & 1 deletion packages/contracts/src/lease-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,11 @@ type LeaseOptionsLike = {
};

export function leaseScopeFromRequest(req: LeaseRequestLike): LeaseScope {
const leaseId = (req.meta?.leaseId ?? readFlagString(req.flags, 'leaseId')) || undefined;
return stripUndefined({
tenantId: req.meta?.tenantId ?? readFlagString(req.flags, 'tenant'),
runId: req.meta?.runId ?? readFlagString(req.flags, 'runId'),
leaseId: req.meta?.leaseId ?? readFlagString(req.flags, 'leaseId'),
leaseId: normalizeLeaseId(leaseId) ?? leaseId,
leaseTtlMs: req.meta?.leaseTtlMs,
leaseRetainOnClose: req.meta?.leaseRetainOnClose,
leaseBackend: req.meta?.leaseBackend,
Expand Down
Loading
Loading