Skip to content

Commit c7242f8

Browse files
authored
refactor: extract durable capture resource lifecycle (#1720)
1 parent 191d49c commit c7242f8

26 files changed

Lines changed: 1954 additions & 1064 deletions

‎docs/adr/0019-request-bound-platform-runtime.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,15 @@ contract handle beside its descriptor and metadata; the field has one R7 transit
304304
descriptor and neutral metadata enter the authoritative persisted recovery record. Concrete platform
305305
classes, provider clients, child handles, timers, transports, and wait promises enter neither store.
306306

307+
The daemon shares the lifecycle mechanics of those facet-specific resources through one
308+
`DurableCaptureResource` coordinator. It owns bounded manifest I/O, per-resource fence serialization,
309+
start/persist/adopt compensation, terminal transitions, and deadline-bounded exact-owner recovery.
310+
The coordinator receives a facet's resource kind and manifest store, neutral session slot, completion
311+
metadata projection, failure wording, and exact-owner recovery adapter; it does not select platforms,
312+
interpret command flags, or form a generic runtime facet. App-log and screen recording retain distinct handles,
313+
descriptors, facts, native finalization semantics, and admission policy. Reusable codec/live-handle
314+
mechanics below the daemon remain in `@agent-device/capture-kit`, preserving the package direction.
315+
307316
A daemon-owned, process-lifetime admission ledger may retain bounded cleanup uncertainty that has no
308317
honest durable representation, but it is not a second live-resource store: it contains no handle or
309318
descriptor, never supersedes the persisted manifest, and is keyed by canonical device identity when

‎src/daemon/__tests__/app-log-resource-store.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,25 @@ test.each([
3939
expect(fs.readFileSync(resourcePath, 'utf8')).toBe(body);
4040
});
4141

42+
test('malformed app-log records preserve the underlying decoder message', () => {
43+
const resourcePath = resolveAppLogResourcePath(
44+
path.join(mkdtempForTestSync('app-log-malformed-message-'), 'session'),
45+
);
46+
fs.mkdirSync(path.dirname(resourcePath), { recursive: true });
47+
fs.writeFileSync(resourcePath, '{');
48+
let expectedMessage = '';
49+
try {
50+
JSON.parse('{');
51+
} catch (error) {
52+
expectedMessage = error instanceof Error ? error.message : '';
53+
}
54+
55+
expect(readAppLogResourceRecord(resourcePath)).toMatchObject({
56+
status: 'unreattachable',
57+
message: expectedMessage,
58+
});
59+
});
60+
4261
test('app-log resource listing is deterministic and ignores unrelated artifacts', () => {
4362
const sessionsDir = mkdtempForTestSync('app-log-record-list-');
4463
for (const sessionName of ['zeta', 'alpha']) {
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { expect, test } from 'vitest';
2+
import type { DeviceInfo } from '@agent-device/kernel/device';
3+
import { createDurableCaptureAdmissionLedger } from '../durable-capture-admission-ledger.ts';
4+
5+
const device: DeviceInfo = {
6+
platform: 'android',
7+
id: 'ledger-device',
8+
name: 'Pixel',
9+
kind: 'emulator',
10+
};
11+
const otherDevice: DeviceInfo = {
12+
platform: 'android',
13+
id: 'other-device',
14+
name: 'Other Pixel',
15+
kind: 'emulator',
16+
};
17+
18+
test('blocks only the affected device in this process-lifetime ledger', () => {
19+
const ledger = createDurableCaptureAdmissionLedger({ displayName: 'Screen recording' });
20+
ledger.blockUndurableCleanup(device, 'cleanup could not be confirmed');
21+
expect(() => ledger.assertStartAllowed(device)).toThrow(/process-local/);
22+
expect(() => ledger.assertStartAllowed(otherDevice)).not.toThrow();
23+
expect(() =>
24+
createDurableCaptureAdmissionLedger({ displayName: 'Screen recording' }).assertStartAllowed(
25+
device,
26+
),
27+
).not.toThrow();
28+
});
29+
30+
test('expires bounded cleanup uncertainty and reports it once', () => {
31+
let now = 1_000;
32+
const expired: string[] = [];
33+
const ledger = createDurableCaptureAdmissionLedger({
34+
displayName: 'Screen recording',
35+
now: () => now,
36+
undurableCleanupTtlMs: 500,
37+
onUndurableCleanupExpired: ({ reason }) => expired.push(reason),
38+
});
39+
ledger.blockUndurableCleanup(device, 'cleanup could not be confirmed');
40+
expect(() => ledger.assertStartAllowed(device)).toThrow(/process-local/);
41+
now += 501;
42+
expect(() => ledger.assertStartAllowed(device)).not.toThrow();
43+
expect(expired).toEqual(['cleanup could not be confirmed']);
44+
expect(() => ledger.assertStartAllowed(device)).not.toThrow();
45+
});
46+
47+
test('clearing a device releases only its recorded uncertainty', () => {
48+
const ledger = createDurableCaptureAdmissionLedger({ displayName: 'Screen recording' });
49+
ledger.blockUndurableCleanup(device, 'first');
50+
ledger.blockUndurableCleanup(otherDevice, 'second');
51+
ledger.clearUndurableCleanup(device);
52+
expect(() => ledger.assertStartAllowed(device)).not.toThrow();
53+
expect(() => ledger.assertStartAllowed(otherDevice)).toThrow(/process-local/);
54+
});
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import { expect, test, vi } from 'vitest';
2+
import { createDurableResourceEnvelope } from '@agent-device/capture-kit';
3+
import { localRuntimeOwner, type AppLogLiveHandle } from '@agent-device/contracts/platform';
4+
import { createTestAppLogLiveHandle } from '../../__tests__/test-utils/app-log-live-handle.ts';
5+
import {
6+
acquireDurableCaptureRecoveryAuthorityBeforeDeadline,
7+
DurableCaptureRecoveryDeadlineError,
8+
} from '../durable-capture-recovery-authority.ts';
9+
10+
const envelope = createDurableResourceEnvelope({
11+
resourceKind: 'app-log',
12+
sessionId: 'session',
13+
device: { id: 'emulator-5554', family: 'android', kind: 'emulator' },
14+
owner: localRuntimeOwner('android'),
15+
fence: { token: 'fence', generation: 1 },
16+
lifecycle: 'open',
17+
descriptor: { version: 1, body: {} },
18+
});
19+
20+
test('deadline abort disposes authority that becomes active after the caller has timed out', async () => {
21+
vi.useFakeTimers();
22+
try {
23+
let resolveReattach!: (outcome: { status: 'active'; handle: AppLogLiveHandle }) => void;
24+
const forceCleanup = vi.fn(async () => ({ status: 'cleaned' }) as const);
25+
const disposeControl = vi.fn(async () => {});
26+
const cleanupFailures = vi.fn();
27+
const acquisition = acquireDurableCaptureRecoveryAuthorityBeforeDeadline({
28+
displayName: 'app-log',
29+
envelope,
30+
scope: {
31+
signal: new AbortController().signal,
32+
diagnostics: { emit: () => {} },
33+
progress: { report: () => {} },
34+
},
35+
deadlineMs: 25,
36+
acquireControl: async () => ({
37+
reattach: async () =>
38+
await new Promise<{ status: 'active'; handle: AppLogLiveHandle }>((resolve) => {
39+
resolveReattach = resolve;
40+
}),
41+
cleanup: async () => ({ status: 'already-missing' }),
42+
[Symbol.asyncDispose]: disposeControl,
43+
}),
44+
onLateCleanupFailure: cleanupFailures,
45+
});
46+
47+
const timedOut = expect(acquisition).rejects.toBeInstanceOf(
48+
DurableCaptureRecoveryDeadlineError,
49+
);
50+
await vi.advanceTimersByTimeAsync(25);
51+
await timedOut;
52+
53+
resolveReattach({
54+
status: 'active',
55+
handle: createTestAppLogLiveHandle({
56+
inspect: () => ({ backend: 'android', state: 'active', startedAt: 1 }),
57+
finish: async () => ({
58+
status: 'completed',
59+
alreadyCompleted: true,
60+
result: { backend: 'android', outputPath: '/tmp/app.log', completedAt: 1 },
61+
}),
62+
forceCleanup,
63+
}),
64+
});
65+
await vi.advanceTimersByTimeAsync(0);
66+
67+
expect(forceCleanup).toHaveBeenCalledOnce();
68+
expect(disposeControl).toHaveBeenCalledOnce();
69+
expect(cleanupFailures).not.toHaveBeenCalled();
70+
} finally {
71+
vi.useRealTimers();
72+
}
73+
});
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import fs from 'node:fs';
2+
import path from 'node:path';
3+
import { expect, test } from 'vitest';
4+
import { AppError } from '@agent-device/kernel/errors';
5+
import {
6+
makeDurableCaptureContext,
7+
makeDurableCaptureStartResult,
8+
testCaptureResource,
9+
testCaptureStore,
10+
} from './durable-capture-resource.fixtures.ts';
11+
12+
test('canceled adoption cleans the pending handle before terminalizing its manifest', async () => {
13+
const context = makeDurableCaptureContext();
14+
const start = makeDurableCaptureStartResult(context);
15+
const cancellation = new AppError('CANCELED', 'request canceled');
16+
17+
await expect(
18+
testCaptureResource.adoptStarted({
19+
...context,
20+
...start,
21+
throwIfCanceled: () => {
22+
throw cancellation;
23+
},
24+
}),
25+
).rejects.toBe(cancellation);
26+
expect(start.forceCleanup).toHaveBeenCalledOnce();
27+
expect(testCaptureStore.read(context.resourcePath)).toMatchObject({
28+
status: 'decoded',
29+
envelope: { lifecycle: 'completed', metadata: { phase: 'completed' } },
30+
});
31+
});
32+
33+
test('a failed terminal transition preserves the primary error and blocks replacement', async () => {
34+
const context = makeDurableCaptureContext();
35+
const start = makeDurableCaptureStartResult(context, {
36+
cleanup: { status: 'cleanup-pending', reason: 'cleanup-unconfirmed' },
37+
});
38+
const primary = new AppError('CANCELED', 'request canceled');
39+
const resourceDir = path.dirname(context.resourcePath);
40+
41+
try {
42+
await expect(
43+
testCaptureResource.adoptStarted({
44+
...context,
45+
...start,
46+
throwIfCanceled: () => {
47+
fs.chmodSync(resourceDir, 0o500);
48+
throw primary;
49+
},
50+
}),
51+
).rejects.toBe(primary);
52+
} finally {
53+
fs.chmodSync(resourceDir, 0o700);
54+
}
55+
56+
expect(() => context.admissionLedger.assertStartAllowed(context.device)).toThrow(/process-local/);
57+
});

src/daemon/__tests__/app-log-resource-fence.test.ts renamed to src/daemon/__tests__/durable-capture-resource-fence.test.ts

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,21 @@ import { expect, test, vi } from 'vitest';
33
import { localRuntimeOwner } from '@agent-device/contracts/platform';
44
import { createDurableResourceEnvelope } from '@agent-device/capture-kit';
55
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
6-
import { withAppLogResourceFence } from '../app-log-resource-fence.ts';
7-
import {
8-
readAppLogResourceRecord,
9-
resolveAppLogResourcePath,
10-
writeAppLogResourceRecord,
11-
} from '../app-log-resource-store.ts';
6+
import { withDurableCaptureResourceFence } from '../durable-capture-resource-fence.ts';
7+
import { createDurableCaptureResourceStore } from '../durable-capture-resource-store.ts';
128

13-
test('ownership fence rejects a stale token before the native side effect', async () => {
9+
const store = createDurableCaptureResourceStore({
10+
resourceKind: 'screen-recording',
11+
fileName: 'screen-recording.resource.json',
12+
displayName: 'Screen recording',
13+
});
14+
15+
test('rejects a stale fence before its side effect', async () => {
1416
const resourcePath = makeRecord();
1517
const sideEffect = vi.fn(async () => {});
1618
await expect(
17-
withAppLogResourceFence({
19+
withDurableCaptureResourceFence({
20+
store,
1821
resourcePath,
1922
expected: { token: 'stale', generation: 1 },
2023
run: sideEffect,
@@ -23,29 +26,31 @@ test('ownership fence rejects a stale token before the native side effect', asyn
2326
expect(sideEffect).not.toHaveBeenCalled();
2427
});
2528

26-
test('ownership fence serializes validation, side effect, and persisted transition', async () => {
29+
test('serializes validation, native work, and transition for one resource path', async () => {
2730
const resourcePath = makeRecord();
2831
const order: string[] = [];
29-
let releaseFirst!: () => void;
30-
let markFirstStarted!: () => void;
32+
let release!: () => void;
33+
let started!: () => void;
3134
const firstStarted = new Promise<void>((resolve) => {
32-
markFirstStarted = resolve;
35+
started = resolve;
3336
});
3437
const firstReleased = new Promise<void>((resolve) => {
35-
releaseFirst = resolve;
38+
release = resolve;
3639
});
37-
const first = withAppLogResourceFence({
40+
const first = withDurableCaptureResourceFence({
41+
store,
3842
resourcePath,
3943
expected: { token: 'current', generation: 1 },
4044
run: async (lease) => {
4145
order.push('first-start');
42-
markFirstStarted();
46+
started();
4347
await firstReleased;
4448
lease.transition('open', { metadata: { phase: 'completing' } });
4549
order.push('first-end');
4650
},
4751
});
48-
const second = withAppLogResourceFence({
52+
const second = withDurableCaptureResourceFence({
53+
store,
4954
resourcePath,
5055
expected: { token: 'current', generation: 1 },
5156
run: async () => {
@@ -54,23 +59,23 @@ test('ownership fence serializes validation, side effect, and persisted transiti
5459
});
5560
await firstStarted;
5661
expect(order).toEqual(['first-start']);
57-
releaseFirst();
62+
release();
5863
await Promise.all([first, second]);
5964
expect(order).toEqual(['first-start', 'first-end', 'second']);
60-
expect(readAppLogResourceRecord(resourcePath)).toMatchObject({
65+
expect(store.read(resourcePath)).toMatchObject({
6166
status: 'decoded',
62-
envelope: { lifecycle: 'open', metadata: { phase: 'completing' } },
67+
envelope: { metadata: { phase: 'completing' } },
6368
});
6469
});
6570

6671
function makeRecord(): string {
67-
const resourcePath = resolveAppLogResourcePath(
68-
path.join(mkdtempForTestSync('app-log-fence-'), 'session'),
72+
const resourcePath = store.resolvePath(
73+
path.join(mkdtempForTestSync('capture-fence-'), 'session'),
6974
);
70-
writeAppLogResourceRecord(
75+
store.write(
7176
resourcePath,
7277
createDurableResourceEnvelope({
73-
resourceKind: 'app-log',
78+
resourceKind: 'screen-recording',
7479
sessionId: 'session',
7580
device: { id: 'emulator-5554', family: 'android', kind: 'emulator' },
7681
owner: localRuntimeOwner('android'),
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import path from 'node:path';
2+
import { expect, test, vi } from 'vitest';
3+
import { createDurableResourceEnvelope } from '@agent-device/capture-kit';
4+
import { localRuntimeOwner } from '@agent-device/contracts/platform';
5+
import { makeSessionStore } from '../../__tests__/test-utils/store-factory.ts';
6+
import { appLogDurableResource } from '../app-log-session-resource.ts';
7+
8+
test('generic recovery terminalizes missing native authority through one exact control', async () => {
9+
const sessionStore = makeSessionStore('durable-capture-recovery-');
10+
const sessionsDir = path.dirname(sessionStore.resolveSessionDir('session'));
11+
const resourcePath = appLogDurableResource.store.resolvePath(
12+
sessionStore.resolveSessionDir('session'),
13+
);
14+
appLogDurableResource.store.write(
15+
resourcePath,
16+
createDurableResourceEnvelope({
17+
resourceKind: 'app-log',
18+
sessionId: 'session',
19+
device: { id: 'emulator-5554', family: 'android', kind: 'emulator' },
20+
owner: localRuntimeOwner('android'),
21+
fence: { token: 'fence', generation: 1 },
22+
lifecycle: 'open',
23+
descriptor: { version: 1, body: { pid: 123 } },
24+
}),
25+
);
26+
const dispose = vi.fn(async () => {});
27+
28+
await expect(
29+
appLogDurableResource.recoverAll({
30+
sessionsDir,
31+
scope: {
32+
signal: new AbortController().signal,
33+
diagnostics: { emit: () => {} },
34+
progress: { report: () => {} },
35+
},
36+
acquireControl: async () => ({
37+
reattach: async () => ({ status: 'missing' }),
38+
cleanup: async () => ({ status: 'already-missing' }),
39+
[Symbol.asyncDispose]: dispose,
40+
}),
41+
}),
42+
).resolves.toEqual({ scanned: 1, recovered: 1, retained: 0 });
43+
expect(dispose).toHaveBeenCalledOnce();
44+
expect(appLogDurableResource.store.read(resourcePath)).toMatchObject({
45+
status: 'decoded',
46+
envelope: {
47+
lifecycle: 'completed',
48+
metadata: { phase: 'completed', recoveryStatus: 'already-missing' },
49+
},
50+
});
51+
});

0 commit comments

Comments
 (0)