Repository navigation
Expand file tree
/
Copy pathruntime.ts
More file actions
415 lines (381 loc) · 13.6 KB
/
Copy pathruntime.ts
File metadata and controls
415 lines (381 loc) · 13.6 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
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';
import { collectFailedStepEvidence, type FailedStepEvidence } from './failed-step-evidence.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>;
/**
* Platform-owned device facts for a failed step (rotation state, whether the app process is
* alive, crash logs), read outside agent-device so they describe the device even when the CLI
* path is what failed. Best-effort: a throw or undefined records nothing.
*/
deviceEvidence?: (context: Context) => Promise<string | undefined>;
/** Bound for `deviceEvidence` as a group. A platform that adds probes raises this with them. */
deviceEvidenceTimeoutMs?: number;
writeCoverageReport: (context: Context) => void;
};
type RunStepOptions = {
allowFailure?: boolean;
commonFlags?: boolean;
expectFailure?: boolean;
/**
* A platform's typed classifier for a failed step whose result says the DEVICE prevented the
* observation rather than the product answering wrongly (a wait whose own `details.reason` is
* an observation-prevented verdict). When it answers true, the step is re-issued and only the
* last attempt is asserted, so one runner restart or bridge rebuild costs a repeat of the wait,
* not the job. A step that already owns a miss policy (`allowFailure` / `expectFailure`) never
* gets this layer under it, and a miss the classifier refuses fails exactly as before.
*/
reattemptInfrastructureMiss?: (result: CliJsonResult) => boolean;
timeoutMs?: number;
};
/** Issues one step gets when its own miss says infrastructure prevented the observation. */
const INFRASTRUCTURE_MISS_ISSUES = 2;
/**
* The re-issue policy a step runs under. A step that already owns a miss policy is issued once:
* its caller reads the failed result or expects failure, and a silent second issue would rewrite
* what that policy observed.
*/
function reattemptPolicyFor(
stepOptions: RunStepOptions,
): ((result: CliJsonResult) => boolean) | undefined {
return stepOptions.allowFailure === true || stepOptions.expectFailure === true
? undefined
: stepOptions.reattemptInfrastructureMiss;
}
/** Whether this failed issue of the step is one the platform policy re-issues instead of asserting. */
function willReissueMiss(
result: CliJsonResult,
reattempt: ((result: CliJsonResult) => boolean) | undefined,
issue: number,
): boolean {
return (
result.status !== 0 &&
reattempt !== undefined &&
issue < INFRASTRUCTURE_MISS_ISSUES &&
reattempt(result)
);
}
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>) {
const reportedFailures = new WeakSet<Error>();
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);
} catch (error) {
await recordScenarioFailure(context, error);
throw error;
} finally {
context.timings.push({ durationMs: Date.now() - startedAt, id: scenario.id });
options.writeCoverageReport(context);
}
}
async function recordScenarioFailure(context: Context, error: unknown): Promise<void> {
if (error instanceof Error && reportedFailures.has(error)) return;
try {
const evidence = await captureFailedStepEvidence(context);
writeFailureReport(
context,
error instanceof Error ? (error.stack ?? error.message) : String(error),
evidence,
);
} catch {
// Artifact I/O is best-effort and must not replace the scenario failure.
}
}
function writeFailureReport(
context: Context,
description: string,
evidence: FailedStepEvidence,
): string {
const message = [
description,
`scenario: ${context.currentScenario}`,
`artifacts: ${context.artifactDir}`,
`screenshot: ${evidence.screenshotPath ?? '(capture failed)'}`,
`snapshot: ${evidence.snapshotPath ?? '(capture failed)'}`,
`device: ${evidence.devicePath ?? '(not collected)'}`,
].join('\n');
fs.writeFileSync(path.join(context.artifactDir, 'failed-step.txt'), message);
return message;
}
async function runStep(
context: Context,
step: string,
args: string[],
stepOptions: RunStepOptions = {},
): Promise<CliJsonResult> {
const reattempt = reattemptPolicyFor(stepOptions);
for (let issue = 1; ; issue += 1) {
const issuedStep = issue === 1 ? step : `${step} (re-issue after observation-prevented miss)`;
const { result, fullArgs } = await issueStep(context, issuedStep, args, stepOptions);
// A miss the policy will re-issue keeps its step record but writes no failure evidence and
// keeps its error to itself: the evidence and the verdict belong to the final issue, which
// is the only outcome this step is judged on.
if (willReissueMiss(result, reattempt, issue)) continue;
await assertStepOutcome(
context,
issuedStep,
fullArgs,
result,
stepOptions.expectFailure === true && result.status !== 0,
stepOptions,
);
return result;
}
}
async function issueStep(
context: Context,
step: string,
args: string[],
stepOptions: RunStepOptions,
): Promise<{ result: CliJsonResult; fullArgs: string[] }> {
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,
});
updateSessionState(context, args[0], result.status);
return { result, fullArgs };
}
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 = writeFailureReport(
context,
formatResultDebug(step, fullArgs, result),
evidence,
);
const failure = new assert.AssertionError({ message });
reportedFailures.add(failure);
throw failure;
}
if (stepOptions.expectFailure === true && result.status === 0) {
assert.fail(`${step} unexpectedly succeeded\ncommand: agent-device ${fullArgs.join(' ')}`);
}
}
function captureFailedStepEvidence(context: Context): Promise<FailedStepEvidence> {
const runCli = options.runCli ?? runBuiltCliJson;
const deviceEvidence = options.deviceEvidence;
return collectFailedStepEvidence({
stem: path.join(context.artifactDir, `failed-step-${context.stepHistory.length}`),
runCli: (args) => runCli(options.commonFlags(context, args), context.env),
...(deviceEvidence ? { deviceEvidence: () => deviceEvidence(context) } : {}),
...(options.deviceEvidenceTimeoutMs === undefined
? {}
: { deviceEvidenceTimeoutMs: options.deviceEvidenceTimeoutMs }),
});
}
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;
}