Repository navigation
Expand file tree
/
Copy pathfalcon.js
More file actions
932 lines (864 loc) · 42 KB
/
Copy pathfalcon.js
File metadata and controls
932 lines (864 loc) · 42 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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
/**
* falcon.js — Falcon-Automation main entry point.
*
* Phase 10 — whole-app coverage:
* - A run now covers the whole application, not just its entry page.
* SiteSweep discovers the frontier with ClickExplorer and then, for
* every page it keeps, runs DOMIssueScanner + TestGenerator + TestRunner
* on that page. Until Phase 10 this file threw the crawler's results
* away: it logged the page count, re-navigated to the root URL and
* generated scenarios for that one page. The header comment below
* claimed per-page generation for seven phases while the code did no
* such thing — that claim is now true rather than aspirational.
* - Pages Falcon deliberately did not test (over --max-pages, past the
* budget, cross-origin, unreachable) are reported with a reason instead
* of vanishing. "What we didn't cover" is half of a coverage claim.
* - New flags: --max-pages=N, --budget-ms=N, --no-dedupe,
* --allow-cross-origin, and --single-page, which restores the
* pre-Phase-10 one-page pipeline verbatim for anyone depending on it.
*
* Phase 12 — repeat execution and an honest "unavailable" outcome:
* - --repeat=N re-executes each page's generated test plan N times (each
* page's plan is still generated only once) so an intermittent target
* gets multiple samples in a single run. N must be a positive integer no
* greater than 50 (comfortably above the 3 samples FlakinessTracker
* needs for a same-run verdict, capped well short of inflating a single
* run's cost or CI minutes unboundedly); omitted, it defaults to 1
* (today's behaviour, byte-identical apart from a `repetition: 1` field
* on result rows). Unlike --max-pages/--budget-ms, an invalid --repeat
* (non-numeric, non-integer, <= 0, > 50, or a conflicting duplicate) is
* a hard failure: Logger.error names the bad value and the process exits
* non-zero before the dashboard starts or the browser launches.
* - A target the AI-healing chain could not resolve at all is reported as
* its own "unavailable" status, distinct from "skipped" (an action
* nobody implements, never attempted) and from an ordinary "failed"
* (resolved but the interaction itself broke).
*
* Phase 3 additions (retained):
* - Real-time live dashboard (http://localhost:3000) — express + socket.io
* were already installed; now wired into every execution pipeline.
* - Dashboard events emitted for every test lifecycle moment so the live
* UI reflects the run in real time without polling.
* - --no-dashboard flag disables the server for headless CI environments
* that don't need a browser window.
*
* Phase 1/2 fixes (retained):
* const → let for uiIssues, TestRunner arity, executeExploratoryTest args,
* headless env var respected, --url= optional (defaults to saucedemo).
*/
require("dotenv").config({ quiet: true });
const { chromium } = require("playwright");
const DOMIssueScanner = require("./src/core/DOMIssueScanner");
const ClickExplorer = require("./src/core/ClickExplorer");
const TestRunner = require("./src/core/TestRunner");
const TestGenerator = require("./src/core/TestGenerator");
const SiteSweep = require("./src/core/SiteSweep");
const Dashboard = require("./src/core/Dashboard");
const Logger = require("./utils/Logger");
const ReportManager = require("./src/core/ReportManager");
const HealingReport = require("./src/core/AIHealer/HealingReport");
const PlanFile = require("./src/core/PlanFile");
const { parseParallelArgs } = require("./src/core/parallel/Args");
const ParallelRunner = require("./src/core/parallel/Runner");
const InvocationContext = require("./src/core/llm/InvocationContext");
const { isKeyShapedValue } = require("./src/core/llm/transport/guardedFetch");
const ContractCli = require("./src/core/outcome/ContractCli");
const ExecutionBinding = require("./src/core/outcome/ExecutionBinding");
const JourneyCoordinator = require("./src/core/outcome/JourneyCoordinator");
const DEFAULT_URL = "https://www.saucedemo.com";
/**
* Phase 15 — run history. Ledger options for this process.
*
* Normal runs use the ledger's own default path. FALCON_TEST_RUN_HISTORY_PATH is
* honoured only when a test preload has set globalThis.__FALCON_TEST_SEAMS__, so
* the variable does nothing otherwise. Tests that spawn falcon.js keep the repo's
* data/run_history.json untouched by running with FALCON_RUN_HISTORY=off.
*/
const historyLedgerOptions = () => {
const seam = globalThis.__FALCON_TEST_SEAMS__;
const override = process.env.FALCON_TEST_RUN_HISTORY_PATH;
if (seam && seam.runHistory === true && typeof override === "string" && override) {
return { filePath: override };
}
return {};
};
/**
* Append this run to the ledger and log trend flags. Never throws, never
* touches process.exitCode (SEC-11, SEC-12): history is advisory.
*/
const recordRun = async ({ incomplete, report, coverage, repeat, startedAt }) => {
try {
const { RunLedger } = require("./src/core/history/RunLedger");
if (!RunLedger.isEnabled(process.env)) return;
const ledgerOptions = historyLedgerOptions();
const { buildRunRecord } = require("./src/core/history/RunRecord");
const { getGitInfo } = require("./src/core/history/GitInfo");
const { evaluate, parseTrendSettings } = require("./src/core/history/TrendDetector");
let pendingDepth = 0;
let quarantineCount = 0;
try { pendingDepth = require("./src/core/AIHealer/HealingTrust").list().length; } catch { /* snapshot unavailable */ }
try {
quarantineCount = require("./src/core/FlakinessTracker").list().filter((e) => e && e.quarantined).length;
} catch { /* snapshot unavailable */ }
const record = buildRunRecord({
report,
coverage: incomplete ? null : coverage,
healLog: HealingReport._instance.logs,
pendingDepth,
quarantineCount,
repeat,
durationMs: Date.now() - startedAt,
incomplete,
git: getGitInfo(),
});
const ledger = new RunLedger(ledgerOptions);
const appended = await ledger.append(record);
if (!appended.ok) return;
let settings;
try {
settings = parseTrendSettings(process.env);
} catch (error) {
Logger.warning(`⚠️ ${error.setting || "FALCON_TREND_*"} is invalid — using the default trend settings.`);
settings = {};
}
const { flags } = evaluate(ledger.load().runs, record, settings);
if (flags.length > 0) {
Logger.info(`history: ${flags.length} flag(s): ${flags.map((f) => f.signal).join(", ")}`);
}
} catch (error) {
try { Logger.warning(`⚠️ Run history was not recorded (${error && error.code ? error.code : "error"}).`); } catch { /* never fail the run */ }
}
};
/**
* Read a `--flag=<number>` argument.
*
* A typo'd or negative bound is treated as "not supplied" rather than as an
* instruction: `--max-pages=abc` silently becoming NaN would disable the cap
* altogether, which is the opposite of what someone passing a cap wants.
*/
const numericArg = (args, name, fallback) => {
const prefix = `--${name}=`;
const raw = args.find((a) => a.startsWith(prefix));
if (!raw) return fallback;
const value = Number(raw.slice(prefix.length));
if (!Number.isFinite(value) || value <= 0) {
Logger.warning(`⚠️ Ignoring ${raw} — expected a positive number; using ${fallback}.`);
return fallback;
}
return value;
};
/** Hard upper bound for --repeat=N — see the Phase 12 header comment above. */
const MAX_REPEAT = 50;
/**
* Read `--repeat=<N>`, the one flag Falcon must fail hard on rather than
* fall back for (AC-02): --max-pages/--budget-ms above treat a bad value as
* "not supplied" because silently disabling a bound is safe, but silently
* defaulting an invalid repeat count would let a broken invocation run
* anyway and report a green(ish) result nobody actually asked for.
*
* Absent --repeat ⇒ 1 (no-op, today's behaviour). Present but invalid
* (non-numeric, non-integer, <= 0, > MAX_REPEAT) or a duplicate/conflicting
* --repeat= occurrence ⇒ Logger.error naming the offending value, followed
* by process.exit(1) — the caller in the IIFE below does this before the
* dashboard starts or the browser launches, so a bad flag never produces a
* partial run.
*
* @param {string[]} args
* @returns {number|null} the validated count, or null if invalid (the
* caller has already logged why and must exit non-zero)
*/
const requireRepeatCount = (args) => {
const prefix = "--repeat=";
const occurrences = args.filter((a) => a.startsWith(prefix));
if (occurrences.length === 0) return 1;
const rawValues = [...new Set(occurrences.map((a) => a.slice(prefix.length)))];
if (rawValues.length > 1) {
Logger.error(
`❌ Conflicting --repeat values supplied (${rawValues.join(", ")}) — pass --repeat once.`
);
return null;
}
const raw = rawValues[0];
if (raw.trim() === "") {
Logger.error("❌ --repeat requires a value, e.g. --repeat=3.");
return null;
}
const value = Number(raw);
if (!Number.isFinite(value) || !Number.isInteger(value) || value <= 0 || value > MAX_REPEAT) {
Logger.error(
`❌ Invalid --repeat=${raw} — expected an integer between 1 and ${MAX_REPEAT}.`
);
return null;
}
return value;
};
/**
* Flags that could carry a credential VALUE. A key must never reach this
* process via argv (it would land in shell history, `ps`, and process
* listings) — any of these, with or without a value, is a hard failure
* named only by the flag, never by whatever value followed it.
*/
const KEY_CARRIER_FLAGS = ["--llm-api-key", "--api-key", "--llm-key", "--key", "--token"];
/**
* Reject any argv entry that is, or assigns a value to, a key-carrier flag.
* Checked before anything else touches argv so a credential-shaped
* invocation never reaches logging, parsing, or provider resolution.
*
* @param {string[]} args
* @returns {boolean} true iff no key-carrier flag was found
*/
const rejectKeyCarrierFlags = (args) => {
for (const flag of KEY_CARRIER_FLAGS) {
const prefix = `${flag}=`;
if (args.includes(flag) || args.some((a) => a.startsWith(prefix))) {
Logger.error(`❌ ${flag} is not accepted — a credential must never be passed on the command line.`);
return false;
}
}
return true;
};
/**
* Strictly read a `--<flag>=<value>` BYOK flag (--llm-profile, --llm-provider,
* --llm-model). Unlike --max-pages/--budget-ms, a bad occurrence here is a
* hard failure (mirrors AC-02's --repeat convention): an empty value, a
* duplicate/conflicting occurrence, or a credential-shaped value all exit
* non-zero before any browser/page work, naming only the flag — never the
* value, which could itself be a leaked credential.
*
* @param {string[]} args
* @param {string} flag - flag name without the leading `--` (e.g. "llm-model")
* @returns {{ok:true, value:(string|undefined)}|{ok:false}}
*/
const readStrictValueFlag = (args, flag) => {
const prefix = `--${flag}=`;
const occurrences = args.filter((a) => a.startsWith(prefix));
if (occurrences.length === 0) return { ok: true, value: undefined };
const rawValues = [...new Set(occurrences.map((a) => a.slice(prefix.length)))];
if (rawValues.length > 1) {
Logger.error(`❌ Conflicting --${flag} values supplied — pass --${flag} once.`);
return { ok: false };
}
if (occurrences.length > 1) {
Logger.error(`❌ --${flag} supplied more than once — pass it once.`);
return { ok: false };
}
const raw = rawValues[0];
if (raw.trim() === "") {
Logger.error(`❌ --${flag} requires a value, e.g. --${flag}=<value>.`);
return { ok: false };
}
if (isKeyShapedValue(raw)) {
Logger.error(`❌ --${flag} was given a credential-shaped value — a key must never be passed on the command line.`);
return { ok: false };
}
return { ok: true, value: raw };
};
/** Count a page's scenario outcomes, "deduped" included. */
const tally = (results) => results.reduce((counts, r) => {
counts[r.status] = (counts[r.status] || 0) + 1;
return counts;
}, {});
/**
* Per-page row for the report.
*
* The scenario objects themselves already appear once in the report's flat
* `tests` array; repeating them under every page would roughly double the
* size of every report to say nothing new, so a page carries its tally and
* its counts instead.
*/
const pageBreakdown = (p) => ({
url: p.url,
status: p.status,
...(p.reason ? { reason: p.reason } : {}),
scenariosGenerated: p.scenariosGenerated || 0,
scenariosDeduplicated: p.scenariosDeduplicated || 0,
durationMs: p.durationMs || 0,
uiIssues: p.uiIssues.length,
summary: tally(p.results),
});
/** Coverage totals derived from a page list, for callers that don't build their own. */
const deriveCoverage = (pages) => ({
pagesDiscovered: pages.length,
pagesTested: pages.filter((p) => p.status === "tested").length,
pagesSkipped: pages.filter((p) => p.status === "skipped").length,
pagesUnreachable: pages.filter((p) => p.status === "unreachable").length,
scenariosGenerated: pages.reduce((n, p) => n + (p.scenariosGenerated || 0), 0),
scenariosDeduplicated: pages.reduce((n, p) => n + (p.scenariosDeduplicated || 0), 0),
budgetExhausted: false,
});
/**
* Coerce whatever SiteSweep returned into the documented SweepResult shape.
*
* Everything downstream — the tally, the exit code, the coverage line —
* indexes into this structure, and a missing array here would turn a
* reporting gap into a crash that loses the whole run's results. This file
* has guarded ClickExplorer's return value the same way since Phase 2.
*/
const normalizeSweep = (result, entryUrl) => {
const raw = result && typeof result === "object" ? result : {};
if (!Array.isArray(raw.pages)) {
Logger.warning("⚠️ SiteSweep returned no page list — reporting the run as covering nothing.");
}
const pages = (Array.isArray(raw.pages) ? raw.pages : [])
.filter((p) => p && typeof p === "object")
.map((p) => ({
...p,
results: Array.isArray(p.results) ? p.results : [],
uiIssues: Array.isArray(p.uiIssues) ? p.uiIssues : [],
}));
return {
entryUrl: raw.entryUrl || entryUrl,
pages,
coverage: raw.coverage && typeof raw.coverage === "object"
? raw.coverage
: deriveCoverage(pages),
};
};
/** Phase 10 default: sweep the whole application from the entry URL. */
const runWholeApp = async (context, entryUrl, emit, opts) => {
Logger.info(
`🧭 Sweeping ${entryUrl} — up to ${opts.maxPages} page(s), ` +
`${(opts.budgetMs / 1000).toFixed(0)} s budget, dedupe ${opts.dedupe ? "on" : "off"}, ` +
`${opts.sameOriginOnly ? "same-origin only" : "cross-origin allowed"}, ` +
`repeat=${opts.repeat ?? 1}…`
);
// pageStart/pageComplete stream straight through to the dashboard's
// coverage panel; per-scenario events are emitted by the caller once the
// sweep's results have been flattened.
const sweep = new SiteSweep(context, { ...opts, onEvent: emit });
const result = normalizeSweep(await sweep.run(entryUrl), entryUrl);
for (const p of result.pages) emit("explorerPage", { url: p.url });
return result;
};
/**
* --single-page: the pre-Phase-10 pipeline, unchanged.
*
* Kept verbatim — same steps, same order, same log lines, same discarded
* crawl — because the flag exists precisely for anyone whose scripts or
* expectations are pinned to that behaviour. Its one page is returned in
* SweepResult shape so the reporting path below stays common to both modes.
*/
const runEntryPageOnly = async (context, url, emit, repeatCount = 1, providerContext = null, savePlanPath = null) => {
Logger.warning("⚠️ --single-page: only the entry page will be tested (pre-Phase-10 behaviour).");
const startedAt = Date.now();
const page = await context.newPage();
await page.goto(url, { waitUntil: "load" });
Logger.info(`✅ Loaded: ${url}`);
emit("explorerPage", { url });
// ── Step 1: Detect UI Issues ─────────────────────────────────────────────
Logger.info("🔍 Step 1: Detecting UI issues with DOMIssueScanner…");
const domIssueScanner = new DOMIssueScanner(page);
let uiIssues = await domIssueScanner.detectUIIssues();
if (!Array.isArray(uiIssues)) {
Logger.warning("⚠️ detectUIIssues() did not return an array — defaulting to []");
uiIssues = [];
}
Logger.info(` → ${uiIssues.length} issue(s) found`);
// ── Step 2: Explore Click Paths ──────────────────────────────────────────
Logger.info("🔍 Step 2: Mapping site with ClickExplorer…");
const clickExplorer = new ClickExplorer(page);
await clickExplorer.explore();
let visitedPages = clickExplorer.visitedPages;
if (!(visitedPages instanceof Set)) {
Logger.warning("⚠️ visitedPages is not a Set — defaulting to empty Set");
visitedPages = new Set();
}
Array.from(visitedPages).forEach((u) => emit("explorerPage", { url: u }));
Logger.info(` → ${visitedPages.size} page(s) explored`);
// ── Step 3: DOM-Driven Test Generation ───────────────────────────────────
Logger.info("🔍 Step 3: Generating test scenarios from DOM analysis…");
// Re-navigate to the root to generate scenarios from the main page
await page.goto(url, { waitUntil: "domcontentloaded" }).catch(() => {});
const generator = new TestGenerator(page);
const testPlan = await generator.generateTestScenarios();
Logger.info(` → ${testPlan.test_scenarios.length} scenario(s) generated for ${testPlan.url}`);
if (savePlanPath) {
await PlanFile.save(savePlanPath, testPlan);
Logger.info(`💾 Test plan saved (${testPlan.test_scenarios.length} scenario(s)) — replay it with --plan.`);
}
// ── Step 4: Execute Generated Test Plan ──────────────────────────────────
Logger.info(`▶ Step 4: Executing generated test scenarios (repeat=${repeatCount})…`);
const results = await TestRunner.runRepeatedTestPlan(page, testPlan, repeatCount, { providerContext });
const only = {
url,
status: "tested",
scenariosGenerated: testPlan.test_scenarios.length,
scenariosDeduplicated: 0,
results,
uiIssues,
durationMs: Date.now() - startedAt,
};
// The crawl's own page list is reported as discovered-but-skipped rather
// than dropped: --single-page is a deliberate narrowing, and the report
// should say what that narrowing cost.
// Compared normalized: the crawl records whatever URL the browser settled
// on, so a `--url=https://x.com` entry comes back as `https://x.com/` and a
// raw !== comparison would list the entry page as skipped alongside the
// tested copy of itself.
const entryKey = SiteSweep.normalizeUrl(url) ?? url;
const skipped = Array.from(visitedPages)
.filter((u) => (SiteSweep.normalizeUrl(u) ?? u) !== entryKey)
.map((u) => ({
url: u,
status: "skipped",
reason: "single-page",
scenariosGenerated: 0,
scenariosDeduplicated: 0,
results: [],
uiIssues: [],
durationMs: 0,
}));
const pages = [only, ...skipped];
return { entryUrl: url, pages, coverage: deriveCoverage(pages) };
};
/**
* WP-77R: fixture identities for `accessEquals` assertions. Loaded only when
* the bound contract actually needs one; any failure (missing file, bad JSON,
* unsafe path) yields {} so the assertion fails closed as
* `unavailable`/`identity_unknown` rather than silently substituting a
* credential. Always returns a fresh deep copy so concurrent journeys never
* share a mutable identity object. Never logged.
*/
const loadIdentitiesFor = async (binding) => {
const needs = Boolean(
binding && binding.ok
&& binding.contract.assertions.some((a) => a.check === "accessEquals")
);
if (!needs) return {};
try {
const LocalSource = require("./src/core/outcome/LocalSource");
const read = await LocalSource.readFileJson("fixtures/identities.json", __dirname);
if (read.ok && read.body && typeof read.body === "object") return structuredClone(read.body);
} catch {
return {};
}
return {};
};
/** Every `--plan=<value>` occurrence, in order (the legacy reader rejects repeats). */
const collectPlanValues = (args) => {
const values = [];
for (const a of args.filter((x) => x.startsWith("--plan="))) {
const v = a.slice("--plan=".length);
if (v.trim() === "") {
Logger.error("❌ --plan requires a value, e.g. --plan=<file>.");
return { ok: false };
}
if (isKeyShapedValue(v)) {
Logger.error("❌ --plan was given a credential-shaped value — a key must never be passed on the command line.");
return { ok: false };
}
values.push(v);
}
return { ok: true, values };
};
/**
* --plan=<file>: replay a saved plan through the same TestRunner → AIHealer
* path every other mode uses. No discovery, no crawl: the plan is the test.
*/
const runSavedPlan = async (context, plan, emit, repeatCount = 1, providerContext = null, contractBinding = null, identities = {}) => {
const startedAt = Date.now();
const page = await context.newPage();
await page.goto(plan.url, { waitUntil: "load" });
Logger.info(`✅ Loaded: ${plan.url}`);
emit("explorerPage", { url: plan.url });
Logger.info(`▶ Running saved plan: ${plan.test_scenarios.length} step(s), repeat=${repeatCount}…`);
const results = await TestRunner.runRepeatedTestPlan(page, plan, repeatCount, { providerContext, contractBinding, baseDir: __dirname, identities });
const only = {
url: plan.url,
status: "tested",
scenariosGenerated: plan.test_scenarios.length,
scenariosDeduplicated: 0,
results,
uiIssues: [],
durationMs: Date.now() - startedAt,
};
return { entryUrl: plan.url, pages: [only], coverage: deriveCoverage([only]) };
};
(async () => {
const args = process.argv.slice(2);
// A key must never come from argv (AC: key-carrier flags). Checked first,
// before any other parsing or logging touches these args.
if (!rejectKeyCarrierFlags(args)) {
await Logger.flush();
process.exit(1);
}
const contractCli = await ContractCli.run(args, {
repoRoot: __dirname,
stdin: process.stdin,
stdout: process.stdout,
isTTY: Boolean(process.stdin.isTTY && process.stdout.isTTY),
});
if (contractCli.handled) {
await Logger.flush();
process.exit(contractCli.code);
}
// Saved plans: a rejected plan is input the user must fix (exit 2), checked
// before the dashboard or the browser exist.
// WP-77I-S2: approved-contract multi-journey mode = more than one --plan,
// or --plan with --workers N>1 (never with --shard: that stays refused).
const planValues = collectPlanValues(args);
const earlyParallel = parseParallelArgs(args);
if (!planValues.ok) {
await Logger.flush();
process.exit(1);
}
const multiJourney = planValues.values.length > 0 && earlyParallel.ok && earlyParallel.shard === null
&& (planValues.values.length > 1 || earlyParallel.workers > 1);
const planFlag = multiJourney ? { ok: true, value: undefined } : readStrictValueFlag(args, "plan");
const savePlanFlag = readStrictValueFlag(args, "save-plan");
if (!planFlag.ok || !savePlanFlag.ok) {
await Logger.flush();
process.exit(1);
}
const planPath = planFlag.value;
const savePlanPath = savePlanFlag.value;
if (planPath && (savePlanPath || args.includes("--single-page"))) {
Logger.error("❌ --plan replays a saved plan; it cannot be combined with --save-plan or --single-page.");
await Logger.flush();
process.exit(1);
}
if (savePlanPath && !args.includes("--single-page")) {
Logger.error("❌ --save-plan needs --single-page: a sweep produces one plan per page.");
await Logger.flush();
process.exit(1);
}
if (multiJourney && (savePlanFlag.value || args.includes("--single-page"))) {
Logger.error("❌ --plan replays a saved plan; it cannot be combined with --save-plan or --single-page.");
await Logger.flush();
process.exit(1);
}
let savedPlan = null;
let contractBinding = null;
if (planPath) {
try {
savedPlan = await PlanFile.load(planPath);
} catch (error) {
Logger.error(`❌ ${error.message}`);
await Logger.flush();
process.exit(error instanceof PlanFile.PlanError ? 2 : 1);
}
// GS12: the approved contract is bound (schema, digest, journey,
// approval state) before any browser exists. A failed binding does
// not stop the interaction steps; the verify step reports it unavailable.
if (savedPlan.contract) {
const storeRootFlag = readStrictValueFlag(args, "store-root");
if (!storeRootFlag.ok) {
await Logger.flush();
process.exit(1);
}
contractBinding = await ExecutionBinding.bind({
contractFile: savedPlan.contract.file,
journeyId: savedPlan.contract.journeyId,
storeRoot: storeRootFlag.value,
repoRoot: __dirname,
});
if (contractBinding.ok) Logger.info(`🔐 Contract bound: journey ${contractBinding.journeyId}, ${contractBinding.digest}`);
else Logger.warning(`⚠️ Contract not bound (${contractBinding.code}); business assertions will be reported unavailable.`);
}
}
let identities = await loadIdentitiesFor(contractBinding);
const urlArg = args.find((a) => a.startsWith("--url="));
const rawUrl = urlArg ? urlArg.slice("--url=".length) : (savedPlan ? savedPlan.url : DEFAULT_URL);
const url = rawUrl.startsWith("http") ? rawUrl : `https://${rawUrl}`;
if (savedPlan && new URL(url).origin !== new URL(savedPlan.url).origin) {
Logger.error("❌ --url does not match the origin of the saved plan's URL.");
await Logger.flush();
process.exit(2);
}
// Default off in CI (process.env.CI is the conventional signal nearly
// every CI system sets) so a headless run never blocks on a dashboard
// server nobody can see; --dashboard forces it back on if ever needed.
const noDashboard = args.includes("--no-dashboard")
|| (process.env.CI === "true" && !args.includes("--dashboard"));
// Sweep bounds. The defaults match SiteSweep's own so that passing
// nothing and passing the documented default produce the same run.
const singlePage = args.includes("--single-page");
const maxPages = numericArg(args, "max-pages", 20);
const budgetMs = numericArg(args, "budget-ms", 600_000);
const dedupe = !args.includes("--no-dedupe");
const sameOriginOnly = !args.includes("--allow-cross-origin");
// Phase 16: parallel/shard/merge flags are strict and parsed before the
// dashboard or the browser. `merge` is a separate command with its own
// exit codes (0/1 validated, 2 rejected input, 3 state not durable).
const parallel = parseParallelArgs(args);
if (args[0] === "merge") {
const argError = ParallelRunner.checkMergeArgv(args) || (parallel.ok ? null : parallel.message);
if (argError) {
Logger.error(`❌ ${argError}`);
await Logger.flush();
process.exit(2);
}
const expect = ParallelRunner.parseMergeExpect(args);
if (!expect.ok) {
Logger.error(`❌ ${expect.message}`);
await Logger.flush();
process.exit(2);
}
const code = await ParallelRunner.runMerge({
merge: { ...parallel.merge, expectRunId: expect.expectRunId, expectCommit: expect.expectCommit }, paths: ParallelRunner.defaultPaths(__dirname),
});
await Logger.flush();
process.exit(code);
}
if (!parallel.ok) {
Logger.error(`❌ ${parallel.message}`);
await Logger.flush();
process.exit(1);
}
const parallelRun = !multiJourney && (parallel.shard !== null || parallel.workers > 1);
if (parallelRun && (singlePage || savedPlan)) {
Logger.error("❌ --single-page and --plan cannot be combined with --workers or --shard.");
await Logger.flush();
process.exit(1);
}
// AC-02: unlike max-pages/budget-ms above, an invalid --repeat is a hard
// failure — process.exit(1) here, before the dashboard starts or the
// browser launches, so a typo'd flag never produces a partial run.
const repeatCount = requireRepeatCount(args);
if (repeatCount === null) {
process.exit(1);
}
// BYOK (ADR-0019): resolve --llm-profile/--llm-provider/--llm-model once,
// at startup, after argument validation and before any browser/page
// work. `providerContext` stays `null` when no --llm-* flag was given at
// all, which keeps the Phase 17 process-level default unchanged (AC23).
const llmProfileFlag = readStrictValueFlag(args, "llm-profile");
const llmProviderFlag = readStrictValueFlag(args, "llm-provider");
const llmModelFlag = readStrictValueFlag(args, "llm-model");
if (!llmProfileFlag.ok || !llmProviderFlag.ok || !llmModelFlag.ok) {
await Logger.flush();
process.exit(1);
}
const invocationResult = await InvocationContext.resolveFromFlags({
llmProfile: llmProfileFlag.value,
llmProvider: llmProviderFlag.value,
llmModel: llmModelFlag.value,
});
if (!invocationResult.ok) {
Logger.error(`❌ BYOK configuration error: ${invocationResult.errorCode}`);
await Logger.flush();
process.exit(1);
}
const providerContext = invocationResult.context;
if (!urlArg && !savedPlan && !multiJourney) {
Logger.info(`ℹ️ No --url supplied — defaulting to ${DEFAULT_URL}`);
}
const headless = process.env.HEADLESS !== "false";
// ── Dashboard ─────────────────────────────────────────────────────────────
const dashboard = new Dashboard({ port: Number(process.env.DASHBOARD_PORT) || 3000 }); // host: DASHBOARD_HOST, default 127.0.0.1
let dashboardUp = false;
if (!noDashboard && !multiJourney) {
try {
await dashboard.start(); // prints http://localhost:3000
dashboardUp = true;
} catch (error) {
// A refusal to expose an unauthenticated dashboard is a
// configuration error, not a transient failure: running on
// without it would hide the misconfiguration.
if (error.code === "DASHBOARD_EXPOSED_WITHOUT_TOKEN") {
Logger.error(`❌ ${error.message}`);
process.exit(1);
}
Logger.warning(`⚠️ Dashboard failed to start (${error.message}) — continuing without it.`);
}
}
const emit = (name, payload) => {
if (dashboardUp) dashboard.emit(name, payload);
};
// ── WP-77I-S2: approved-contract journeys on in-process workers ─────────
// Whole journeys are scheduled across workers by JourneyCoordinator; each
// journey gets its own BrowserContext and its own deep-copied plan and
// identities. Approval is re-checked at merge time and a report is only
// trusted when every journey's revalidation succeeded.
if (multiJourney) {
const mFail = async (message) => {
Logger.error(`❌ ${message}`);
await Logger.flush();
process.exit(1);
};
if (urlArg) await mFail("--url cannot be combined with several approved-contract plans; each plan carries its own URL.");
const storeRootFlag = readStrictValueFlag(args, "store-root");
if (!storeRootFlag.ok) {
await Logger.flush();
process.exit(1);
}
const journeys = [];
for (const file of planValues.values) {
try {
journeys.push({ planFile: file, plan: await PlanFile.load(file) });
} catch (error) {
Logger.error(`❌ ${error.message}`);
await Logger.flush();
process.exit(error instanceof PlanFile.PlanError ? 2 : 1);
}
}
const configCheck = JourneyCoordinator.validateConfig({ journeys, workers: parallel.workers, shard: null });
if (!configCheck.ok) await mFail(`Approved-contract run refused (${configCheck.code}).`);
const mReport = new ReportManager();
mReport.startRun();
const mStartedAt = Date.now();
let mBrowser;
try {
mBrowser = await chromium.launch({ headless });
Logger.info(`▶ ${journeys.length} approved-contract journey(s) on ${Math.min(parallel.workers, journeys.length)} in-process worker(s)…`);
const coordinated = await JourneyCoordinator.run({
journeys,
workers: parallel.workers,
storeRoot: storeRootFlag.value,
repoRoot: __dirname,
// The context lifecycle (open, run, always close) lives in
// JourneyCoordinator.runIsolated: a failed close() is flagged
// as cleanupFailed and never replaces the journey's own result.
executeJourney: ({ plan, binding }) => JourneyCoordinator.runIsolated(
() => mBrowser.newContext(),
async (jContext) => {
const jIdentities = await loadIdentitiesFor(binding);
const sweep = await runSavedPlan(jContext, plan, () => {}, repeatCount, providerContext, binding, jIdentities);
return { rows: sweep.pages.flatMap((p) => p.results), pages: sweep.pages };
}
),
});
if (!coordinated.ok) {
Logger.error(`❌ Approved-contract run refused (${coordinated.code}).`);
process.exitCode = 1;
} else {
for (const e of coordinated.entries) {
if (e.cleanupFailed) Logger.error(`❌ Journey ${e.journeyId}: execution context could not be closed (JOURNEY_CLEANUP_FAILED); isolation is uncertain, so this run cannot pass.`);
}
const allPages = coordinated.entries.flatMap((e) => (Array.isArray(e.pages) ? e.pages : []));
const report = mReport.generateReport({
tests: [],
uiIssues: allPages.flatMap((p) => p.uiIssues || []),
healingEvents: HealingReport._instance.logs,
coverage: deriveCoverage(allPages),
pages: allPages.map(pageBreakdown),
journeyEntries: coordinated.entries.map((e) => ({ binding: e.binding, rows: e.rows, revalidation: e.revalidation, ...(e.cleanupFailed ? { cleanupFailed: true } : {}) })),
requireRevalidation: true,
});
await recordRun({
incomplete: false, report, coverage: deriveCoverage(allPages), repeat: repeatCount, startedAt: mStartedAt,
});
}
} catch (error) {
Logger.error(`❌ Fatal error: ${error && error.code ? error.code : "error"}`);
process.exitCode = 1;
} finally {
await Logger.flush();
if (mBrowser) await mBrowser.close();
}
return;
}
// ── Phase 16: sharded / multi-worker run (never reached by default) ──────
if (parallelRun) {
let pBrowser;
try {
pBrowser = await chromium.launch({ headless });
let commit = "unknown";
try { commit = require("./src/core/history/GitInfo").getGitInfo().sha; } catch { /* unknown */ }
process.exitCode = await ParallelRunner.run({
browser: pBrowser, parsed: parallel, url, emit, repoRoot: __dirname, commit,
startedAt: Date.now(),
sweepOpts: { maxPages, budgetMs, dedupe, sameOriginOnly, repeat: repeatCount, providerContext },
});
} catch (error) {
Logger.error(`❌ Fatal error: ${error.message}`);
process.exitCode = 1;
} finally {
await Logger.flush();
if (pBrowser) await pBrowser.close();
if (dashboardUp) await dashboard.stop();
}
return;
}
// ── Browser ───────────────────────────────────────────────────────────────
let browser;
const reportManager = new ReportManager();
reportManager.startRun();
const runStartedAt = Date.now();
Logger.info(`🌍 Navigating to ${url}…`);
try {
browser = await chromium.launch({ headless });
const context = await browser.newContext();
const sweep = savedPlan
? await runSavedPlan(context, savedPlan, emit, repeatCount, providerContext, contractBinding, identities)
: singlePage
? await runEntryPageOnly(context, url, emit, repeatCount, providerContext, savePlanPath)
: await runWholeApp(context, url, emit, {
maxPages,
budgetMs,
dedupe,
sameOriginOnly,
repeat: repeatCount,
providerContext,
});
// One flat array for ReportManager: the tally, the pass/fail branch
// and the exit code are properties of the run, not of any one page.
// The per-page breakdown rides alongside in `pages`.
const results = sweep.pages.flatMap((p) => p.results);
const uiIssues = sweep.pages.flatMap((p) => p.uiIssues);
// Emit each result to the dashboard. "deduped" is deliberately not
// emitted: it is a bookkeeping entry for a scenario that was never
// executed on this page, so surfacing it as a test lifecycle event
// would inflate the live counters with work that did not happen.
for (const r of results) {
if (r.status === "passed") {
emit("testPass", { name: r.name, duration: r.duration });
} else if (r.status === "failed") {
emit("testFail", { name: r.name, error: r.error });
} else if (r.status === "skipped") {
emit("testSkip", { name: r.name, reason: r.reason });
} else if (r.status === "quarantined") {
emit("testQuarantined", { name: r.name, error: r.error });
} else if (r.status === "unavailable") {
// Phase 12: a target the healing chain could not resolve at
// all. The dashboard has no dedicated "unavailable" lifecycle
// event, and it would need its own contract change to gain
// one; "testFail" already renders the failure honestly (name
// + error) without the live view silently dropping the row,
// which is what a missing branch here would do.
emit("testFail", { name: r.name, error: r.error });
}
}
// The numbered step banners only describe the single-page pipeline;
// a sweep has no fixed step count, so it gets an unnumbered line
// rather than a stale "Step 5".
Logger.info(singlePage
? "📊 Step 5: Writing exploratory report…"
: "📊 Writing exploratory report…");
// executeExploratoryTest() only formats and writes the summary — it
// never touches this.page — and SiteSweep has already closed the
// pages it opened, so there is no live page to hand it here.
await new TestRunner(null, null, { providerContext }).executeExploratoryTest({
uiIssues,
exploredPages: sweep.pages.map((p) => p.url),
});
const report = reportManager.generateReport({
tests: results,
uiIssues,
healingEvents: HealingReport._instance.logs,
coverage: sweep.coverage,
pages: sweep.pages.map(pageBreakdown),
});
await recordRun({
incomplete: false, report, coverage: sweep.coverage, repeat: repeatCount, startedAt: runStartedAt,
});
} catch (error) {
const crashReport = reportManager.generateReport({ tests: [{ name: "falcon.js", status: "failed", error: error.message }] });
await recordRun({
incomplete: true, report: crashReport, coverage: null, repeat: repeatCount, startedAt: runStartedAt,
});
Logger.error(`❌ Fatal error: ${error.message}`);
console.error(error);
emit("testFail", { name: "falcon.js", error: error.message });
} finally {
await Logger.flush();
if (browser) await browser.close();
if (dashboardUp) {
const lingerMs = Number(process.env.DASHBOARD_LINGER_MS) || 60_000;
Logger.info(`🖥 Dashboard will stay up for ${(lingerMs / 1000).toFixed(0)} s — open ${dashboard.safeUrl} to review results.`);
Logger.info(" Press Ctrl-C to exit early.");
await new Promise((r) => setTimeout(r, lingerMs));
await dashboard.stop();
}
}
})();