Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
620eaba
refactor(daemon): fake the host-diagnostics, perf-capture, android-ob…
Oct 12, 2026
4d8d80e
refactor(daemon): fake the application-lifecycle runtime-binding port…
thymikee Oct 12, 2026
b9d7bea
refactor(daemon): delete the five dead root-module mocks from daemon …
thymikee Oct 13, 2026
3b67712
refactor(daemon): answer the platform-services and lifecycle ports wi…
thymikee Oct 13, 2026
e3375a6
chore(gates): commit the daemon residue scan the 11a slices measure with
thymikee Oct 13, 2026
4d38064
refactor(daemon): keep the canned-answer spies unexported and registe…
thymikee Oct 13, 2026
2182ba2
refactor(daemon): observe the boot probe at the services port in the …
thymikee Oct 13, 2026
9acaf1f
refactor(daemon): take the harness lifecycle loader as a parameter, o…
thymikee Oct 13, 2026
fc2f1be
refactor(daemon): move the android discovery seam to the composition …
thymikee Oct 13, 2026
6889e55
test(composition): pin the composed snapshot-helper stop rule against…
thymikee Oct 13, 2026
eeef98b
fix(gates): report residue edges at the keyword line and on native paths
thymikee Oct 13, 2026
4a85acf
test(composition): park the orphan recorder on the current Node binary
thymikee Oct 13, 2026
17be8b9
refactor(daemon): keep the fixture's relaunch order close, hints, open
thymikee Oct 13, 2026
3a6c9bf
refactor(daemon): carry the request signal into lifecycle gateway binds
thymikee Oct 13, 2026
0c1d202
refactor(daemon): answer exact-owner binds with the requested owner
thymikee Oct 13, 2026
f0ffe35
test(composition): prove lazy runtime-hints loading before the first …
thymikee Oct 13, 2026
9b4c47e
test(composition): restore the claims-dir override after each case
thymikee Oct 13, 2026
7daf9ba
test(composition): drive close retention through the composed cleanup
thymikee Oct 13, 2026
f5582f4
test(daemon): answer the open-target identity once per case
thymikee Oct 13, 2026
392ceb9
docs(tests): say what the one-shot rejection and the TTL pin actually…
thymikee Oct 13, 2026
6817b43
docs(tests): scope the post-open observation suite to what it composes
thymikee Oct 13, 2026
b5d7af7
test(composition): put the interaction-prepare and integration suites…
thymikee Oct 14, 2026
51281e5
test(composition): name the root fixtures after their lane
thymikee Oct 14, 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
3 changes: 3 additions & 0 deletions .fallowrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@
"scripts/patch-xcuitest-runner-icon.ts",
"scripts/write-xcuitest-cache-metadata.ts",
"scripts/xcuitest-build-settings.ts",
// The 11a-4 residue scan runs by hand (and from CI prose until R11 in #3546 owns
// the rule); nothing in the dependency graph imports it.
"scripts/daemon-edge-residue-scan.mjs",
"packages/capture-kit/src/ios-snapshot-engine/replay.ts",
// #1596 regression fixture: runs as a real `node --experimental-strip-types`
// subprocess (test/integration/daemon-replace-exit-flush.test.ts), so
Expand Down
90 changes: 90 additions & 0 deletions scripts/daemon-edge-residue-scan.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// Daemon residue scan (11a-4): every module specifier in a file under src/daemon/ that resolves
// to a non-package module outside src/daemon/. The rule: daemon files may import workspace
// packages, externals, and each other — nothing else. Once the daemon is its own package, R11 in
// the layering guard (#3546) enforces this permanently; until then this scan is the measurement.
//
// Why a naive regex reported zero edges while five mocks survived: a single alternation that
// starts at `import|export` and bridges to the next `from` with `[\s\S]*?` swallows everything in
// between — including a `vi.mock('../../../platform-runtime-….ts', …)` whose own specifier sits
// between an earlier `importOriginal<typeof import(...)>` and the file's next static `from`. The
// mocked specifier is then attributed to the wrong (allowed) capture or skipped entirely. So each
// specifier form is matched independently, statement-anchored where the language is:
//
// - static `import`/`export … from '…'` and side-effect `import '…'`, anchored at a statement
// start (line start or `;`), never bridging statements;
// - `import type` / `export type` variants (same anchor);
// - dynamic `import('…')` / `require('…')` with a string or no-substitution template argument;
// - `vi.mock` / `vi.doMock` / `vi.unmock` / `vi.importMock` / `vi.importActual` /
// `vi.importOriginal` first argument, any position, string or template literal;
// - `importOriginal<typeof import('…')>` type-position specifiers (the dynamic-import form).
//
// Known limits: computed specifiers (variables, string concatenation) are out of scope — none
// exist in the daemon tree, and a runtime resolver is the only tool that could see them.
//
// Usage: `node scripts/daemon-edge-residue-scan.mjs` from the repo root. Exit code 1 when any
// edge is found.
import fs from 'node:fs';
import path from 'node:path';

