Skip to content

Commit 871ce1b

Browse files
thymikeeclaude
andauthored
refactor(daemon): normalize lifecycle participation of platform resource owners (callstack#2415)
* refactor(daemon): typed lifecycle participation for platform resource owners daemon-runtime.ts no longer imports the Apple runner owner, the Android snapshot-helper/Web orphan cleanups, or the app-log legacy marker recovery directly. Those are now behind PlatformOwnerLifecycle, a typed startup/shutdown surface owned by the daemon; the root composition module platform-runtime-daemon-lifecycle.ts is the sole place that wires the concrete platform owners into it. Reclassifies the R76 daemon-platform-runtime-inventory edges accordingly: the leaked apple-runner-owner and operation-host edges are removed, and resource-cleanup/daemon-lifecycle stay as composition-essential. Closes callstack#2333 Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017oNQ8THHYFcK7NX1s78kW5 * style: apply oxfmt formatting to R76 inventory test fixtures Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017oNQ8THHYFcK7NX1s78kW5 * test(daemon): update source-ordering assertion for the renamed call site daemon-runtime.ts now calls platformDaemonLifecycleOwners.recoverLegacyAppLogMarkers instead of the old recoverLegacyAppLogMarkersAfterDaemonLock dynamic import; the text-based ordering guard needs to look for the new call site. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017oNQ8THHYFcK7NX1s78kW5 * docs(adr): record callstack#2333 as landed in ADR 0022 The registry (DAEMON_PLATFORM_RUNTIME_EDGES) already reflects the retired apple-runner-owner/operation-host edges; update the ADR prose to match instead of leaving callstack#2333 listed as outstanding work. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017oNQ8THHYFcK7NX1s78kW5 * fix(daemon): configure the Apple runner owner only after the daemon lock is held configureForDaemonLock ran before acquireDaemonLock, which meant a process that lost the lock race briefly published a global runner-owner state dir and claim-authority probe it didn't own. Move the call inside the post-lock try block (verified nothing reads the runner-owner state before request time — runner-host.ts only captures getter closures) and drop the now-unreachable clear call on the lock-failure branch. Adds a source-order regression test pinning the new sequence. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_017oNQ8THHYFcK7NX1s78kW5 --------- Co-authored-by: Claude <[email protected]>
1 parent fda41b4 commit 871ce1b

7 files changed

Lines changed: 169 additions & 92 deletions

‎docs/adr/0022-daemon-platform-runtime-coupling.md‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,13 @@ or owning issue. #2278 audited all four concerns at `27a97ee619`.
4747
device refresh, and open-hint policy. Root composition supplies request-local inventory
4848
and its error classifier; `packages/platform-apple` owns the probes. The three consumers
4949
are daemon-policy-essential. Selector production and lifecycle participation stay separate.
50-
- **#2333** — lifecycle participation of platform resource owners
51-
(`daemon-runtime.ts` → `platform-runtime-apple-runner-owner.ts`,
52-
`platform-runtime-resource-cleanup.ts`, and the dynamic
53-
`platform-runtime-operation-host.ts` import).
50+
- **#2333 (done)** — lifecycle participation of platform resource owners. The
51+
`apple-runner-owner` and `operation-host` edges are retired; `daemon-runtime.ts` now holds
52+
only the typed `PlatformOwnerLifecycle` contract (`src/daemon/platform-owner-lifecycle.ts`),
53+
composed at the root by `platform-runtime-daemon-lifecycle.ts`, which is the sole importer of
54+
the Apple runner owner, the Android snapshot-helper and Web orphan cleanups, and legacy
55+
app-log marker recovery. The `resource-cleanup` edge stays, reclassified
56+
composition-essential and carrying only `platformResourceCleanup`.
5457
- **#2334** — open-target planning separated from platform mechanics
5558
(`session-open-prepare.ts`, `session-selector-dispatch.ts` →
5659
`platform-runtime-open-target.ts`), blocked by #2332.
@@ -117,5 +120,5 @@ or owning issue. #2278 audited all four concerns at `27a97ee619`.
117120
`scripts/layering/check.ts` (both observed red against planted violations before acceptance).
118121
- R7 `session-state-ownership` and the R10 merge-base ratchet for the owning-module slice.
119122
- R65 for the concrete-platform-import ban this audit builds on.
120-
- Child issues #2333, #2334 (and #2273/#2274 for the selector seam) for the remaining category-3
121-
implementation work.
123+
- Child issue #2334 (and #2273/#2274 for the selector seam) for the remaining category-3
124+
implementation work; #2333 landed (see §2.2).

‎scripts/layering/daemon-platform-runtime-inventory.test.ts‎

Lines changed: 30 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -100,61 +100,58 @@ test('R76 rejects new symbols on a classified edge', () => {
100100

101101
test('R76 matches a destructured dynamic import by target with the recorded bindings', () => {
102102
const sources = {
103-
'src/platform-runtime-operation-host.ts':
104-
'export async function recoverLegacyAppLogMarkersAfterDaemonLock() { return {}; }\n',
103+
'src/platform-runtime-daemon-lifecycle.ts':
104+
'export const platformDaemonLifecycleOwners = {};\n',
105105
'src/daemon/server/daemon-runtime.ts':
106-
"const { recoverLegacyAppLogMarkersAfterDaemonLock } = await import('../../platform-runtime-operation-host.ts');\n" +
107-
'void recoverLegacyAppLogMarkersAfterDaemonLock;\n',
106+
"const { platformDaemonLifecycleOwners } = await import('../../platform-runtime-daemon-lifecycle.ts');\n" +
107+
'void platformDaemonLifecycleOwners;\n',
108108
};
109109
assert.deepEqual(edgeViolations(sources, 'src/daemon/server/daemon-runtime.ts'), []);
110110
});
111111

112112
test('R76 rejects an expanded destructured dynamic import on a classified edge', () => {
113113
const sources = {
114-
'src/platform-runtime-operation-host.ts':
115-
'export async function recoverLegacyAppLogMarkersAfterDaemonLock() { return {}; }\n' +
116-
'export async function extraLegacyMarkerSweep() { return {}; }\n',
114+
'src/platform-runtime-daemon-lifecycle.ts':
115+
'export const platformDaemonLifecycleOwners = {};\n' +
116+
'export const extraLifecycleParticipant = {};\n',
117117
'src/daemon/server/daemon-runtime.ts':
118-
"const { recoverLegacyAppLogMarkersAfterDaemonLock, extraLegacyMarkerSweep } = await import('../../platform-runtime-operation-host.ts');\n" +
119-
'void [recoverLegacyAppLogMarkersAfterDaemonLock, extraLegacyMarkerSweep];\n',
118+
"const { platformDaemonLifecycleOwners, extraLifecycleParticipant } = await import('../../platform-runtime-daemon-lifecycle.ts');\n" +
119+
'void [platformDaemonLifecycleOwners, extraLifecycleParticipant];\n',
120120
};
121121
const found = edgeViolations(sources, 'src/daemon/server/daemon-runtime.ts');
122122
assert.equal(found.length, 1);
123123
assert.equal(found[0]!.rule, DAEMON_PLATFORM_RUNTIME_RULE);
124124
assert.match(found[0]!.message, /classified symbols drifted/);
125-
assert.match(
126-
found[0]!.message,
127-
/extraLegacyMarkerSweep, recoverLegacyAppLogMarkersAfterDaemonLock/,
128-
);
125+
assert.match(found[0]!.message, /extraLifecycleParticipant, platformDaemonLifecycleOwners/);
129126
});
130127

131128
test('R76 rejects a rest binding next to a recorded dynamic-import binding', () => {
132129
const sources = {
133-
'src/platform-runtime-operation-host.ts':
134-
'export async function recoverLegacyAppLogMarkersAfterDaemonLock() { return {}; }\n' +
135-
'export async function sweepLegacyAppLogMarkers() { return {}; }\n',
130+
'src/platform-runtime-daemon-lifecycle.ts':
131+
'export const platformDaemonLifecycleOwners = {};\n' +
132+
'export const sweepLifecycleParticipants = {};\n',
136133
'src/daemon/server/daemon-runtime.ts':
137-
"const { recoverLegacyAppLogMarkersAfterDaemonLock, ...operationHost } = await import('../../platform-runtime-operation-host.ts');\n" +
138-
'void [recoverLegacyAppLogMarkersAfterDaemonLock, operationHost];\n',
134+
"const { platformDaemonLifecycleOwners, ...lifecycleModule } = await import('../../platform-runtime-daemon-lifecycle.ts');\n" +
135+
'void [platformDaemonLifecycleOwners, lifecycleModule];\n',
139136
};
140137
const found = edgeViolations(sources, 'src/daemon/server/daemon-runtime.ts');
141138
assert.equal(found.length, 1);
142139
assert.equal(found[0]!.rule, DAEMON_PLATFORM_RUNTIME_RULE);
143140
assert.match(found[0]!.message, /unnameable dynamic-import binding/);
144141
assert.match(
145142
found[0]!.message,
146-
/src\/daemon\/server\/daemon-runtime\.ts -> src\/platform-runtime-operation-host\.ts/,
143+
/src\/daemon\/server\/daemon-runtime\.ts -> src\/platform-runtime-daemon-lifecycle\.ts/,
147144
);
148145
});
149146

150147
test('R76 rejects a computed destructure key on a classified dynamic import', () => {
151148
const sources = {
152-
'src/platform-runtime-operation-host.ts':
153-
'export async function recoverLegacyAppLogMarkersAfterDaemonLock() { return {}; }\n',
149+
'src/platform-runtime-daemon-lifecycle.ts':
150+
'export const platformDaemonLifecycleOwners = {};\n',
154151
'src/daemon/server/daemon-runtime.ts':
155-
"const markerName = 'recoverLegacyAppLogMarkersAfterDaemonLock';\n" +
156-
'const { [markerName]: recover } = await import("../../platform-runtime-operation-host.ts");\n' +
157-
'void recover;\n',
152+
"const ownersName = 'platformDaemonLifecycleOwners';\n" +
153+
'const { [ownersName]: owners } = await import("../../platform-runtime-daemon-lifecycle.ts");\n' +
154+
'void owners;\n',
158155
};
159156
const found = edgeViolations(sources, 'src/daemon/server/daemon-runtime.ts');
160157
assert.equal(found.length, 1);
@@ -163,10 +160,10 @@ test('R76 rejects a computed destructure key on a classified dynamic import', ()
163160

164161
test('R76 rejects a namespace-form dynamic import that hides the recorded bindings', () => {
165162
const sources = {
166-
'src/platform-runtime-operation-host.ts':
167-
'export async function recoverLegacyAppLogMarkersAfterDaemonLock() { return {}; }\n',
163+
'src/platform-runtime-daemon-lifecycle.ts':
164+
'export const platformDaemonLifecycleOwners = {};\n',
168165
'src/daemon/server/daemon-runtime.ts':
169-
"const mod = await import('../../platform-runtime-operation-host.ts');\nvoid mod;\n",
166+
"const mod = await import('../../platform-runtime-daemon-lifecycle.ts');\nvoid mod;\n",
170167
};
171168
const found = edgeViolations(sources, 'src/daemon/server/daemon-runtime.ts');
172169
assert.equal(found.length, 1);
@@ -176,20 +173,20 @@ test('R76 rejects a namespace-form dynamic import that hides the recorded bindin
176173

177174
test('R76 rejects a namespace import alongside the recorded named binding on the same pair', () => {
178175
const sources = {
179-
'src/platform-runtime-operation-host.ts':
180-
'export async function recoverLegacyAppLogMarkersAfterDaemonLock() { return {}; }\n',
176+
'src/platform-runtime-daemon-lifecycle.ts':
177+
'export const platformDaemonLifecycleOwners = {};\n',
181178
'src/daemon/server/daemon-runtime.ts':
182-
"const { recoverLegacyAppLogMarkersAfterDaemonLock } = await import('../../platform-runtime-operation-host.ts');\n" +
183-
"const operationHost = await import('../../platform-runtime-operation-host.ts');\n" +
184-
'void [recoverLegacyAppLogMarkersAfterDaemonLock, operationHost];\n',
179+
"const { platformDaemonLifecycleOwners } = await import('../../platform-runtime-daemon-lifecycle.ts');\n" +
180+
"const lifecycleModule = await import('../../platform-runtime-daemon-lifecycle.ts');\n" +
181+
'void [platformDaemonLifecycleOwners, lifecycleModule];\n',
185182
};
186183
const found = edgeViolations(sources, 'src/daemon/server/daemon-runtime.ts');
187184
assert.equal(found.length, 1);
188185
assert.equal(found[0]!.rule, DAEMON_PLATFORM_RUNTIME_RULE);
189186
assert.match(found[0]!.message, /open-ended dynamic import/);
190187
assert.match(
191188
found[0]!.message,
192-
/src\/daemon\/server\/daemon-runtime\.ts -> src\/platform-runtime-operation-host\.ts/,
189+
/src\/daemon\/server\/daemon-runtime\.ts -> src\/platform-runtime-daemon-lifecycle\.ts/,
193190
);
194191
});
195192

‎scripts/layering/daemon-platform-runtime-inventory.ts‎

Lines changed: 14 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -67,44 +67,28 @@ export const DAEMON_PLATFORM_RUNTIME_EDGES: readonly DaemonPlatformRuntimeEdge[]
6767
'per-family probes load lazily inside the root module, so the daemon consumes only ' +
6868
'the contract surface.',
6969
},
70-
{
71-
file: 'src/daemon/server/daemon-runtime.ts',
72-
target: 'src/platform-runtime-apple-runner-owner.ts',
73-
symbols: [
74-
'configureAppleRunnerDeviceClaimAuthorityProbe',
75-
'configureAppleRunnerLeaseOwnerStateDir',
76-
],
77-
classification: 'leaked-platform-mechanics',
78-
rationale:
79-
'daemon startup/shutdown names the Apple runner owner directly; the daemon-owned ' +
80-
'inputs (lease-owner state dir, claim-authority probe) should flow through typed ' +
81-
'lifecycle participation instead of configure calls into a platform-composed owner.',
82-
deepenedBy: '#2333',
83-
},
8470
{
8571
file: 'src/daemon/server/daemon-runtime.ts',
8672
target: 'src/platform-runtime-resource-cleanup.ts',
87-
symbols: [
88-
'cleanupManagedWebRuntimeOrphans',
89-
'platformResourceCleanup',
90-
'resetAndroidSnapshotHelperRuntime',
91-
],
92-
classification: 'leaked-platform-mechanics',
73+
symbols: ['platformResourceCleanup'],
74+
classification: 'composition-essential',
9375
rationale:
94-
'startup/shutdown cleanup participation names the Android snapshot-helper and Web ' +
95-
'orphan owners directly; platformResourceCleanup (the neutral PlatformResourceCleanup ' +
96-
'contract) is the model the other two symbols should follow.',
97-
deepenedBy: '#2333',
76+
'process-root assembly of the neutral PlatformResourceCleanup contract capability; the ' +
77+
'Android snapshot-helper reset and Web orphan cleanup that used to be named directly on ' +
78+
'this edge now sit behind the typed lifecycle-participation surface (#2333, see the ' +
79+
'platform-runtime-daemon-lifecycle.ts edge below).',
9880
},
9981
{
10082
file: 'src/daemon/server/daemon-runtime.ts',
101-
target: 'src/platform-runtime-operation-host.ts',
102-
symbols: ['recoverLegacyAppLogMarkersAfterDaemonLock'],
103-
classification: 'leaked-platform-mechanics',
83+
target: 'src/platform-runtime-daemon-lifecycle.ts',
84+
symbols: ['platformDaemonLifecycleOwners'],
85+
classification: 'composition-essential',
10486
rationale:
105-
'daemon startup names app-log legacy marker recovery, a platform process mechanic; ' +
106-
'it should join the same typed lifecycle participation as the other startup cleanups.',
107-
deepenedBy: '#2333',
87+
'process-root assembly of the typed PlatformOwnerLifecycle contract capability (#2333): ' +
88+
'the daemon keeps ordering, cancellation, and best-effort failure policy for its ' +
89+
'startup/shutdown platform-owner participation, while this composition module is the ' +
90+
'sole place that names the Apple runner owner, the Android snapshot-helper and Web ' +
91+
'orphan cleanups, and legacy app-log marker recovery.',
10892
},
10993
{
11094
file: 'src/daemon/device-claim-owner-recovery.ts',

‎src/daemon/__tests__/daemon-runtime-app-log.test.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ import { unavailableDeviceRuntimeGateway } from './test-device-runtime-gateway.t
2121
test('daemon startup awaits app-log recovery after acquiring the lock and before opening servers', () => {
2222
const source = fs.readFileSync(new URL('../server/daemon-runtime.ts', import.meta.url), 'utf8');
2323
const acquiredLock = source.indexOf('if (!acquireDaemonLock(');
24-
const legacyRecovery = source.indexOf('await recoverLegacyAppLogMarkersAfterDaemonLock(');
24+
const legacyRecovery = source.indexOf(
25+
'await platformDaemonLifecycleOwners.recoverLegacyAppLogMarkers(',
26+
);
2527
const recovery = source.indexOf('await recoverAppLogResourcesAfterDaemonLock(');
2628
const openedServers = source.indexOf('const opened = await openDaemonServers()');
2729

@@ -31,6 +33,25 @@ test('daemon startup awaits app-log recovery after acquiring the lock and before
3133
expect(openedServers).toBeGreaterThan(recovery);
3234
});
3335

36+
test('daemon startup configures the Apple runner owner after acquiring the lock, not before', () => {
37+
// #2333/#2415 review: the daemon-owned lease-owner state dir and claim-authority probe must
38+
// publish only once this process actually holds the daemon lock, so a losing process never
39+
// configures a global platform owner it does not own.
40+
const source = fs.readFileSync(new URL('../server/daemon-runtime.ts', import.meta.url), 'utf8');
41+
const acquiredLock = source.indexOf('if (!acquireDaemonLock(');
42+
const runnerOwnerConfigured = source.indexOf(
43+
'await platformDaemonLifecycleOwners.configureForDaemonLock(',
44+
);
45+
const lockFailureExit = source.indexOf("stderr.write('Daemon lock is held by another process");
46+
47+
expect(acquiredLock).toBeGreaterThanOrEqual(0);
48+
expect(lockFailureExit).toBeGreaterThan(acquiredLock);
49+
expect(runnerOwnerConfigured).toBeGreaterThan(acquiredLock);
50+
// The configure call sits inside the post-lock try block, after the failure branch that exits
51+
// for a lock held by another process.
52+
expect(runnerOwnerConfigured).toBeGreaterThan(lockFailureExit);
53+
});
54+
3455
test('retained startup recovery evidence is flushed after daemon.log publication', async () => {
3556
const root = mkdtempForTestSync('daemon-runtime-app-log-recovery-diagnostics-');
3657
const sessionsDir = path.join(root, 'sessions');
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import type { DeviceIdentity, DeviceInfo } from '@agent-device/kernel/device';
2+
import type { OwnedProcessRecordStore } from '@agent-device/host-kit/process';
3+
4+
/** Predicate answering whether this process currently holds an active claim on the device. */
5+
export type DeviceClaimAuthorityProbe = (device: DeviceInfo) => boolean;
6+
7+
export type LegacyAppLogMarkerRecoveryOutcome = Readonly<{
8+
recovered: readonly string[];
9+
retained: readonly Readonly<{
10+
markerPath: string;
11+
reason: 'invalid' | 'ownership-lost';
12+
message?: string;
13+
device?: DeviceIdentity;
14+
}>[];
15+
}>;
16+
17+
/**
18+
* Typed startup/shutdown participation for the platform resource owners the daemon coordinates
19+
* but does not itself implement (#2333): the daemon supplies its own inputs, ordering, and
20+
* best-effort failure policy, and the root composition wires the concrete platform owners behind
21+
* this surface. No generic hook bag — every phase this daemon relies on is named here.
22+
*/
23+
export type PlatformOwnerLifecycle = Readonly<{
24+
/** Publishes the daemon-owned lease-owner state dir and claim-authority probe. */
25+
configureForDaemonLock(
26+
input: Readonly<{
27+
stateDir: string;
28+
hasDeviceClaimAuthority: DeviceClaimAuthorityProbe;
29+
}>,
30+
): Promise<void>;
31+
/** Clears the configuration above: on a failed lock acquisition, and on shutdown. */
32+
clearDaemonLockConfiguration(): Promise<void>;
33+
/** Startup, before servers open: recovers marker-only app-log sessions left by a prior daemon. */
34+
recoverLegacyAppLogMarkers(sessionsDir: string): Promise<LegacyAppLogMarkerRecoveryOutcome>;
35+
/** Startup, before servers open: cleans up orphaned managed Web runtime sessions. */
36+
cleanupManagedWebOrphans(
37+
params: Readonly<{
38+
stateDir: string;
39+
openWebSessionNames: readonly string[];
40+
ownedProcessRecords?: OwnedProcessRecordStore;
41+
}>,
42+
): Promise<void>;
43+
/** Shutdown: resets Android snapshot-helper runtime sessions. */
44+
resetAndroidSnapshotHelper(): Promise<void>;
45+
}>;

0 commit comments

Comments
 (0)