Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
370 lines (350 loc) · 15.2 KB
/
Copy pathindex.ts
File metadata and controls
370 lines (350 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
import type { CommandSchemaOverride } from '@agent-device/command-registry/command-schema';
import type { CommandResultMap } from '@agent-device/command-registry/command-result';
import { messageOutput } from '../output-common.ts';
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<boolean | string>({
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 `src/mcp/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<Record<keyof CommandResultMap, JsonSchema>, 'replay' | 'test'>;
const replayCliSchema = {
usageOverride: 'replay <path> | replay export <file.ad> [--out <path>]',
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 <path-or-glob>...',
usageFlags: [],
listUsageOverride: 'test <path-or-glob>...',
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 <ms> 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 <flow.yaml> --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 <file.ad> 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,
// Replay owns a composable warnings channel (`optional` step skips, capture degradations);
// a run that reports success while warnings say otherwise must not render as a bare
// success line (#2560).
cliOutputFormatter: messageOutput,
});
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:<path>) 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.",
},
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<string, string>,
): Record<string, string> {
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<string, string> {
const result: Record<string, string> = {};
for (const [key, value] of Object.entries(env)) {
if (typeof value === 'string' && key.startsWith(REPLAY_SHELL_ENV_PREFIX)) result[key] = value;
}
return result;
}