const root = process.cwd();

function walk(dir, out) {
for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, ent.name);
if (ent.isDirectory()) walk(p, out);
else if (/\.(ts|tsx|mjs)$/.test(ent.name)) out.push(p);
}
return out;
}

// A quoted string or no-substitution template literal as the specifier position.
const SPEC = '(?:\'([^\']*)\'|"([^"]*)"|`([^`]*)`)';
const forms = [
// Static import/export with a `from` clause; the keyword must start a statement.
new RegExp(`(?:^|[;\\n])\\s*(?:import|export)\\b[^'"()\`]*?\\bfrom\\s*${SPEC}`, 'gm'),
// Side-effect import.
new RegExp(`(?:^|[;\\n])\\s*import\\s+${SPEC}`, 'gm'),
// Dynamic import (also catches `typeof import('…')` in type positions) and require.
new RegExp(`\\bimport\\s*\\(\\s*${SPEC}`, 'g'),
Comment thread
thymikee marked this conversation as resolved.
new RegExp(`\\brequire\\s*\\(\\s*${SPEC}`, 'g'),
// Vitest module-factory hoists, any position in the file.
new RegExp(
`\\bvi\\.(?:mock|doMock|unmock|importMock|importActual|importOriginal)\\s*\\(\\s*${SPEC}`,
'g',
),
];

const files = walk(path.join(root, 'src/daemon'), []);
const edges = [];
for (const file of files) {
const rel = path.relative(root, file);
const source = fs.readFileSync(file, 'utf8');
const seen = new Set();
for (const form of forms) {
form.lastIndex = 0;
let match;
while ((match = form.exec(source))) {
const specifier = match[1] ?? match[2] ?? match[3];
if (!specifier) continue;
if (!specifier.startsWith('.')) continue; // bare specifier: package or external, allowed
const resolved = path
.normalize(path.join(path.dirname(rel), specifier))
.replace(/\.tsx?$/, '');
// path.join yields backslashes on Windows, so compare against the native separator.
const daemonDir = path.join('src', 'daemon');
if (resolved === daemonDir || resolved.startsWith(`${daemonDir}${path.sep}`)) continue;
if (seen.has(resolved)) continue;
seen.add(resolved);
// The static forms anchor at the preceding `;`/newline, so slice(0, match.index)
// counts lines only up to that separator and reports one early. Count to the
// keyword inside the match (position 0 for the unanchored forms).
const keywordAt = match[0].search(/import|export|require|vi\./);
const line = source.slice(0, match.index + keywordAt).split('\n').length;
edges.push(`${rel}:${line} -> ${resolved}`);
}
}
}
edges.sort();
if (edges.length > 0) process.stdout.write(edges.join('\n') + '\n');
process.stdout.write(`daemon residue edges: ${edges.length}\n`);
if (edges.length > 0) process.exit(1);
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
import type { ApplicationLifecycleRuntimeOperations } from '@agent-device/contracts/application-lifecycle-runtime';
import type { DeviceBinding } from '@agent-device/contracts/platform-runtime';
import type {
PlatformRuntimeHost,
PlatformRuntimeOperations,
} from '@agent-device/contracts/platform-runtime-operations';
import type { DeviceInfo } from '@agent-device/kernel/device';
import type { TargetShutdownResult } from '@agent-device/contracts/device';
import { vi } from 'vitest';
// The lifecycle seams (dispatch spy, readiness pause, fixture interactor) have ONE owner: the
// daemon's canned lifecycle fixture. This real-composition fixture builds the REAL root gateway
// and platform application tools on top of the same seams, so every lane observes one spy set.
// Android readiness discovery is the composed owners' rule (which devices discovery runs for),
// so its already-running-emulator seam lives HERE, not in the daemon fixture.
export {
awaitFixtureReadiness,
dispatchApplicationLifecycleEffect,
} from '../../daemon/__tests__/application-lifecycle-runtime-fixture.ts';
import {
applicationLifecycleFixtureInteractor,
awaitFixtureReadiness,
} from '../../daemon/__tests__/application-lifecycle-runtime-fixture.ts';
import type { Interactor, RunnerContext } from '@agent-device/contracts/interactor-types';
import { createAndroidApplicationTools } from '../../platform-runtime-android-application-tools.ts';
import { createAppleApplicationTools } from '../../platform-runtime-apple-application-tools.ts';
import { createComposedPlatformRuntimeGateway } from '../../platform-runtime-gateway.ts';
import { platformRuntimeModules } from '../../platform-runtime.ts';

