diff --git a/.fallowrc.json b/.fallowrc.json index 1daaeb3098..8a18a8bda2 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -6,6 +6,12 @@ "scripts/check-provider-plugin.mjs", "scripts/check-affected/command.ts", "packages/provider-testmu/test/package-smoke.mjs", + "packages/maestro/test/package-artifact.test.mjs", + "packages/maestro/test/packed-clickability.mjs", + "packages/maestro/test/packed-screen-origin.mjs", + "packages/maestro/test/package-test-support.mjs", + "packages/maestro/tsdown.config.ts", + "packages/maestro/src/plugin.ts", "packages/provider-testmu/tsdown.config.ts", "packages/provider-revyl/test/package-smoke.mjs", "packages/provider-revyl/tsdown.config.ts", @@ -150,8 +156,8 @@ "exports": ["*"] }, { - // A published provider package's default export is its plugin contract; the plugin loader imports the installed package's resolved entry at runtime and reads `default`. - "file": "packages/provider-*/src/index.ts", + // A published plugin's default export is its contract; the plugin loader imports the installed package's resolved entry at runtime and reads `default`. + "file": "packages/{provider-*/src/index,maestro/src/plugin}.ts", "exports": ["default"] }, { @@ -281,7 +287,7 @@ }, { // Tool config default exports, loaded by the tool rather than imported. - "file": "{oxlint.config.ts,tsdown.config.ts,packages/provider-*/tsdown.config.ts,packages/proxy/tsdown.config.ts,vitest.mutation.config.ts}", + "file": "{oxlint.config.ts,tsdown.config.ts,packages/provider-*/tsdown.config.ts,packages/maestro/tsdown.config.ts,packages/proxy/tsdown.config.ts,vitest.mutation.config.ts}", "exports": ["default"] }, { diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 17ba0ab3e9..6fd1cb7a56 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -102,11 +102,28 @@ jobs: uses: ./.github/actions/run-gate with: { gate: build } + - name: Verify the core and standalone Maestro packages + uses: ./.github/actions/run-gate + with: { gate: package } + - name: Verify emitted chunk ownership uses: ./.github/actions/run-gate with: { gate: bundle-owner-files } - # The build runs on the default toolchain Node and the package is verified on the minimum + - name: Setup Node.js 22.13 + uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0 + with: + node-version: '22.13.0' + + - name: Verify the repository build on Node.js 22.13 + uses: ./.github/actions/run-gate + with: { gate: build } + + - name: Verify development packaging on Node.js 22.13 + uses: ./.github/actions/run-gate + with: { gate: package } + + # The build runs on the development floor and the package is verified on the minimum # supported Node, so this job covers what a user on `engines.node` floor actually installs. - name: Setup Node.js 22.12 uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0 @@ -118,7 +135,7 @@ jobs: # # Runs the script directly rather than through `pnpm check:package`: the repo's pinned pnpm # requires Node >= 22.13 and refuses to start on the 22.12 floor this job exists to cover. The - # gate itself only needs `node` and `npm`, so it is the package.json script minus the launcher. + # root-package probe only needs `node` and `npm`. The full package gate runs above. - name: Verify the published package on Node.js 22.12 run: node --experimental-strip-types scripts/check-package.ts diff --git a/package.json b/package.json index c053231e5c..739bcd917a 100644 --- a/package.json +++ b/package.json @@ -165,7 +165,7 @@ "depgraph:test": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test scripts/depgraph/model.test.ts scripts/depgraph/entries.test.ts scripts/depgraph/import-graph.test.ts scripts/depgraph/affected.test.ts scripts/depgraph/structure-summary.test.ts tools/depgraph-view/*.test.mjs", "check:production-exports": "fallow dead-code --config fallow-production-exports.json --production --unused-exports --fail-on-issues", "check:bundle-owner-files": "node --experimental-strip-types scripts/check-bundle-owner-files.ts", - "check:package": "node --experimental-strip-types scripts/check-package.ts", + "check:package": "node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test packages/maestro/test/package-artifact.test.mjs && node --experimental-strip-types scripts/check-package.ts", "check:command-docs": "vitest run --project unit-core test/repo-guards/command-doc-coverage.test.ts", "check:adr-citations": "vitest run --project unit-core test/repo-guards/adr-citations.test.ts", "check:capabilities-matrix": "vitest run --project unit-core test/repo-guards/capability-matrix.test.ts", @@ -373,6 +373,7 @@ "tsdown": "^0.22.14", "typescript": "^7.0.2", "undici": "7.30.1", + "unrun": "0.3.1", "vite": "^8.3.5", "vitest": "5.0.4", "yaml": "^2.9.0", diff --git a/packages/contracts/src/host-diagnostics.ts b/packages/contracts/src/host-diagnostics.ts index fc99bd47aa..1611d41e61 100644 --- a/packages/contracts/src/host-diagnostics.ts +++ b/packages/contracts/src/host-diagnostics.ts @@ -46,3 +46,14 @@ export type HostDiagnostics = Readonly<{ context: HostDiagnosticsContext, ): Promise; }>; + +/** The severity an event is recorded with. */ +export type DiagnosticLevel = 'info' | 'warn' | 'error' | 'debug'; + +/** A diagnostic handed to the host that owns the request log and redaction. */ +export type DiagnosticEventInput = { + level?: DiagnosticLevel; + phase: string; + durationMs?: number; + data?: Record; +}; diff --git a/packages/contracts/src/platform-runtime-use.ts b/packages/contracts/src/platform-runtime-use.ts index 9c2e387842..2c0219d01f 100644 --- a/packages/contracts/src/platform-runtime-use.ts +++ b/packages/contracts/src/platform-runtime-use.ts @@ -27,7 +27,7 @@ type RuntimeUseInput< * Runtime validation keeps declarations built from dynamic data fail-closed too. */ export function runtimeUse() { - return < + const define = < const Required extends readonly RuntimeOperationKey[], const Preferred extends readonly Exclude, Required[number]>[] = readonly [], @@ -68,6 +68,7 @@ export function runtimeUse() { conditional.length === 0 ? { required, preferred } : { required, preferred, conditional }, ) as RuntimeUse; }; + return define; } function freezeUniqueKeys(keys: Keys, label: string): Keys { diff --git a/packages/contracts/src/replay-backend.ts b/packages/contracts/src/replay-backend.ts index a8597b2037..43c2bb0e54 100644 --- a/packages/contracts/src/replay-backend.ts +++ b/packages/contracts/src/replay-backend.ts @@ -1,3 +1,5 @@ +import type { DiagnosticEventInput } from './host-diagnostics.ts'; +import type { SnapshotClickabilityEvidence } from './snapshot-private-evidence.ts'; import type { DaemonError } from '@agent-device/kernel/errors'; import type { DaemonResponse, SessionRuntimeHints } from '@agent-device/kernel/contracts'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -230,6 +232,11 @@ export type ReplayBackendDeviceBinding = Readonly<{ * session policy is a member; stateless workspace packages stay direct imports of the plugin. */ export type ReplayBackendHost = Readonly<{ + emitDiagnostic(event: DiagnosticEventInput): void; + /** Reads capture-local facts from the host's private evidence owner, without wire fields. */ + readSnapshotClickabilityEvidence(owner: object): SnapshotClickabilityEvidence | undefined; + /** Refuses capture-derived input when the host has no established screen origin. */ + assertSnapshotScreenOrigin(owner: object, label: string): Promise; /** Appends one record to the run's trace file, if any; failures are diagnostics, never thrown. */ appendTraceEvent(tracePath: string | undefined, event: Record): void; /** The `AD_*` variables every replay run is seeded with. */ @@ -269,5 +276,5 @@ export type ReplayBackendDeclaration = Readonly<{ }>; export type ReplayBackendPlugin = Readonly<{ - create(host: ReplayBackendHost): ReplayBackend; + create(host: ReplayBackendHost): ReplayBackend | Promise>; }>; diff --git a/packages/maestro/package.json b/packages/maestro/package.json index c56e47f68e..4589643ccf 100644 --- a/packages/maestro/package.json +++ b/packages/maestro/package.json @@ -2,18 +2,15 @@ "name": "@agent-device/maestro", "version": "0.0.0", "private": true, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/callstack/agent-device.git", + "directory": "packages/maestro" + }, "sideEffects": false, "type": "module", - "description": "Private Maestro compatibility engine for agent-device.", - "dependencies": { - "@agent-device/ad-script": "workspace:*", - "@agent-device/capture-kit": "workspace:*", - "@agent-device/contracts": "workspace:*", - "@agent-device/host-kit": "workspace:*", - "@agent-device/kernel": "workspace:*", - "@agent-device/provision-kit": "workspace:*", - "@agent-device/selectors": "workspace:*" - }, + "description": "Optional Maestro compatibility engine plugin for agent-device.", "exports": { ".": { "types": "./src/index.ts", @@ -30,10 +27,38 @@ "./run-script-http": { "types": "./src/daemon-port/run-script-http.ts", "default": "./src/daemon-port/run-script-http.ts" + }, + "./agent-device": { + "types": "./src/plugin.ts", + "default": "./src/plugin.ts" } }, "devDependencies": { "undici": "7.30.1", - "yaml": "^2.9.0" + "yaml": "^2.9.0", + "@agent-device/ad-script": "workspace:*", + "@agent-device/capture-kit": "workspace:*", + "@agent-device/contracts": "workspace:*", + "@agent-device/host-kit": "workspace:*", + "@agent-device/kernel": "workspace:*", + "@agent-device/provision-kit": "workspace:*", + "@agent-device/selectors": "workspace:*", + "agent-device": "workspace:*" + }, + "scripts": { + "build": "tsdown --config tsdown.config.ts", + "prepack": "pnpm build" + }, + "files": [ + "dist" + ], + "publishConfig": { + "exports": { + "./agent-device": { + "types": "./dist/agent-device.d.mts", + "import": "./dist/agent-device.mjs" + } + }, + "access": "public" } } diff --git a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-fixtures.ts b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-fixtures.ts index c340894509..c3c444e32d 100644 --- a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-fixtures.ts +++ b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-fixtures.ts @@ -1,4 +1,8 @@ import type { CommandFlags } from '@agent-device/contracts/command'; +import { + assertSnapshotScreenOrigin, + readSnapshotClickabilityEvidence, +} from '@agent-device/contracts/capture'; import { formatRole } from '@agent-device/kernel/snapshot'; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; @@ -21,8 +25,13 @@ export function makeSnapshot( /** The daemon-owned half of the port options: the runtime envelope flags and the network origin. */ export function makeRuntimeEnvelope( overrides: { flags?: CommandFlags; publicNetworkOnly?: boolean } = {}, -): Pick { +): Pick< + CreateDaemonMaestroRuntimeOperationsOptions, + 'flags' | 'publicNetworkOnly' | 'readSnapshotClickabilityEvidence' | 'assertSnapshotScreenOrigin' +> { return { + readSnapshotClickabilityEvidence, + assertSnapshotScreenOrigin, publicNetworkOnly: false, ...overrides, }; diff --git a/packages/maestro/src/daemon-port/daemon-runtime-port-snapshot-source.ts b/packages/maestro/src/daemon-port/daemon-runtime-port-snapshot-source.ts index 5aa7b90d03..2059272164 100644 --- a/packages/maestro/src/daemon-port/daemon-runtime-port-snapshot-source.ts +++ b/packages/maestro/src/daemon-port/daemon-runtime-port-snapshot-source.ts @@ -1,6 +1,6 @@ import { AppError } from '@agent-device/kernel/errors'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; -import { copySnapshotClickabilityEvidence } from '@agent-device/contracts/capture'; +import { attachSnapshotClickabilityEvidence } from '@agent-device/contracts/capture'; import { MAESTRO_RUNTIME_ADAPTER_POLICY, type MaestroObservationIdentity, @@ -36,7 +36,9 @@ export function createDaemonMaestroSnapshotSource( if (!data || !Array.isArray(data.nodes)) { throw new AppError('COMMAND_FAILED', 'Maestro snapshot did not return node data.'); } - const snapshot = copySnapshotClickabilityEvidence(data, data as SnapshotState); + const snapshot = data as SnapshotState; + const clickability = options.readSnapshotClickabilityEvidence(data); + if (clickability) attachSnapshotClickabilityEvidence(snapshot, clickability); cached = { generation: context.generation, snapshot }; return snapshot; }; diff --git a/packages/maestro/src/daemon-port/daemon-runtime-port-support.ts b/packages/maestro/src/daemon-port/daemon-runtime-port-support.ts index a8b87f36d2..38c823f9d3 100644 --- a/packages/maestro/src/daemon-port/daemon-runtime-port-support.ts +++ b/packages/maestro/src/daemon-port/daemon-runtime-port-support.ts @@ -1,4 +1,5 @@ import type { CommandFlags } from '@agent-device/contracts/command'; +import type { ReplayBackendHost } from '@agent-device/contracts/replay-backend'; import path from 'node:path'; import type { MaestroObservation, @@ -22,7 +23,10 @@ export type MaestroDaemonOperationInvoke = ( request: MaestroDaemonOperationRequest, ) => Promise; -export type CreateDaemonMaestroRuntimeOperationsOptions = { +export type CreateDaemonMaestroRuntimeOperationsOptions = Pick< + ReplayBackendHost, + 'readSnapshotClickabilityEvidence' | 'assertSnapshotScreenOrigin' +> & { readonly invoke: MaestroDaemonOperationInvoke; /** The runtime envelope every operation carries: platform, target, device, and recording flags. */ readonly flags?: CommandFlags; diff --git a/packages/maestro/src/daemon-port/daemon-runtime-port.ts b/packages/maestro/src/daemon-port/daemon-runtime-port.ts index 44ae555403..9e7fb91342 100644 --- a/packages/maestro/src/daemon-port/daemon-runtime-port.ts +++ b/packages/maestro/src/daemon-port/daemon-runtime-port.ts @@ -10,7 +10,6 @@ import { } from '@agent-device/maestro'; import { registerDiagnosticSensitiveValue } from '@agent-device/host-kit/diagnostics'; import { AppError } from '@agent-device/kernel/errors'; -import { assertSnapshotScreenOrigin } from '@agent-device/contracts/capture'; import { stripUndefined } from '@agent-device/kernel/record'; import { executeRunScriptFile } from './run-script-execution.ts'; import { captureMaestroComparisonScreenshot } from './maestro-comparison-screenshot.ts'; @@ -301,7 +300,8 @@ function createDaemonMaestroRuntimeParts(options: CreateDaemonMaestroRuntimeOper input.durationMs, platform, ); - if (gesture) await assertSnapshotScreenOrigin(snapshot.nodes, 'Maestro scroll target'); + if (gesture) + await options.assertSnapshotScreenOrigin(snapshot.nodes, 'Maestro scroll target'); await invokeMutation( gesture ? { kind: 'swipe', ...gesture } diff --git a/packages/maestro/src/daemon-port/daemon-runtime-tap.ts b/packages/maestro/src/daemon-port/daemon-runtime-tap.ts index 1ebf721e7b..ed241456ea 100644 --- a/packages/maestro/src/daemon-port/daemon-runtime-tap.ts +++ b/packages/maestro/src/daemon-port/daemon-runtime-tap.ts @@ -1,5 +1,4 @@ import { AppError, asAppError } from '@agent-device/kernel/errors'; -import { assertSnapshotScreenOrigin } from '@agent-device/contracts/capture'; import { INTERACTION_ERROR_REASONS } from '@agent-device/selectors/interaction-error'; import type { Rect } from '@agent-device/kernel/snapshot'; import { @@ -52,7 +51,7 @@ export async function resolveDaemonMaestroTarget(params: { { context, snapshot: snapshots.capture, dependencies: options.dependencies }, deadline, ); - await assertSnapshotScreenOrigin(currentSnapshot.nodes, 'Maestro selector target'); + await options.assertSnapshotScreenOrigin(currentSnapshot.nodes, 'Maestro selector target'); const match = resolveTypedMaestroTarget({ query: input, context, diff --git a/packages/maestro/src/index.test.ts b/packages/maestro/src/index.test.ts index 4a7ec925e8..204c3602ef 100644 --- a/packages/maestro/src/index.test.ts +++ b/packages/maestro/src/index.test.ts @@ -22,18 +22,19 @@ describe('@agent-device/maestro facade', () => { test('keeps the plugin and helper off the engine entry and declares pure modules', () => { const manifest = JSON.parse( fs.readFileSync(path.join(import.meta.dirname, '../package.json'), 'utf8'), - ) as { exports: Record; sideEffects?: boolean }; - // The runScript HTTP helper is a subpath, not part of the engine entry, and the replay - // backend plugin (#3377) is the only other way in: its engine-free declaration lets help list - // the backend without evaluating the engine. This pins the surface; - // scripts/__tests__/eager-closure-budgets.test.ts is what keeps `.` from starting to evaluate - // host-kit, capture-kit, or provision-kit. + ) as { + exports: Record; + publishConfig: { exports: Record }; + sideEffects?: boolean; + }; expect(Object.keys(manifest.exports)).toEqual([ '.', './replay-backend', './replay-backend-declaration', './run-script-http', + './agent-device', ]); + expect(Object.keys(manifest.publishConfig.exports)).toEqual(['./agent-device']); expect(manifest.sideEffects).toBe(false); }); }); diff --git a/packages/maestro/src/plugin.test.ts b/packages/maestro/src/plugin.test.ts new file mode 100644 index 0000000000..a01c37e41f --- /dev/null +++ b/packages/maestro/src/plugin.test.ts @@ -0,0 +1,105 @@ +import assert from 'node:assert/strict'; +import { beforeEach, expect, test, vi } from 'vitest'; +import type { ReplayBackendHost } from '@agent-device/contracts/replay-backend'; +import type { retainPngWorker } from '@agent-device/capture-kit/png-worker-client'; + +const state = vi.hoisted(() => ({ + engineLoads: 0, + retain: vi.fn(), +})); + +vi.mock('./replay-backend/replay-maestro-backend.ts', async (importOriginal) => { + state.engineLoads += 1; + return await importOriginal(); +}); + +vi.mock('@agent-device/capture-kit/png-worker-client', async (importOriginal) => ({ + ...(await importOriginal()), + retainPngWorker: state.retain, +})); + +const setupHost = { + env: {}, + options: {}, + clientVersion: '0.22.0-dev', + createError: () => { + throw new Error('setup must not use host services'); + }, +}; + +beforeEach(() => { + vi.resetModules(); + state.engineLoads = 0; + state.retain.mockReset(); +}); + +test('factory setup and unused disposal leave the engine and PNG worker unloaded', async () => { + const { default: maestroPlugin } = await import('./plugin.ts'); + const plugin = maestroPlugin(); + expect({ apiVersion: plugin.apiVersion, kind: plugin.kind, backend: plugin.backend }).toEqual({ + apiVersion: 2, + kind: 'replay-backend', + backend: 'maestro', + }); + + const setup = await plugin.setup(setupHost); + await setup.dispose?.(); + + expect(state.engineLoads).toBe(0); + expect(state.retain).not.toHaveBeenCalled(); +}); + +test('selected creation retains one worker, forwards its diagnostic to the host and releases it', async () => { + const sinks: Parameters[0][] = []; + const release = vi.fn(async () => {}); + state.retain.mockImplementation((sink) => { + sinks.push(sink); + return release; + }); + const host: ReplayBackendHost = { + emitDiagnostic: vi.fn(), + appendTraceEvent: () => { + throw new Error('trace unused'); + }, + buildBuiltinVars: () => { + throw new Error('variables unused'); + }, + readScriptSourceFile: () => { + throw new Error('source reader unused'); + }, + readSnapshotClickabilityEvidence: () => undefined, + assertSnapshotScreenOrigin: () => Promise.reject(new Error('screen origin unused')), + scriptSourceRequiredMessage: '', + resolveTargetDevice: () => Promise.reject(new Error('device selection unused')), + requestSignal: () => undefined, + buildActionFailureResponse: () => Promise.reject(new Error('failure response unused')), + }; + const { default: maestroPlugin } = await import('./plugin.ts'); + const setup = await maestroPlugin().setup(setupHost); + const backend = await setup.replayBackend.create(host); + const nextBackend = await setup.replayBackend.create(host); + + expect(state.engineLoads).toBe(1); + expect(backend.id).toBe('maestro'); + expect( + nextBackend.inspectSource( + 'appId: com.example.app\nname: Checkout\n---\n- launchApp', + '/flow.yaml', + ), + ).toEqual({ title: 'Checkout', appTarget: 'com.example.app' }); + expect(state.retain).toHaveBeenCalledTimes(1); + expect(release).not.toHaveBeenCalled(); + + const reason = { kind: 'worker-exited', detail: 'exit code 1' } as const; + const onUnavailable = sinks[0]; + assert.ok(onUnavailable); + onUnavailable(reason); + expect(host.emitDiagnostic).toHaveBeenCalledExactlyOnceWith({ + level: 'warn', + phase: 'png_worker_unavailable', + data: { reason: reason.kind, detail: reason.detail }, + }); + + await setup.dispose?.(); + expect(release).toHaveBeenCalledTimes(1); +}); diff --git a/packages/maestro/src/plugin.ts b/packages/maestro/src/plugin.ts new file mode 100644 index 0000000000..2369152c92 --- /dev/null +++ b/packages/maestro/src/plugin.ts @@ -0,0 +1,36 @@ +import type { ReplayEnginePlugin } from 'agent-device/plugins'; + +/** The managed entry is engine-free. Only a selected backend evaluates the implementation. */ +function maestroPlugin(): ReplayEnginePlugin { + return { + apiVersion: 2, + kind: 'replay-backend', + backend: 'maestro', + setup: () => { + let releasePngWorker: (() => Promise) | undefined; + return { + replayBackend: { + create: async (host) => { + const [{ maestroReplayBackendPlugin }, { retainPngWorker }] = await Promise.all([ + import('./replay-backend/replay-maestro-backend.ts'), + import('@agent-device/capture-kit/png-worker-client'), + ]); + releasePngWorker ??= retainPngWorker((reason) => + host.emitDiagnostic({ + level: 'warn', + phase: 'png_worker_unavailable', + data: { reason: reason.kind, detail: reason.detail }, + }), + ); + return await maestroReplayBackendPlugin.create(host); + }, + }, + dispose: async () => { + await releasePngWorker?.(); + }, + }; + }, + }; +} + +export { maestroPlugin as default }; diff --git a/packages/maestro/src/replay-backend/__tests__/replay-maestro-backend.test.ts b/packages/maestro/src/replay-backend/__tests__/replay-maestro-backend.test.ts index 68e4237f19..8c2d989b41 100644 --- a/packages/maestro/src/replay-backend/__tests__/replay-maestro-backend.test.ts +++ b/packages/maestro/src/replay-backend/__tests__/replay-maestro-backend.test.ts @@ -7,6 +7,9 @@ import { maestroReplayBackendPlugin } from '../replay-maestro-backend.ts'; // each test the behavior through the registry; what is pinned here is the adapter's own mapping. // None of these capabilities reach host services, so the host is never called. const unusedHost: ReplayBackendHost = { + emitDiagnostic: () => { + throw new Error('host unused'); + }, appendTraceEvent: () => { throw new Error('host unused'); }, @@ -16,6 +19,8 @@ const unusedHost: ReplayBackendHost = { readScriptSourceFile: () => { throw new Error('host unused'); }, + readSnapshotClickabilityEvidence: () => undefined, + assertSnapshotScreenOrigin: () => Promise.reject(new Error('host unused')), scriptSourceRequiredMessage: '', resolveTargetDevice: () => Promise.reject(new Error('host unused')), requestSignal: () => undefined, diff --git a/packages/maestro/src/replay-backend/__tests__/session-replay-maestro-failure.test.ts b/packages/maestro/src/replay-backend/__tests__/session-replay-maestro-failure.test.ts index 6617455911..4987caa3bc 100644 --- a/packages/maestro/src/replay-backend/__tests__/session-replay-maestro-failure.test.ts +++ b/packages/maestro/src/replay-backend/__tests__/session-replay-maestro-failure.test.ts @@ -78,9 +78,12 @@ test('the failure response hands the host the step, its warnings, and its sugges await buildTypedMaestroFailureResponse( { + emitDiagnostic: () => {}, appendTraceEvent: () => {}, buildBuiltinVars: () => ({}), readScriptSourceFile: () => '', + readSnapshotClickabilityEvidence: () => undefined, + assertSnapshotScreenOrigin: () => Promise.reject(new Error('unused')), scriptSourceRequiredMessage: '', resolveTargetDevice: () => Promise.reject(new Error('unused')), requestSignal: () => undefined, diff --git a/packages/maestro/src/replay-backend/replay-maestro-backend.ts b/packages/maestro/src/replay-backend/replay-maestro-backend.ts index f0bc099c1d..6064337116 100644 --- a/packages/maestro/src/replay-backend/replay-maestro-backend.ts +++ b/packages/maestro/src/replay-backend/replay-maestro-backend.ts @@ -44,6 +44,6 @@ function createMaestroReplayBackend(host: ReplayBackendHost): ReplayBackend<'mae }; } -export const maestroReplayBackendPlugin: ReplayBackendPlugin<'maestro'> = { +export const maestroReplayBackendPlugin = { create: createMaestroReplayBackend, -}; +} satisfies ReplayBackendPlugin<'maestro'>; diff --git a/packages/maestro/src/replay-backend/session-replay-maestro-runtime.ts b/packages/maestro/src/replay-backend/session-replay-maestro-runtime.ts index 451576385e..37b5e9fea0 100644 --- a/packages/maestro/src/replay-backend/session-replay-maestro-runtime.ts +++ b/packages/maestro/src/replay-backend/session-replay-maestro-runtime.ts @@ -116,6 +116,7 @@ async function executeTypedMaestroReplay( // for flows that did not arrive over the daemon's remote HTTP surface. const publicNetworkOnly = command.publicNetworkOnly === true; const port = createMaestroReplayPort({ + host, command, device: context.device, platform: context.platform, @@ -334,6 +335,7 @@ function buildTypedMaestroEnv(req: DaemonWireRequest, hostEnv: EnvMap): Record; @@ -349,6 +351,8 @@ function createMaestroReplayPort(params: { ...(command.dispatch ? { dispatch: command.dispatch } : {}), }; return createDaemonMaestroRuntimePort({ + readSnapshotClickabilityEvidence: params.host.readSnapshotClickabilityEvidence, + assertSnapshotScreenOrigin: params.host.assertSnapshotScreenOrigin, invoke: (operation) => invoke(maestroOperationDispatchRequest(replay, operation)), flags: maestroRuntimeDeviceFlags(device, platform, req.flags, publicNetworkOnly), publicNetworkOnly, diff --git a/packages/maestro/test/package-artifact.test.mjs b/packages/maestro/test/package-artifact.test.mjs new file mode 100644 index 0000000000..75daa18f60 --- /dev/null +++ b/packages/maestro/test/package-artifact.test.mjs @@ -0,0 +1,57 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; +import { run, assertPackagedRunScriptChildren } from './package-test-support.mjs'; + +const root = path.resolve(import.meta.dirname, '../../..'); + +test('packed managed plugin contains its factory and runs real script children without workspace dependencies', async () => { + const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-maestro-artifact-')); + try { + const pluginTarball = path.join(scratch, 'maestro.tgz'); + run('pnpm', ['pack', '--out', pluginTarball], path.join(root, 'packages/maestro')); + const store = path.join(scratch, 'store'); + fs.mkdirSync(store); + fs.writeFileSync(path.join(store, 'package.json'), '{"private":true,"type":"module"}'); + run('npm', ['install', '--ignore-scripts', '--no-audit', '--no-fund', pluginTarball], store); + const plugin = path.join(store, 'node_modules/@agent-device/maestro'); + const manifest = JSON.parse(fs.readFileSync(path.join(plugin, 'package.json'), 'utf8')); + assert.deepEqual(Object.keys(manifest.exports), ['./agent-device']); + assert.equal(manifest.dependencies, undefined); + assert.equal(manifest.peerDependencies, undefined); + assert.ok(!fs.existsSync(path.join(store, 'node_modules/agent-device'))); + for (const entry of [ + 'agent-device.mjs', + 'agent-device.d.mts', + 'png-worker.mjs', + 'run-script-child.mjs', + 'run-script-http-child.mjs', + ]) + assert.ok(fs.existsSync(path.join(plugin, 'dist', entry)), entry); + await assertPackagedRunScriptChildren(plugin, scratch); + run( + process.execPath, + [ + '--experimental-strip-types', + path.join(import.meta.dirname, 'packed-clickability.mjs'), + plugin, + scratch, + ], + root, + ); + run( + process.execPath, + [ + '--experimental-strip-types', + path.join(import.meta.dirname, 'packed-screen-origin.mjs'), + plugin, + scratch, + ], + root, + ); + } finally { + fs.rmSync(scratch, { recursive: true, force: true }); + } +}); diff --git a/packages/maestro/test/package-test-support.mjs b/packages/maestro/test/package-test-support.mjs new file mode 100644 index 0000000000..e88c41f817 --- /dev/null +++ b/packages/maestro/test/package-test-support.mjs @@ -0,0 +1,49 @@ +import { runCmdSync } from '@agent-device/host-kit/command'; +import http from 'node:http'; +import { promisify } from 'node:util'; +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; + +function run(command, args, cwd, env = process.env) { + return runCmdSync(command, args, { + cwd, + env, + timeoutMs: 120_000, + maxBuffer: 16 * 1024 * 1024, + }).stdout; +} +async function assertPackagedRunScriptChildren(plugin, scratch) { + const alias = path.join(scratch, 'plugin-alias'); + fs.symlinkSync(plugin, alias, process.platform === 'win32' ? 'junction' : 'dir'); + const server = http.createServer((_request, response) => + response.end('x'.repeat(2 * 1024 * 1024)), + ); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { + const scriptPath = path.join(scratch, 'http.js'); + fs.writeFileSync(scriptPath, 'output.size = http.post(SERVER_URL).body.length'); + for (const directory of [plugin, alias]) { + const result = promisify(execFile)( + process.execPath, + [path.join(directory, 'dist/run-script-child.mjs')], + { timeout: 120_000, maxBuffer: 16 * 1024 * 1024 }, + ); + result.child.stdin.end( + JSON.stringify({ + scriptPath, + env: { SERVER_URL: `http://127.0.0.1:${server.address().port}/` }, + publicNetworkOnly: false, + }), + ); + assert.deepEqual(JSON.parse((await result).stdout), { + outputEnv: { 'output.size': String(2 * 1024 * 1024) }, + }); + } + } finally { + await new Promise((resolve) => server.close(resolve)); + } +} + +export { run, assertPackagedRunScriptChildren }; diff --git a/packages/maestro/test/packed-clickability.mjs b/packages/maestro/test/packed-clickability.mjs new file mode 100644 index 0000000000..df66440b27 --- /dev/null +++ b/packages/maestro/test/packed-clickability.mjs @@ -0,0 +1,102 @@ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { + parseUiHierarchyTree, + buildUiHierarchySnapshot, +} from '../../platform-android/src/ui-hierarchy.ts'; +import { buildAndroidSnapshotClickabilityEvidence } from '../../platform-android/src/snapshot-clickability.ts'; +import { + createAndroidSnapshotCapture, + androidSnapshotPublicationInput, +} from '../../platform-android/src/snapshot-capture.ts'; +import { readSnapshotClickabilityEvidence } from '../../contracts/src/snapshot-private-evidence.ts'; +import { createReplayBackendHost } from '../../replay-port/src/daemon-port/replay-backend-host.ts'; + +const [plugin, scratch] = process.argv.slice(2); +const { default: maestroPlugin } = await import( + pathToFileURL(path.join(plugin, 'dist/agent-device.mjs')) +); +const target = 'maestro-clickable-first-target'; +const setup = maestroPlugin().setup(); +const host = { + ...createReplayBackendHost(), + resolveTargetDevice: () => { + throw new Error('explicit platform must not discover devices'); + }, + buildActionFailureResponse: (failure) => { + throw new Error(JSON.stringify(failure.error)); + }, +}; +const backend = await setup.replayBackend.create(host); + +try { + for (const indexed of [false, true]) { + let selection = 'none'; + const points = []; + const expectedPoint = indexed ? [20, 20] : [20, 80]; + const expectedSelection = indexed ? 'inert' : 'clickable'; + const entry = path.join(scratch, `clickability-${indexed}.yaml`); + const source = `appId: com.example.app\n---\n- tapOn:\n id: ${target}\n${indexed ? ' index: 0\n' : ''}- assertVisible:\n text: "Maestro selection: ${expectedSelection}"\n`; + const capture = () => { + const xml = ``; + const built = buildUiHierarchySnapshot(parseUiHierarchyTree(xml), undefined, {}); + const { sourceNodes: _sourceNodes, occlusionContext, ...snapshot } = built; + const data = androidSnapshotPublicationInput( + createAndroidSnapshotCapture( + { ...snapshot, createdAt: Date.now(), androidSnapshot: {} }, + { clickability: buildAndroidSnapshotClickabilityEvidence(built), occlusionContext }, + ), + ); + assert.equal(readSnapshotClickabilityEvidence(data)?.kind, 'exact'); + assert.ok(data.nodes.every((node) => !Object.hasOwn(node, 'clickable'))); + return data; + }; + const result = await backend.runReplay({ + request: { + command: 'replay', + positionals: [entry], + flags: { + platform: 'android', + replayBackend: 'maestro', + replayScriptSource: { entry, files: { [entry]: source } }, + }, + }, + host: { env: {}, cwd: scratch }, + session: { + name: 'packed-clickability', + logPath: path.join(scratch, 'clickability.log'), + store: { + get: () => undefined, + lookup: () => undefined, + resolveOpenRuntimeHints: () => undefined, + }, + }, + invoke: async (request) => { + if (request.command === 'snapshot') return { ok: true, data: capture() }; + if (request.command === 'runtime') + return { ok: true, data: { viewport: { x: 0, y: 0, width: 200, height: 200 } } }; + if (request.command === 'click') { + const point = request.positionals.map(Number); + points.push(point); + assert.deepEqual( + point, + expectedPoint, + indexed + ? 'explicit index must retain source order' + : 'no-index Maestro must select the clickable duplicate', + ); + selection = point[1] < 40 ? 'inert' : 'clickable'; + return { ok: true, data: {} }; + } + throw new Error(`unexpected native boundary command: ${request.command}`); + }, + }); + assert.equal(result.ok, true, JSON.stringify(result)); + assert.equal(result.data.replayed, 2); + assert.deepEqual(points, [expectedPoint]); + } + console.log('packed clickability: no-index and explicit-index contracts passed'); +} finally { + await setup.dispose(); +} diff --git a/packages/maestro/test/packed-screen-origin.mjs b/packages/maestro/test/packed-screen-origin.mjs new file mode 100644 index 0000000000..e3b82d68a2 --- /dev/null +++ b/packages/maestro/test/packed-screen-origin.mjs @@ -0,0 +1,108 @@ +import assert from 'node:assert/strict'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { createIosSnapshotAcquisition } from '../../capture-kit/src/ios-snapshot-acquisition.ts'; +import { presentIosSnapshotAcquisition } from '../../capture-kit/src/snapshot/ios-snapshot-runtime.ts'; +import { buildSnapshotState } from '../../capture-kit/src/snapshot-state.ts'; +import { createReplayBackendHost } from '../../replay-port/src/daemon-port/replay-backend-host.ts'; + +const [plugin, scratch] = process.argv.slice(2); +const { default: maestroPlugin } = await import( + pathToFileURL(path.join(plugin, 'dist/agent-device.mjs')) +); +const setup = maestroPlugin().setup(); +const backend = await setup.replayBackend.create({ + ...createReplayBackendHost(), + resolveTargetDevice: () => { + throw new Error('explicit platform must not discover devices'); + }, + buildActionFailureResponse: async ({ error }) => ({ ok: false, error }), +}); +const rect = { x: 0, y: 0, width: 390, height: 844 }; + +try { + for (const kind of ['derived', 'missing', 'reported']) { + for (const action of ['tap', 'scroll']) { + let dispatched = false; + const requests = []; + const nodes = [ + { index: 0, type: 'Application', rect }, + { index: 1, parentIndex: 0, type: 'ScrollView', identifier: 'container', rect }, + { + index: 2, + parentIndex: 1, + type: 'Button', + identifier: 'action', + label: 'Action', + rect: { x: 100, y: 100, width: 80, height: 40 }, + }, + ]; + const entry = path.join(scratch, `screen-origin-${kind}-${action}.yaml`); + const source = `appId: com.example.app\n---\n${action === 'tap' ? '- tapOn:\n id: action\n index: 0\n' : '- scrollUntilVisible:\n element: Found\n direction: DOWN\n timeout: 1000\n'}`; + const result = await backend.runReplay({ + request: { + command: 'replay', + positionals: [entry], + flags: { + platform: 'ios', + replayBackend: 'maestro', + replayScriptSource: { entry, files: { [entry]: source } }, + }, + }, + host: { env: {}, cwd: scratch }, + session: { + name: 'packed-screen-origin', + logPath: path.join(scratch, 'screen-origin.log'), + store: { + get: () => undefined, + lookup: () => undefined, + resolveOpenRuntimeHints: () => undefined, + }, + }, + invoke: async (request) => { + requests.push(request); + if (request.command === 'snapshot') { + const acquisition = createIosSnapshotAcquisition({ + producer: 'appium-source', + nodes: dispatched + ? [...nodes, { index: 3, parentIndex: 1, type: 'StaticText', label: 'Found', rect }] + : nodes, + viewport: kind === 'missing' ? { kind, reason: 'not-provided' } : { kind, rect }, + lineage: { targetId: 'ios-origin:com.example.app' }, + }); + return { + ok: true, + data: buildSnapshotState(presentIosSnapshotAcquisition(acquisition, { raw: true }), { + snapshotRaw: true, + }), + }; + } + if (request.command === 'runtime') return { ok: true, data: { viewport: rect } }; + if (request.command === 'click' || request.command === 'gesture') { + dispatched = true; + return { ok: true, data: {} }; + } + throw new Error(`unexpected native boundary command: ${request.command}`); + }, + }); + if (kind === 'reported') { + assert.equal(result.ok, true, JSON.stringify(result)); + assert.equal(result.data.replayed, 1); + assert.equal(dispatched, true, `${action} must dispatch with reported origin`); + const input = requests.find( + ({ command }) => command === (action === 'tap' ? 'click' : 'gesture'), + ); + assert.ok(input); + if (action === 'tap') assert.deepEqual(input.positionals, ['140', '120']); + } else { + assert.equal(dispatched, false, `${kind} ${action} must refuse before input`); + assert.equal(result.ok, false); + assert.equal(result.error.details.reason, 'window-origin-unknown'); + assert.equal(result.error.details.dispatched, 'no'); + } + } + } + console.log('packed screen origin: derived/missing refusal and reported tap/scroll passed'); +} finally { + await setup.dispose(); +} diff --git a/packages/maestro/tsconfig.json b/packages/maestro/tsconfig.json index 6614d7d44e..8c7b3a73e0 100644 --- a/packages/maestro/tsconfig.json +++ b/packages/maestro/tsconfig.json @@ -6,17 +6,34 @@ "emitDeclarationOnly": true, "declaration": true, "declarationDir": "./dist-types", - "rootDir": "./src", - "tsBuildInfoFile": "./dist-types/index.tsbuildinfo" + "rootDir": ".", + "tsBuildInfoFile": "./dist-types/index.tsbuildinfo", + "paths": { + "agent-device/plugins": ["./node_modules/agent-device/src/sdk/plugins.ts"] + } }, "include": ["src"], "references": [ - { "path": "../ad-script" }, - { "path": "../capture-kit" }, - { "path": "../contracts" }, - { "path": "../host-kit" }, - { "path": "../kernel" }, - { "path": "../provision-kit" }, - { "path": "../selectors" } + { + "path": "../ad-script" + }, + { + "path": "../capture-kit" + }, + { + "path": "../contracts" + }, + { + "path": "../host-kit" + }, + { + "path": "../kernel" + }, + { + "path": "../provision-kit" + }, + { + "path": "../selectors" + } ] } diff --git a/packages/maestro/tsdown.config.ts b/packages/maestro/tsdown.config.ts new file mode 100644 index 0000000000..d1d1807d28 --- /dev/null +++ b/packages/maestro/tsdown.config.ts @@ -0,0 +1,29 @@ +import { defineConfig } from 'tsdown'; + +export default defineConfig({ + entry: { + 'agent-device': 'src/plugin.ts', + 'png-worker': '../capture-kit/src/png-worker.ts', + 'run-script-child': 'src/daemon-port/run-script-child.ts', + 'run-script-http-child': 'src/daemon-port/run-script-http-child.ts', + }, + outDir: 'dist', + tsconfig: '../../tsconfig.lib.json', + format: 'esm', + platform: 'node', + target: 'es2022', + minify: true, + dts: true, + hash: false, + deps: { + neverBundle: ['agent-device/plugins'], + alwaysBundle: [/^@agent-device\//], + onlyBundle: ['yaml', 'undici', 'ipaddr.js', 'pngjs', 'jpeg-js'], + }, + inputOptions: { + onLog(level, log, handler) { + if (log.code === 'UNRESOLVED_IMPORT') throw new Error(log.message); + handler(level, log); + }, + }, +}); diff --git a/packages/plugins/package.json b/packages/plugins/package.json index a5d803b8fc..5bbe4534db 100644 --- a/packages/plugins/package.json +++ b/packages/plugins/package.json @@ -41,6 +41,10 @@ "./credential-fingerprint": { "types": "./src/credential-fingerprint.ts", "default": "./src/credential-fingerprint.ts" + }, + "./replay-backend": { + "types": "./src/replay-backend.ts", + "default": "./src/replay-backend.ts" } }, "devDependencies": { diff --git a/packages/plugins/src/replay-backend.ts b/packages/plugins/src/replay-backend.ts new file mode 100644 index 0000000000..55944fe4fc --- /dev/null +++ b/packages/plugins/src/replay-backend.ts @@ -0,0 +1,15 @@ +import type { ReplayBackendPlugin } from '@agent-device/contracts/replay-backend'; +import type { ProviderPluginHost } from './host.ts'; + +/** A managed v2 replay engine. The host retains sessions, dispatch, cancellation and cleanup. */ +export type ReplayEnginePlugin = Readonly<{ + apiVersion: 2; + kind: 'replay-backend'; + backend: string; + setup(host: ProviderPluginHost): Promise | ReplayEngineSetup; +}>; + +export type ReplayEngineSetup = Readonly<{ + replayBackend: ReplayBackendPlugin; + dispose?(): Promise | void; +}>; diff --git a/packages/replay-port/src/daemon-port/replay-backend-host.ts b/packages/replay-port/src/daemon-port/replay-backend-host.ts index 2d9e6aa1e0..67c0ae8ce7 100644 --- a/packages/replay-port/src/daemon-port/replay-backend-host.ts +++ b/packages/replay-port/src/daemon-port/replay-backend-host.ts @@ -1,4 +1,9 @@ +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import type { ReplayBackendHost } from '@agent-device/contracts/replay-backend'; +import { + assertSnapshotScreenOrigin, + readSnapshotClickabilityEvidence, +} from '@agent-device/contracts/capture'; import { resolveTargetDevice } from '@agent-device/device-selection/dispatch-resolve'; import { getRequestSignal } from '@agent-device/host-kit/request'; import { buildReplayBuiltinVars } from '../session-replay-vars.ts'; @@ -16,6 +21,9 @@ import { appendReplayTraceEvent } from './session-replay-trace.ts'; */ export function createReplayBackendHost(): ReplayBackendHost { return { + emitDiagnostic, + readSnapshotClickabilityEvidence, + assertSnapshotScreenOrigin, appendTraceEvent: appendReplayTraceEvent, buildBuiltinVars: (params) => buildReplayBuiltinVars({ ...params, metadata: {} }), readScriptSourceFile: readReplayScriptSourceFile, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a899704bfe..4dec8b9b81 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -244,13 +244,16 @@ importers: version: 3.2.0 tsdown: specifier: ^0.22.14 - version: 0.22.14(@arethetypeswrong/core@0.18.5)(@volar/typescript@2.4.30(typescript@7.0.2))(publint@0.3.24)(typescript@7.0.2) + version: 0.22.14(@arethetypeswrong/core@0.18.5)(@volar/typescript@2.4.30(typescript@7.0.2))(publint@0.3.24)(typescript@7.0.2)(unrun@0.3.1) typescript: specifier: ^7.0.2 version: 7.0.2 undici: specifier: 7.30.1 version: 7.30.1 + unrun: + specifier: 0.3.1 + version: 0.3.1 vite: specifier: ^8.3.5 version: 8.3.5(@types/node@22.20.1)(yaml@2.9.0) @@ -682,7 +685,7 @@ importers: packages/kernel: {} packages/maestro: - dependencies: + devDependencies: '@agent-device/ad-script': specifier: workspace:* version: link:../ad-script @@ -704,7 +707,9 @@ importers: '@agent-device/selectors': specifier: workspace:* version: link:../selectors - devDependencies: + agent-device: + specifier: workspace:* + version: link:../.. undici: specifier: 7.30.1 version: 7.30.1 @@ -5418,6 +5423,16 @@ packages: unist-util-visit@5.1.0: resolution: {integrity: sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==} + unrun@0.3.1: + resolution: {integrity: sha512-onIck/oNnCaytwths1ZVp1LK2Gq2hPoyFhiHebObuUXqR3S0uHuLLaBK8K6mRRgV7Ptip8AnNvaUsgzwWwBZuA==} + engines: {node: ^22.13.0 || >=24.0.0} + hasBin: true + peerDependencies: + synckit: ^0.11.11 + peerDependenciesMeta: + synckit: + optional: true + unstorage@1.17.6: resolution: {integrity: sha512-gjKtcmn/KwZuJZO9o2sc0esAQnhmTw0LviDHwevTXbJMYs0dRTp8ZEEWXHU0vTpzbN3cA0yxlTeyXssMp3zDqw==} peerDependencies: @@ -9876,7 +9891,7 @@ snapshots: dependencies: typescript: 7.0.2 - tsdown@0.22.14(@arethetypeswrong/core@0.18.5)(@volar/typescript@2.4.30(typescript@7.0.2))(publint@0.3.24)(typescript@7.0.2): + tsdown@0.22.14(@arethetypeswrong/core@0.18.5)(@volar/typescript@2.4.30(typescript@7.0.2))(publint@0.3.24)(typescript@7.0.2)(unrun@0.3.1): dependencies: ansis: 4.3.1 cac: 7.0.0 @@ -9897,6 +9912,7 @@ snapshots: '@arethetypeswrong/core': 0.18.5 publint: 0.3.24 typescript: 7.0.2 + unrun: 0.3.1 transitivePeerDependencies: - '@typescript/native-preview' - '@volar/typescript' @@ -10029,6 +10045,10 @@ snapshots: unist-util-is: 6.0.1 unist-util-visit-parents: 6.0.2 + unrun@0.3.1: + dependencies: + rolldown: 1.2.15 + unstorage@1.17.6: dependencies: anymatch: 3.1.3 diff --git a/scripts/check-affected/device-lanes.test.ts b/scripts/check-affected/device-lanes.test.ts index 72452fa6ba..6ae88a0299 100644 --- a/scripts/check-affected/device-lanes.test.ts +++ b/scripts/check-affected/device-lanes.test.ts @@ -143,10 +143,15 @@ test('unit tests under src/ and packages/*/src own no lane', () => { const imeFixture = 'packages/platform-android/src/fixtures/android-ime-capture.raw.json'; assert.ok(fs.existsSync(imeFixture), imeFixture); assert.ok(!isUnitTest(imeFixture)); - // Package tests outside src/ have no owner and keep failing open. assert.ok(!isUnitTest('packages/maestro/test/conformance/verify.test.ts')); + const conformance = selectChecks({ + changedFiles: ['packages/maestro/test/conformance/verify.test.ts'], + }); + assert.equal(conformance.failOpen, false); + assert.ok(conformance.checks.includes('maestro-conformance')); + assert.ok(conformance.checks.includes('maestro-differential')); assert.equal( - selectChecks({ changedFiles: ['packages/maestro/test/conformance/verify.test.ts'] }).failOpen, + selectChecks({ changedFiles: ['packages/unknown/test/unowned.test.ts'] }).failOpen, true, ); }); diff --git a/scripts/check-affected/model.test.ts b/scripts/check-affected/model.test.ts index 46aee98647..7f15cdaa9d 100644 --- a/scripts/check-affected/model.test.ts +++ b/scripts/check-affected/model.test.ts @@ -552,3 +552,49 @@ test('every configured scan root selects native duplication regardless of extens assert.ok(ids([file]).includes('native-dupes-model'), file); } }); + +test('managed engine and loading changes retain every Maestro oracle lane', () => { + for (const file of [ + 'packages/maestro/src/plugin.ts', + 'packages/plugins/src/registry.ts', + 'packages/plugins/src/replay-backend.ts', + 'packages/plugins/src/store.ts', + 'packages/plugins/src/discovery.ts', + 'packages/plugins/src/validate.ts', + 'packages/replay-port/src/daemon-port/replay-backend-registry.ts', + ]) { + const result = plan([file]); + assert.equal(result.failOpen, false, file); + assert.ok(result.checks.includes('maestro-conformance'), file); + assert.ok(result.checks.includes('maestro-differential'), file); + } +}); + +test('Maestro conformance Vitest inputs retain their registered unit runner', () => { + for (const file of [ + 'packages/maestro/test/conformance/conformance-selector-projection.test.ts', + 'packages/maestro/test/conformance/conformance-selector-projection.ts', + 'packages/maestro/test/conformance/conformance-normalize.ts', + ]) { + assert.ok(fs.existsSync(path.join(repoRoot, file)), file); + const result = plan([file]); + assert.equal(result.failOpen, false, file); + assert.ok(result.checks.includes('unit'), `unit must run for ${file}`); + } +}); + +test('managed engine non-source inputs retain conservative full selection', () => { + for (const file of [ + 'packages/maestro/package.json', + 'packages/maestro/tsdown.config.ts', + 'packages/maestro/test/package-artifact.test.mjs', + 'packages/replay-port/package.json', + 'packages/replay-port/test/artifact.test.mjs', + ]) { + const result = plan([file]); + assert.equal(result.failOpen, true, file); + assert.ok(result.checks.includes('build'), file); + assert.ok(result.checks.includes('typecheck'), file); + assert.ok(result.checks.includes('package'), file); + } +}); diff --git a/scripts/check-affected/model.ts b/scripts/check-affected/model.ts index 3a2aa8494c..8942366ee0 100644 --- a/scripts/check-affected/model.ts +++ b/scripts/check-affected/model.ts @@ -256,6 +256,38 @@ const vitestRelatedOwnership: OwnershipRule = ({ file, isTs, underSrc, underTest ] : []; +const replayBackendOwnership: OwnershipRule = ({ file }) => + (file.endsWith('.ts') && + (file.startsWith('packages/maestro/src/') || + file.startsWith('packages/maestro/test/conformance/') || + file.startsWith('packages/replay-port/src/'))) || + /^packages\/plugins\/src\/(?:registry|replay-backend|store|discovery|validate)\./.test(file) + ? [ + reason( + 'maestro-conformance', + file, + 'own:replay-backend-conformance', + 'managed replay backends retain the generated conformance oracle', + ), + reason( + 'maestro-differential', + file, + 'own:replay-backend-differential', + 'installed replay backends retain live outcome and timing invariants', + ), + ...(file.startsWith('packages/maestro/test/conformance/') + ? [ + reason( + 'unit', + file, + 'own:maestro-conformance-unit', + 'the unit suite covers conformance selector projection and its shared helpers', + ), + ] + : []), + ] + : []; + // Workspace package source (#1490 W0): bundled into the published artifact, // type-checked in the root graph, covered by Vitest's module graph, and // guarded by layering R11. Fallow scans it too — the W0 ignorePatterns entry @@ -689,6 +721,7 @@ const OWNERSHIP_RULES: readonly OwnershipRule[] = [ macosCoverageOwnership, testAppOwnership, replayCompatOwnership, + replayBackendOwnership, daemonWireCompatOwnership, buildOwnership, nativeDupesOwnership, diff --git a/scripts/gate/workflows.test.ts b/scripts/gate/workflows.test.ts index fad6ac94d0..c4875fea9f 100644 --- a/scripts/gate/workflows.test.ts +++ b/scripts/gate/workflows.test.ts @@ -68,9 +68,13 @@ function planted(files: Record): ReturnType { } test('a command repeating a script body verbatim credits that script', () => { - const body = model.scripts['check:package'] as string; - assert.deepEqual(verbatimScripts(body, model.scripts), ['check:package']); - assert.deepEqual(verbatimScripts('node scripts/something-else.ts', model.scripts), []); + const scripts = { + verify: 'node scripts/verify.ts', + combined: 'node scripts/verify.ts && node scripts/other.ts', + }; + assert.deepEqual(verbatimScripts(scripts.verify, scripts), ['verify']); + assert.deepEqual(verbatimScripts(scripts.combined, scripts), ['verify', 'combined']); + assert.deepEqual(verbatimScripts('node scripts/something-else.ts', scripts), []); }); test('path filters use GitHub glob semantics', () => { diff --git a/scripts/gate/workflows.ts b/scripts/gate/workflows.ts index 5bafa455d2..b45c10205c 100644 --- a/scripts/gate/workflows.ts +++ b/scripts/gate/workflows.ts @@ -255,7 +255,9 @@ export function verbatimScripts( command: string, scripts: Readonly>, ): string[] { - const wanted = commandSegments(command).map((segment) => segment.replaceAll(/\s+/g, ' ')); + const wanted = [command, ...commandSegments(command)].map((segment) => + segment.replaceAll(/\s+/g, ' '), + ); return Object.entries(scripts) .filter(([, body]) => wanted.includes(body.replaceAll(/\s+/g, ' '))) .map(([name]) => name); diff --git a/scripts/layering/package-boundaries-dev-dependencies.test.ts b/scripts/layering/package-boundaries-dev-dependencies.test.ts index 7d0ff537ef..b0fb9f54e7 100644 --- a/scripts/layering/package-boundaries-dev-dependencies.test.ts +++ b/scripts/layering/package-boundaries-dev-dependencies.test.ts @@ -101,3 +101,17 @@ test('a published package keeps its siblings in devDependencies for every file', assert.deepEqual(violations(published, file), [], file); } }); + +test('a private publication placeholder keeps bundled dependencies in the publication field', () => { + const staged = { + ...DEV_ONLY, + publishConfig: { exports: { './agent-device': { import: './dist/plugin.mjs' } } }, + }; + assert.deepEqual(violations(staged, 'packages/owner/src/thing.ts'), []); + const undeclared = violations({ ...staged, devDependencies: {} }, 'packages/owner/src/thing.ts'); + assert.equal(undeclared.length, 1); + assert.match(undeclared[0]!.message, /without declaring "@agent-device\/helper"/); + const privateDevOnly = violations(DEV_ONLY, 'packages/owner/src/thing.ts'); + assert.equal(privateDevOnly.length, 1); + assert.match(privateDevOnly[0]!.message, /declare it in dependencies/); +}); diff --git a/scripts/layering/package-boundaries.test.ts b/scripts/layering/package-boundaries.test.ts index cee6d6dc56..9fe4198665 100644 --- a/scripts/layering/package-boundaries.test.ts +++ b/scripts/layering/package-boundaries.test.ts @@ -675,11 +675,9 @@ test('the real tree parses, declares, and passes R11', () => { ]); const maestroPackage = packages.find((pkg) => pkg.name === '@agent-device/maestro'); assert.ok(maestroPackage, 'maestro package must exist'); - // Locks the export surface: `.` (the engine), the replay backend plugin (#3377) with its - // engine-free declaration, and the runScript HTTP helper. The eager-closure budget gate - // (scripts/__tests__/eager-closure-budgets.test.ts) is what keeps the plugin off `.`. assert.deepEqual([...maestroPackage.exportTargets.keys()].sort(), [ '@agent-device/maestro', + '@agent-device/maestro/agent-device', '@agent-device/maestro/replay-backend', '@agent-device/maestro/replay-backend-declaration', '@agent-device/maestro/run-script-http', @@ -692,6 +690,7 @@ test('the real tree parses, declares, and passes R11', () => { '@agent-device/kernel', '@agent-device/provision-kit', '@agent-device/selectors', + 'agent-device', ]); const adScriptPackage = packages.find((pkg) => pkg.name === '@agent-device/ad-script'); assert.ok(adScriptPackage, 'ad-script package must exist'); diff --git a/scripts/layering/package-boundaries.ts b/scripts/layering/package-boundaries.ts index 0b4a70f31d..b19d1dbc57 100644 --- a/scripts/layering/package-boundaries.ts +++ b/scripts/layering/package-boundaries.ts @@ -147,6 +147,7 @@ export function workspacePackagesFromManifests( const manifest = JSON.parse(manifests.get(manifestFile)!) as { name?: string; private?: boolean; + publishConfig?: { exports?: unknown }; exports?: | string | Record; @@ -179,14 +180,16 @@ export function workspacePackagesFromManifests( ), ), ); - const workspaceDependencyField = manifest.private === true ? 'dependencies' : 'devDependencies'; + const bundledForPublication = + manifest.private !== true || manifest.publishConfig?.exports !== undefined; + const workspaceDependencyField = bundledForPublication ? 'devDependencies' : 'dependencies'; const workspaceDependencies = new Set( Object.entries(manifest[workspaceDependencyField] ?? {}) .filter(([, range]) => range.startsWith('workspace:')) .map(([name]) => name), ); const workspaceDevDependencies = new Set( - manifest.private === true + !bundledForPublication ? Object.entries(manifest.devDependencies ?? {}) .filter(([, range]) => range.startsWith('workspace:')) .map(([name]) => name) diff --git a/src/sdk/plugins.ts b/src/sdk/plugins.ts index 15dca39bd1..851631fa16 100644 --- a/src/sdk/plugins.ts +++ b/src/sdk/plugins.ts @@ -25,3 +25,6 @@ export type AgentDevicePluginFactory> = Contra Options, CloudWebDriverProviderOptions >; + +export type { ReplayEnginePlugin, ReplayEngineSetup } from '@agent-device/plugins/replay-backend'; +export type { ReplayBackend, ReplayBackendHost } from '@agent-device/contracts/replay-backend'; diff --git a/test/repo-guards/npm-package-scripts.test.ts b/test/repo-guards/npm-package-scripts.test.ts index 7ad65885a9..8de50a35e4 100644 --- a/test/repo-guards/npm-package-scripts.test.ts +++ b/test/repo-guards/npm-package-scripts.test.ts @@ -98,7 +98,11 @@ test('publishing cannot skip the package gate', () => { assert.equal(getCheckSpec('package').localRunnable, true); // The minimum-Node job runs the script directly — the repo's pinned pnpm needs a newer Node than // the floor that job covers — so it must still name the same entry point the script does. - assert.match(script('check:package'), /scripts\/check-package\.ts$/); + assert.deepEqual(script('check:package').split(' && '), [ + 'node --experimental-strip-types scripts/node-test-tmpdir.ts --experimental-strip-types --test packages/maestro/test/package-artifact.test.mjs', + 'node --experimental-strip-types scripts/check-package.ts', + ]); + assert.match(packagedCliWorkflow, /with: \{ gate: package \}/); assert.match( packagedCliWorkflow, /run: node --experimental-strip-types scripts\/check-package\.ts/, diff --git a/tsdown.config.ts b/tsdown.config.ts index 5412d1a204..71ad1a64f0 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -1,9 +1,13 @@ import { buildEntries } from './scripts/build-entries.ts'; import fs from 'node:fs'; +import { createRequire } from 'node:module'; +import { pathToFileURL } from 'node:url'; import { defineConfig, type TsdownPluginOption } from 'tsdown'; import { bundledLicenseNotices } from './scripts/lib/bundled-license-notices.ts'; -const typeScriptPackageJsonUrl = import.meta.resolve('typescript/package.json'); +const typeScriptPackageJsonUrl = pathToFileURL( + createRequire(import.meta.url).resolve('typescript/package.json'), +); const { default: getTypeScript7ExePath } = await import( new URL('lib/getExePath.js', typeScriptPackageJsonUrl).href ); @@ -151,10 +155,16 @@ export default defineConfig({ hash: false, outputOptions: { codeSplitting: { - groups: publicSdkChunkGroups.flatMap(([name, dtsTest, jsTest]) => [ - { test: dtsTest, name: `${name}.d` }, - { test: jsTest, name }, - ]), + groups: [ + ...publicSdkChunkGroups.flatMap(([name, dtsTest, jsTest]) => [ + { test: dtsTest, name: `${name}.d` }, + { test: jsTest, name }, + ]), + { + test: /packages[\\/]contracts[\\/]src[\\/]replay-backend\.d\.[cm]?ts$/, + name: 'sdk-replay-backend.d', + }, + ], }, }, outExtensions: () => ({ js: '.js', dts: '.d.ts' }),