import type { CommandSchemaOverride } from '@agent-device/command-registry/command-schema'; import type { CommandResultMap } from '@agent-device/command-registry/command-result'; import { defineCommandFacet, defineCommandFamilyFromFacets } from '../family/types.ts'; import type { JsonSchema } from '../command-contract.ts'; import { booleanField, booleanSchema, integerField, jsonSchemaField, looseObjectSchema, numberSchema, objectSchema, requiredField, stringArrayField, stringArraySchema, stringField, stringSchema, } from '../command-input.ts'; import { defineFieldCommandMetadata } from '../field-command-contract.ts'; import { commonInputFromFlags, request, requiredDaemonString, requiredString, } from '../cli-grammar/common.ts'; import type { AsyncDaemonWriter, CliReader, CommandInput } from '../cli-grammar/types.ts'; import { METRO_RELOAD_FLAGS, REPLAY_FLAGS } from '@agent-device/command-registry/flag-groups'; import { withCommandRuntimeHints } from '../runtime-hints.ts'; import { collectReplayShellEnv, parseReplayCliEnvEntries, readReplayCliEnvEntries, } from '@agent-device/ad-script'; import { loadReplayScriptSourceBundle } from '@agent-device/replay-port/script-source-bundle'; import { discoverReplaySourcePaths } from '@agent-device/replay-port/source-discovery'; const REPLAY_COMMAND_NAME = 'replay'; const TEST_COMMAND_NAME = 'test'; const REPLAY_SHELL_ENV_PREFIX = 'AD_VAR_'; const replayCommandDescription = 'Run a recorded automation script, including compatible Maestro YAML flows. A script without a terminal close leaves its session active for subsequent automation.'; const testCommandDescription = 'Run one or more replay scripts as a serial test suite'; export const replayCommandMetadata = defineFieldCommandMetadata( REPLAY_COMMAND_NAME, replayCommandDescription, { path: requiredField(stringField()), update: booleanField(), backend: stringField(), maestro: booleanField(), env: stringArrayField(), metroHost: stringField('Metro/debug host hint inherited by replay-opened sessions.'), metroPort: integerField('Metro/debug port hint inherited by replay-opened sessions.'), bundleUrl: stringField('Bundle URL hint inherited by replay-opened sessions.'), // ADR 0012 decision 4 / migration step 5: replay-only resume. Named // `resumeFrom`/`resumePlanDigest` (not `from`/`planDigest`) because // `from` already means a gesture's `PointInput` on `CommandInput` // (shared flat type across every command). `test` deliberately has // neither field — it must stay a full, deterministic suite run. resumeFrom: integerField(), resumePlanDigest: stringField(), keepSession: booleanField( 'Leave the session active by suppressing exactly an authored terminal close in native .ad.', ), timeoutMs: integerField( 'Operation wall-clock budget in milliseconds (default 60000). The client allows another 30000 milliseconds for the daemon result.', ), // ADR 0012 decision 6, R1/R6: arms agent-supervised re-record repair // from the first replay attempt; optional string value is the healed // script's output path. saveScript: jsonSchemaField({ oneOf: [booleanSchema(), stringSchema()], }), // #1258: overwrite an existing --save-script target (arm-time preflight + // publish) instead of refusing. Alias: --overwrite. force: booleanField(), testIme: booleanField( 'Activate the headless Android test IME for the sessions this replay opens (default on for emulators; opt-in on real devices).', ), }, ); export const testCommandMetadata = defineFieldCommandMetadata( TEST_COMMAND_NAME, testCommandDescription, { paths: requiredField(stringArrayField()), update: booleanField(), backend: stringField(), maestro: booleanField(), env: stringArrayField(), metroHost: stringField('Metro/debug host hint inherited by each test session.'), metroPort: integerField('Metro/debug port hint inherited by each test session.'), bundleUrl: stringField('Bundle URL hint inherited by each test session.'), failFast: booleanField(), timeoutMs: integerField(), retries: integerField(), recordVideo: booleanField(), artifactsDir: stringField(), shardAll: integerField(), shardSplit: integerField(), testIme: booleanField( 'Activate the headless Android test IME for the sessions each suite attempt opens (default on for emulators; opt-in on real devices).', ), }, ); /** * This family's advertised MCP `outputSchema`s — `ReplayCommandResult` and `ReplaySuiteResult` * (`packages/contracts/src/replay.ts`) — keyed by daemon command name and projected into the * command map by `command-output-schemas.ts`. Non-strict like every other entry: no * `additionalProperties: false`, so additive response fields such as `cost` keep validating. */ export const REPLAY_COMMAND_OUTPUT_SCHEMAS = { replay: objectSchema( { replayed: numberSchema(), healed: numberSchema(), session: stringSchema(), sessionActive: booleanSchema( 'True iff the session is still active — the script had no terminal close.', ), artifactPaths: stringArraySchema(), snapshotDiagnostics: looseObjectSchema(), message: stringSchema(), }, ['replayed', 'healed', 'session', 'sessionActive', 'artifactPaths', 'message'], ), test: objectSchema( { total: numberSchema(), executed: numberSchema(), passed: numberSchema(), failed: numberSchema(), skipped: numberSchema(), notRun: numberSchema(), durationMs: numberSchema(), failures: { type: 'array', items: looseObjectSchema() }, tests: { type: 'array', items: looseObjectSchema() }, snapshotDiagnostics: looseObjectSchema(), }, [ 'total', 'executed', 'passed', 'failed', 'skipped', 'notRun', 'durationMs', 'failures', 'tests', ], ), } satisfies Pick, 'replay' | 'test'>; const replayCliSchema = { usageOverride: 'replay | replay export [--out ]', usageFlags: [], positionalArgs: ['path'], allowsExtraPositionals: true, allowedFlags: [ 'replayMaestro', ...REPLAY_FLAGS, ...METRO_RELOAD_FLAGS, 'replayFrom', 'replayPlanDigest', 'replayKeepSession', 'timeoutMs', 'out', 'saveScript', 'force', 'testIme', ], // ADR 0012 decision 6: on replay, --save-script arms a repair transaction from step 1 (not the // open/close authoring lifecycle the shared flag description documents) and the healed script // commits on that transaction's own teardown, not on a plain close. flagDescriptionOverrides: { saveScript: 'Arm a repair transaction from this replay (ADR 0012): recording starts at step 1, and the healed script commits when the repair-armed session tears down (close, close --save-script, or idle-reap). Independent of the open/close authoring arm-on-open. Optional custom output path.', }, } as const satisfies CommandSchemaOverride; const testCliSchema = { usageOverride: 'test ...', usageFlags: [], listUsageOverride: 'test ...', positionalArgs: ['pathOrGlob'], allowsExtraPositionals: true, allowedFlags: [ 'replayMaestro', ...REPLAY_FLAGS, ...METRO_RELOAD_FLAGS, 'failFast', 'timeoutMs', 'retries', 'recordVideo', 'artifactsDir', 'reporter', 'reportJunit', 'shardAll', 'shardSplit', 'testIme', ], } as const satisfies CommandSchemaOverride; export const replayCliReader: CliReader = (positionals, flags) => ({ ...commonInputFromFlags(flags), path: requiredString(positionals[0], 'replay requires path'), update: flags.replayUpdate, backend: flags.replayMaestro ? 'maestro' : undefined, env: flags.replayEnv, metroHost: flags.metroHost, metroPort: flags.metroPort, bundleUrl: flags.bundleUrl, resumeFrom: flags.replayFrom, resumePlanDigest: flags.replayPlanDigest, keepSession: flags.replayKeepSession, timeoutMs: flags.timeoutMs, saveScript: flags.saveScript, force: flags.force, testIme: flags.testIme, }); export const testCliReader: CliReader = (positionals, flags) => ({ ...commonInputFromFlags(flags), paths: positionals, update: flags.replayUpdate, backend: flags.replayMaestro ? 'maestro' : undefined, env: flags.replayEnv, metroHost: flags.metroHost, metroPort: flags.metroPort, bundleUrl: flags.bundleUrl, failFast: flags.failFast, timeoutMs: flags.timeoutMs, retries: flags.retries, recordVideo: flags.recordVideo, artifactsDir: flags.artifactsDir, shardAll: flags.shardAll, shardSplit: flags.shardSplit, testIme: flags.testIme, }); export const replayDaemonWriter: AsyncDaemonWriter = async (input, host) => { const inputPath = requiredDaemonString(input.path, 'replay requires path'); const replayBackend = readReplayBackend(input); const replayShellEnv = collectReplayClientShellEnv(host.env); return request(REPLAY_COMMAND_NAME, [inputPath], { ...input, replayUpdate: input.update, replayBackend, replayEnv: input.env, replayShellEnv, // #1802: the caller owns the flow files, so it reads them here — the same // client-collects-local-input move `replayShellEnv` already makes — and // the daemon executes only what arrives in this bundle. replayScriptSource: await loadReplayScriptSourceBundle({ inputPath, cwd: readReplayClientCwd(input, host.cwd), replayBackend, env: readReplayScriptSourceEnv(input, replayShellEnv), }), replayFrom: input.resumeFrom, replayPlanDigest: input.resumePlanDigest, replayKeepSession: input.keepSession, saveScript: input.saveScript, }); }; export const testDaemonWriter: AsyncDaemonWriter = async (input, host) => { const inputs = input.paths ?? []; const replayBackend = readReplayBackend(input); const cwd = readReplayClientCwd(input, host.cwd); const replayShellEnv = collectReplayClientShellEnv(host.env); const env = readReplayScriptSourceEnv(input, replayShellEnv); return request(TEST_COMMAND_NAME, inputs, { ...stripReplayTestPresentationInput(input), replayUpdate: input.update, replayBackend, replayEnv: input.env, replayShellEnv, // #1802: `test` inputs are paths, directories, and globs on the CALLER's // filesystem. Expanding them here keeps discovery order identical for a // local and a remote daemon and ships each discovered source's text. replayScriptSources: await Promise.all( discoverReplaySourcePaths({ inputs, cwd, replayBackend }).map( async (inputPath) => await loadReplayScriptSourceBundle({ inputPath, cwd, replayBackend, env }), ), ), }); }; export const replayCommandFacet = defineCommandFacet({ name: REPLAY_COMMAND_NAME, text: { summary: 'Replay a recorded session or Maestro flow', cliDetail: 'Replay has a 60-second work budget inside a 90-second client timeout; --timeout sets a work budget of X and client timeout of X + 30000 ms. The running step receives ordinary request cancellation at the budget. When it settles, failure returns details.reason daemon_request_timeout and details.timeoutMs, preserving the failing script path and line. The daemon and other sessions stay available if it responds; an authored close may already have ended its session. A completed replay returns success even if it settles just after the deadline. Cancellation does not prove native device work stopped. A step that ignores cancellation beyond the 30-second margin may cause a transport timeout; an unresponsive daemon retains the client liveness-based reset. Direct test keeps its own timeout behavior. For Maestro YAML compatibility flows, use replay --maestro and keep the target binding such as --platform ios on the replay command. A script with no terminal close leaves its session (and daemon) running until you close it or it idle-reaps — no different from a session opened interactively. For native .ad scripts, --keep-session suppresses exactly an authored terminal close so you can continue interactively. replay export converts compatible actions to Maestro YAML locally, including app switches with explicit launchApp.appId targets, deep links (including tel: and mailto:) as openLink, and home as pressKey: Home.', }, metadata: replayCommandMetadata, run: (client, input) => client.replay.run(withCommandRuntimeHints(input)), cliSchema: replayCliSchema, cliReader: replayCliReader, daemonWriter: replayDaemonWriter, }); export const testCommandFacet = defineCommandFacet({ name: TEST_COMMAND_NAME, text: { summary: 'Run replay test suites', cliDetail: "Relative globs are expanded on the caller from its working directory, whose name is treated literally. Quote glob inputs to defer expansion to test. Copied diagnostic artifacts receive numbered filenames when needed to preserve other artifacts, replay sources, timing traces, and attempt manifests. JUnit reports (--reporter junit:) replace characters forbidden by XML 1.0 with U+FFFD and preserve legal Unicode and whitespace. JSON and other reporters retain the original suite values. Custom reporter getExitCode hooks must return an integer from 0 to 255 or undefined; the highest valid code wins and cannot lower a failing suite's exit code. A nested test stops after a bounded resource refusal even with --retries; other failures keep their configured retries.", }, metadata: testCommandMetadata, run: (client, input) => client.replay.test(withCommandRuntimeHints(input)), cliSchema: testCliSchema, cliReader: testCliReader, daemonWriter: testDaemonWriter, }); export const replayCommandFamily = defineCommandFamilyFromFacets({ name: 'replay', commands: [replayCommandFacet, testCommandFacet], }); /** * The `${VAR}` values a Maestro `runFlow` include path can be resolved from before the run * starts — the same shell (`AD_VAR_*`) and `-e KEY=VALUE` sources the run itself merges into its * environment, read here so collection sees what the run will see. */ function readReplayScriptSourceEnv( input: CommandInput, replayShellEnv: Record, ): Record { return { ...collectReplayShellEnv(replayShellEnv), ...parseReplayCliEnvEntries(readReplayCliEnvEntries(input.env)), }; } function readReplayClientCwd(input: CommandInput, hostCwd: string): string { return typeof input.cwd === 'string' && input.cwd.length > 0 ? input.cwd : hostCwd; } function readReplayBackend(input: CommandInput): string | undefined { return input.backend ?? (input.maestro === true ? 'maestro' : undefined); } function stripReplayTestPresentationInput(input: CommandInput): CommandInput { const daemonInput = { ...input }; delete daemonInput.reporter; delete daemonInput.reportJunit; return daemonInput; } function collectReplayClientShellEnv(env: NodeJS.ProcessEnv): Record { const result: Record = {}; for (const [key, value] of Object.entries(env)) { if (typeof value === 'string' && key.startsWith(REPLAY_SHELL_ENV_PREFIX)) result[key] = value; } return result; }