/**
* Readiness discovery, as a seam for the composed host. It reports the device under test as an
* already-running emulator so composition fixtures never launch or poll a boot; a test that needs
* a pre-effect readiness failure rejects this instead.
*/
export const discoverReadyAndroidEmulators = vi.fn(async (readyDevice: DeviceInfo) => [
{
...readyDevice,
id: readyDevice.id.startsWith('emulator-') ? readyDevice.id : `emulator-${readyDevice.id}`,
booted: true,
},
]);

export async function composedLifecycleRuntimeFixture(
device: DeviceInfo,
signal: AbortSignal = new AbortController().signal,
shutdownTarget: (device: DeviceInfo) => Promise<TargetShutdownResult> = async () => ({
success: true,
exitCode: 0,
stdout: '',
stderr: '',
}),
): Promise<ApplicationLifecycleRuntimeOperations> {
const gateway = createComposedPlatformRuntimeGateway({
modules: platformRuntimeModules,
loadHost: async () => fixtureHost(device, shutdownTarget),
});
const binding = await gateway.bind({
device,
intent: { kind: 'ordinary' },
scope: { signal, diagnostics: { emit: () => {} }, progress: { report: () => {} } },
});
return lifecycleOperations(binding);
}

function lifecycleOperations(
binding: DeviceBinding<PlatformRuntimeOperations>,
): ApplicationLifecycleRuntimeOperations {
const operations = binding.operations;
const keys = [
'resolveOpenTarget',
'prepareApplicationOpen',
'openApplication',
'applyRuntimeHints',
'clearRuntimeHints',
'closeApplication',
'finalizeApplicationClose',
'prepareAppleRunner',
'configureProviderPortReverse',
] as const satisfies readonly (keyof ApplicationLifecycleRuntimeOperations)[];
const selected = Object.fromEntries(
keys.flatMap((key) => {
const operation = operations[key];
return operation ? [[key, operation]] : [];
}),
);
return Object.freeze(selected) as ApplicationLifecycleRuntimeOperations;
}

