-
-
Notifications
You must be signed in to change notification settings - Fork 277
Expand file tree
/
Copy pathruntime.ts
More file actions
327 lines (300 loc) · 10.1 KB
/
Copy pathruntime.ts
File metadata and controls
327 lines (300 loc) · 10.1 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
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { type CliJsonResult, formatResultDebug, runBuiltCliJson } from '../cli-json.ts';
export type StepRecord = {
accepted: boolean;
command: string;
commandName?: string;
durationMs: number;
errorCode?: string;
errorMessage?: string;
scenario: string;
status: number;
step: string;
};
export type ScenarioTiming = {
durationMs: number;
id: string;
};
export type LiveDeviceContext<BehaviorId extends string> = {
artifactDir: string;
behaviorEvidence: Partial<Record<BehaviorId, string[]>>;
commandEvidence: Record<string, string[]>;
completedScenarios: string[];
currentScenario: string;
env: NodeJS.ProcessEnv;
session: string;
sessionOpen: boolean;
startedAtMs: number;
stepHistory: StepRecord[];
timings: ScenarioTiming[];
};
export type LiveScenario<Context> = {
id: string;
run: (context: Context) => Promise<void>;
};
type HarnessOptions<Context, BehaviorId extends string> = {
behaviorsForScenario: (scenarioId: string) => readonly BehaviorId[];
commandsForScenario: (scenarioId: string) => readonly string[];
commonFlags: (context: Context, args: readonly string[]) => string[];
runCli?: (
args: string[],
env: NodeJS.ProcessEnv,
options?: { timeoutMs?: number },
) => Promise<CliJsonResult>;
writeCoverageReport: (context: Context) => void;
};
type RunStepOptions = {
allowFailure?: boolean;
commonFlags?: boolean;
expectFailure?: boolean;
timeoutMs?: number;
};
export function createLiveDeviceContext<BehaviorId extends string>(options: {
artifactRoot: string;
session: string;
}): LiveDeviceContext<BehaviorId> {
const runId = `${Date.now()}-${process.pid}`;
const artifactDir = path.resolve(options.artifactRoot, runId);
fs.mkdirSync(artifactDir, { recursive: true });
return {
artifactDir,
behaviorEvidence: {},
commandEvidence: {},
completedScenarios: [],
currentScenario: 'bootstrap',
env: process.env,
session: options.session,
sessionOpen: false,
startedAtMs: Date.now(),
stepHistory: [],
timings: [],
};
}
export function createLiveDeviceHarness<
Context extends LiveDeviceContext<BehaviorId>,
BehaviorId extends string,
>(options: HarnessOptions<Context, BehaviorId>) {
async function runScenario(context: Context, scenario: LiveScenario<Context>): Promise<void> {
context.currentScenario = scenario.id;
const commandCounts = evidenceCounts(
options.commandsForScenario(scenario.id),
context.commandEvidence,
);
const behaviorCounts = evidenceCounts(
options.behaviorsForScenario(scenario.id),
context.behaviorEvidence,
);
const startedAt = Date.now();
try {
await scenario.run(context);
assertNewEvidence(
scenario.id,
options.commandsForScenario(scenario.id),
context.commandEvidence,
commandCounts,
);
assertNewEvidence(
scenario.id,
options.behaviorsForScenario(scenario.id),
context.behaviorEvidence,
behaviorCounts,
);
context.completedScenarios.push(scenario.id);
} finally {
context.timings.push({ durationMs: Date.now() - startedAt, id: scenario.id });
options.writeCoverageReport(context);
}
}
async function runStep(
context: Context,
step: string,
args: string[],
stepOptions: RunStepOptions = {},
): Promise<CliJsonResult> {
const fullArgs = buildStepArgs(context, args, stepOptions);
const startedAt = Date.now();
const result = await (options.runCli ?? runBuiltCliJson)(fullArgs, context.env, {
timeoutMs: stepOptions.timeoutMs,
});
const failedAsExpected = stepOptions.expectFailure === true && result.status !== 0;
recordStep(context, {
accepted: result.status === 0 || failedAsExpected,
command: `agent-device ${fullArgs.join(' ')}`,
commandName: args[0],
durationMs: Date.now() - startedAt,
errorCode: stringValue(result.json?.error?.code),
errorMessage: stringValue(result.json?.error?.message),
scenario: context.currentScenario,
status: result.status,
step,
});
await assertStepOutcome(context, step, fullArgs, result, failedAsExpected, stepOptions);
updateSessionState(context, args[0], result.status);
return result;
}
function buildStepArgs(
context: Context,
args: readonly string[],
stepOptions: RunStepOptions,
): string[] {
return stepOptions.commonFlags === false ? withJson(args) : options.commonFlags(context, args);
}
function recordStep(context: Context, record: StepRecord): void {
context.stepHistory.push(record);
writeStepHistory(context);
}
async function assertStepOutcome(
context: Context,
step: string,
fullArgs: string[],
result: CliJsonResult,
failedAsExpected: boolean,
stepOptions: RunStepOptions,
): Promise<void> {
const unexpectedFailure =
result.status !== 0 && !failedAsExpected && stepOptions.allowFailure !== true;
if (unexpectedFailure) {
const evidence = await captureFailedStepEvidence(context);
const message = [
formatResultDebug(step, fullArgs, result),
`scenario: ${context.currentScenario}`,
`artifacts: ${context.artifactDir}`,
`screenshot: ${evidence.screenshotPath ?? '(capture failed)'}`,
`snapshot: ${evidence.snapshotPath ?? '(capture failed)'}`,
].join('\n');
fs.writeFileSync(path.join(context.artifactDir, 'failed-step.txt'), message);
assert.fail(message);
}
if (stepOptions.expectFailure === true && result.status === 0) {
assert.fail(`${step} unexpectedly succeeded\ncommand: agent-device ${fullArgs.join(' ')}`);
}
}
/**
* What the device showed when a step failed: the pixels and the accessibility tree the
* next capture would have read. Best-effort, never throws; a failed capture yields undefined.
*/
async function captureFailedStepEvidence(
context: Context,
): Promise<{ screenshotPath?: string; snapshotPath?: string }> {
const stem = path.join(context.artifactDir, `failed-step-${context.stepHistory.length}`);
const screenshotPath = `${stem}.png`;
const snapshotPath = `${stem}-snapshot.json`;
const runCli = options.runCli ?? runBuiltCliJson;
const evidence: { screenshotPath?: string; snapshotPath?: string } = {};
try {
const screenshot = await runCli(
options.commonFlags(context, ['screenshot', screenshotPath]),
context.env,
);
if (screenshot.status === 0) evidence.screenshotPath = screenshotPath;
} catch {
// evidence only
}
try {
const snapshot = await runCli(options.commonFlags(context, ['snapshot']), context.env);
if (snapshot.status === 0 && snapshot.json !== undefined) {
fs.writeFileSync(snapshotPath, JSON.stringify(snapshot.json, null, 2));
evidence.snapshotPath = snapshotPath;
}
} catch {
// evidence only
}
return evidence;
}
function updateSessionState(context: Context, command: string | undefined, status: number): void {
if (status !== 0) return;
if (command === 'open') context.sessionOpen = true;
if (command === 'close') context.sessionOpen = false;
}
function verifyCommand(context: Context, command: string, evidence: string): void {
recordCommandEvidence(context, command, command, evidence);
}
function verifyNestedCommand(
context: Context,
command: string,
executedCommand: string,
evidence: string,
): void {
recordCommandEvidence(context, command, executedCommand, evidence);
}
function recordCommandEvidence(
context: Context,
command: string,
executedCommand: string,
evidence: string,
): void {
assert.ok(
context.stepHistory.some(
(record) =>
record.scenario === context.currentScenario &&
record.commandName === executedCommand &&
record.accepted,
),
`${context.currentScenario} credited ${command} without a successful ${executedCommand} execution`,
);
context.commandEvidence[command] = [...(context.commandEvidence[command] ?? []), evidence];
}
function verifyBehavior(context: Context, behavior: BehaviorId, evidence: string): void {
context.behaviorEvidence[behavior] = [...(context.behaviorEvidence[behavior] ?? []), evidence];
}
async function sessionExists(context: Context): Promise<boolean> {
const inventory = await runStep(
context,
'inspect final session ownership',
['session', 'list'],
{
commonFlags: false,
},
);
const sessions = Array.isArray(inventory.json?.data?.sessions)
? inventory.json.data.sessions
: [];
return sessions.some((session: { name?: unknown }) => session.name === context.session);
}
return {
runScenario,
runStep,
sessionExists,
verifyBehavior,
verifyCommand,
verifyNestedCommand,
};
}
export function requiredEnv(name: string, enabledFlag: string): string {
const value = process.env[name]?.trim();
assert.ok(value, `${name} is required when ${enabledFlag}=1`);
return value;
}
function evidenceCounts<Key extends string>(
keys: readonly Key[],
evidence: Partial<Record<Key, string[]>>,
): ReadonlyMap<Key, number> {
return new Map(keys.map((key) => [key, evidence[key]?.length ?? 0]));
}
function assertNewEvidence<Key extends string>(
scenarioId: string,
keys: readonly Key[],
evidence: Partial<Record<Key, string[]>>,
counts: ReadonlyMap<Key, number>,
): void {
for (const key of keys) {
assert.ok(
(evidence[key]?.length ?? 0) > (counts.get(key) ?? 0),
`${scenarioId} produced no specific evidence for ${key}`,
);
}
}
function withJson(args: readonly string[]): string[] {
return args.includes('--json') ? [...args] : [...args, '--json'];
}
function writeStepHistory<BehaviorId extends string>(context: LiveDeviceContext<BehaviorId>): void {
fs.writeFileSync(
path.join(context.artifactDir, 'step-history.json'),
JSON.stringify(context.stepHistory, null, 2),
);
}
function stringValue(value: unknown): string | undefined {
return typeof value === 'string' ? value : undefined;
}