function fixtureHost(
readyDevice: DeviceInfo,
shutdownTarget: (device: DeviceInfo) => Promise<TargetShutdownResult>,
): PlatformRuntimeHost {
let simulatorState = readyDevice.booted === false ? 'Shutdown' : 'Booted';
const localInteractors = Object.freeze({
resolve: async (device: DeviceInfo, runner: RunnerContext): Promise<Interactor> =>
applicationLifecycleFixtureInteractor(device, runner),
});
return {
localInteractors,
appleApplications: createAppleApplicationTools(),
androidApplications: createAndroidApplicationTools(),
deviceShutdown: Object.freeze({
apple: Object.freeze({
shutdownTarget: async (device: DeviceInfo) => await shutdownTarget(device),
}),
android: Object.freeze({
shutdownTarget: async (device: DeviceInfo) => await shutdownTarget(device),
}),
close: Object.freeze({
canShutdownTarget: async (device: DeviceInfo) =>
(device.platform === 'apple' && device.kind === 'simulator') ||
(device.platform === 'android' && device.kind === 'emulator'),
shutdownTarget: async (device: DeviceInfo) => await shutdownTarget(device),
}),
}),
// Readiness is package-owned; these handler fixtures exercise lifecycle dispatch, so the
// narrow ports report an already-ready device instead of booting anything.
deviceReadiness: Object.freeze({
applePhysical: Object.freeze({
ensureConnected: async (_device: DeviceInfo, signal: AbortSignal) => {
signal.throwIfAborted();
},
}),
appleAutomation: Object.freeze({
keepHot: () => undefined,
markBooted: () => {},
wasRecentlyObservedBooted: async () => false,
}),
androidEmulator: Object.freeze({
discover: async (_request: unknown, signal: AbortSignal) => {
signal.throwIfAborted();
await awaitFixtureReadiness(readyDevice);
return await discoverReadyAndroidEmulators(readyDevice);
},
launch: () => 1,
terminate: async () => undefined,
}),
}),
// Readiness reads the device's own boot state, so a `booted: false` fixture still exercises
// the cold-boot path (and its runner-cache prewarm hook) before settling.
appleTools: Object.freeze({
isXcrunAvailable: async () => true,
run: async (request: Readonly<{ args: readonly string[] }>) => {
await awaitFixtureReadiness(readyDevice);
if (request.args.includes('boot')) {
simulatorState = 'Booted';
return { stdout: '', stderr: '', exitCode: 0 };
}
return {
stdout: JSON.stringify({
devices: { fixture: [{ udid: readyDevice.id, state: simulatorState }] },
}),
stderr: '',
exitCode: 0,
};
},
}),
commands: Object.freeze({
which: async (executable: string) => executable,
run: async () => ({ stdout: '1', stderr: '', exitCode: 0 }),
}),
toolchains: Object.freeze({ prepare: async () => undefined }),
clock: Object.freeze({
now: () => Date.now(),
sleep: async () => undefined,
}),
processTransports: Object.freeze({
resolve: async () => ({ mode: 'local' as const }),
}),
networkTransports: Object.freeze({
resolve: async () => ({ mode: 'local' as const }),
}),
screenRecording: Object.freeze({
apple: Object.freeze({
availability: async () => ({
available: false as const,
hint: 'Screen recording is outside this lifecycle fixture.',
}),
}),
android: Object.freeze({ resolve: async () => ({}) }),
web: Object.freeze({ resolve: async () => undefined }),
}),
audioProbe: Object.freeze({
hostCapture: Object.freeze({
info: Object.freeze({
source: 'system-audio' as const,
backend: 'fixture',
sourceCount: 0,
notes: () => [],
}),
start: async () => {
throw new Error('Audio probe is outside this lifecycle fixture.');
},
inspectProcess: async () => 'missing' as const,
terminateProcess: async () => 'already-missing' as const,
}),
web: Object.freeze({ resolve: async () => undefined }),
ownedProcesses: Object.freeze({ replace: () => {}, clear: () => {} }),
}),
} as unknown as PlatformRuntimeHost;
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { daemonPlatformServicesFixture } from '../../__tests__/platform-services-fixture.ts';
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
import { promises as fs } from 'node:fs';
import { composedPlatformServicesFixture } from '../platform-services-fixture.ts';
import type { DeviceInfo } from '@agent-device/kernel/device';

vi.mock('@agent-device/host-kit/command', async (importOriginal) => {
Expand Down Expand Up @@ -28,14 +28,19 @@ import {
IOS_DEVICE,
IOS_SIMULATOR,
} from '@agent-device/test-kit/device-fixtures';
import { DEVICE_READY_CACHE_TTL_MS, ensureDeviceReady } from '../device-ready.ts';
import {
DEVICE_READY_CACHE_TTL_MS,
ensureDeviceReady,
} from '../../../daemon/device/device-ready.ts';

const mockRunCmd = vi.mocked(runCmd);
const mockEnsureBootedSimulator = vi.mocked(ensureBootedSimulator);
const mockWaitForAndroidBoot = vi.mocked(waitForAndroidBoot);
// Readiness mechanics stay the real ones: the fixture delegates to the root adapter, so the
// platform-leaf mocks above still own what the port actually calls.
const platformServices = daemonPlatformServicesFixture();
// This suite pins what the REAL composed readiness port does per device family: it runs in the
// composition lane on the root-composed services fixture, with the platform leaves mocked above.
// The daemon-lane port fixture answers readiness with a canned spy; this suite separately
// pins the readiness cache contract, including its TTL behavior.
const platformServices = composedPlatformServicesFixture();

beforeEach(() => {
vi.useFakeTimers();
Expand Down
6 changes: 3 additions & 3 deletions src/__tests__/daemon-composition/generic-settle.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { daemonPlatformServicesFixture } from '../../daemon/__tests__/platform-services-fixture.ts';
import { composedPlatformServicesFixture } from './platform-services-fixture.ts';
import { beforeEach, expect, test, vi } from 'vitest';
import type { CommandFlags } from '@agent-device/contracts/command';
import type { RawSnapshotNode } from '@agent-device/kernel/snapshot';
Expand Down Expand Up @@ -214,7 +214,7 @@ async function dispatchGeneric(params: {
};
return await dispatchGenericCommand({
createCommandSurface: testCreateCommandSurface,
platformServices: daemonPlatformServicesFixture(),
platformServices: composedPlatformServicesFixture(),
req,
ref: params.sessionStore.lookup(params.sessionName)!,
sessionName: params.sessionName,
Expand Down Expand Up @@ -654,7 +654,7 @@ test('an ended generic lifetime is refused before dispatch or settle constructio
await expect(
dispatchGenericCommand({
createCommandSurface: testCreateCommandSurface,
platformServices: daemonPlatformServicesFixture(),
platformServices: composedPlatformServicesFixture(),
req: {
token: 't',
session: sessionName,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { daemonPlatformServicesFixture } from '../../daemon/__tests__/platform-services-fixture.ts';
import { composedPlatformServicesFixture } from './platform-services-fixture.ts';
import { expect, test } from 'vitest';
import type {
GestureCommandInput,
Expand Down Expand Up @@ -71,7 +71,7 @@ async function admit(input: GestureCommandInput, target: DeviceInfo) {
});
try {
return await resolveBoundGestureRuntime({
platformServices: daemonPlatformServicesFixture(),
platformServices: composedPlatformServicesFixture(),
device: target,
input,
inspectFacts: bindings.inspectFacts,
Expand Down
Loading
Loading