@gate-forge/cli 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +220 -0
  2. package/README.md +13 -1
  3. package/bin/gateforge.js +3 -1
  4. package/dist/additional-app-origins.d.ts +38 -0
  5. package/dist/additional-app-origins.d.ts.map +1 -0
  6. package/dist/additional-app-origins.js +46 -0
  7. package/dist/additional-app-origins.js.map +1 -0
  8. package/dist/args.d.ts.map +1 -1
  9. package/dist/args.js +1 -0
  10. package/dist/args.js.map +1 -1
  11. package/dist/candidate-tree.d.ts +1 -1
  12. package/dist/candidate-tree.d.ts.map +1 -1
  13. package/dist/candidate-tree.js +24 -2
  14. package/dist/candidate-tree.js.map +1 -1
  15. package/dist/ci-witnessed-template.d.ts.map +1 -1
  16. package/dist/ci-witnessed-template.js +7 -5
  17. package/dist/ci-witnessed-template.js.map +1 -1
  18. package/dist/cli.d.ts +1 -1
  19. package/dist/cli.d.ts.map +1 -1
  20. package/dist/cli.js +1 -1
  21. package/dist/commands/adopt.d.ts.map +1 -1
  22. package/dist/commands/adopt.js +3 -3
  23. package/dist/commands/adopt.js.map +1 -1
  24. package/dist/commands/blocking.d.ts.map +1 -1
  25. package/dist/commands/blocking.js +1 -0
  26. package/dist/commands/blocking.js.map +1 -1
  27. package/dist/commands/check.d.ts.map +1 -1
  28. package/dist/commands/check.js +12 -7
  29. package/dist/commands/check.js.map +1 -1
  30. package/dist/commands/enforcement.d.ts +12 -1
  31. package/dist/commands/enforcement.d.ts.map +1 -1
  32. package/dist/commands/enforcement.js +85 -34
  33. package/dist/commands/enforcement.js.map +1 -1
  34. package/dist/commands/test-gates.d.ts +83 -0
  35. package/dist/commands/test-gates.d.ts.map +1 -1
  36. package/dist/commands/test-gates.js +118 -48
  37. package/dist/commands/test-gates.js.map +1 -1
  38. package/dist/evaluate.d.ts +9 -0
  39. package/dist/evaluate.d.ts.map +1 -1
  40. package/dist/evaluate.js +34 -5
  41. package/dist/evaluate.js.map +1 -1
  42. package/dist/execution.d.ts +0 -25
  43. package/dist/execution.d.ts.map +1 -1
  44. package/dist/execution.js +16 -11
  45. package/dist/execution.js.map +1 -1
  46. package/dist/git-ignored.d.ts +22 -0
  47. package/dist/git-ignored.d.ts.map +1 -1
  48. package/dist/git-ignored.js +49 -0
  49. package/dist/git-ignored.js.map +1 -1
  50. package/dist/providers.d.ts +22 -0
  51. package/dist/providers.d.ts.map +1 -1
  52. package/dist/providers.js +60 -11
  53. package/dist/providers.js.map +1 -1
  54. package/dist/reseal.d.ts.map +1 -1
  55. package/dist/reseal.js +30 -14
  56. package/dist/reseal.js.map +1 -1
  57. package/dist/runtime-reuse.d.ts +8 -0
  58. package/dist/runtime-reuse.d.ts.map +1 -1
  59. package/dist/runtime-reuse.js +40 -0
  60. package/dist/runtime-reuse.js.map +1 -1
  61. package/guides/QUICKSTART.md +7 -7
  62. package/guides/REFERENCE.md +45 -1
  63. package/guides/TEST-ENVIRONMENT.md +15 -8
  64. package/package.json +11 -11
@@ -59,8 +59,8 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync,
59
59
  import { setTimeout as delay } from 'node:timers/promises';
60
60
  import { tmpdir } from 'node:os';
61
61
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
62
- import { AttestationSchema, BEHAVIOR_CASE_KIND, BehaviorCasePayloadSchema, BehaviorCatalogRegistrationSchema, CAUSE_NEXT_ACTIONS, canonicalJson, compareStrings, caseExecutionDigestOf, EMPTY_BEHAVIOR_CATALOG_DIGEST, engineBundleDigestOf, EvidenceRecordSchema, GateReceiptSchema, ExecutionResultSchema, executionBoundaryDigestOf, evaluateObligation, LOCAL_UNISOLATED_BOUNDARY, humanMessage, isWitnessedRecord, renderRun, requiredCaseSetDigestOf, repositoryDebtOf, runExitCode, sha256Canonical, selectionDigestOf, targetArtifactDigestOf, verifyAttestationMac, executionResultDigestOf, testOutcomesDigestOf, verifyRunRecord, BLOCKING_VERDICTS, decideStrictness, loadQuarantines, QUARANTINE_DIR, resolveStrictnessMode, strictnessSummaryLine, twinDivergenceDetail, twinLinksFor, twinPathDivergence, withoutQuarantinedBindings, } from '@gate-forge/core';
63
- import { appendFreezeReleaseEvent, armFreezeControl, buildWitnessedPytestChildEnv, canonicalFreezeJson, defaultPlaywrightCommand, diffNativePlaywrightTests, discoverTestCatalog, findPlaywrightConfig, isPlaywrightRunnerInstall, listNativePlaywrightTests, mintFreezeSigningKeyPair, nativeConfigDirOf, playwrightTestModulePath, removeFreezeSpecDir, signFreezeRelease, spoolPathFor, supervisedRunnerChildEnv, writeFreezeRefusal, resolveProjectStorageState, CypressRunnerAdapter, PlaywrightAdapter, PytestRunnerAdapter, readRunnerOutcomes, startSupervisorSpoolDrain, startWitnessProcess, SupervisorClient, TestDiscoveryError, VitestRunnerAdapter, RUN_HEADER, VERIFIER_HEADER, DEFAULT_RUN_TIMEOUT_MS, ENV_CHAOS_MAX_DELAY_MS, ENV_CHAOS_REORDER, ENV_CHAOS_SEED, ENV_PROXY_TARGET, ENV_TWIN_INVENTORY, ENV_TWIN_QUERY_KEYS, ENV_TWIN_SHAPES, } from '@gate-forge/pack-playwright';
62
+ import { AttestationSchema, BEHAVIOR_CASE_KIND, BehaviorCasePayloadSchema, BehaviorCatalogRegistrationSchema, CAUSE_NEXT_ACTIONS, canonicalJson, compareStrings, caseExecutionDigestOf, EMPTY_BEHAVIOR_CATALOG_DIGEST, engineBundleDigestOf, EvidenceRecordSchema, GateReceiptSchema, ExecutionResultSchema, executionBoundaryDigestOf, evaluateObligation, LOCAL_UNISOLATED_BOUNDARY, humanMessage, isWitnessedRecord, renderRun, requiredCaseSetDigestOf, repositoryDebtOf, runExitCode, sha256Canonical, selectionDigestOf, targetArtifactDigestOf, verifyAttestationMac, executionResultDigestOf, testOutcomesDigestOf, verifyRunRecord, BLOCKING_VERDICTS, decideStrictness, loadQuarantines, QUARANTINE_DIR, resolveStrictnessMode, strictnessSummaryLine, twinDivergenceDetail, twinLinksFor, twinPathDivergence, withoutQuarantinedBindings, runnerLogicalKey, } from '@gate-forge/core';
63
+ import { appendFreezeReleaseEvent, armFreezeControl, buildWitnessedPytestChildEnv, canonicalFreezeJson, defaultPlaywrightCommand, diffNativePlaywrightTests, discoverTestCatalog, refreshCatalogAfterRunnerEnumeration, findPlaywrightConfig, isPlaywrightRunnerInstall, listNativePlaywrightTests, mintFreezeSigningKeyPair, nativeConfigDirOf, playwrightTestModulePath, removeFreezeSpecDir, signFreezeRelease, spoolPathFor, supervisedRunnerChildEnv, writeFreezeRefusal, resolveProjectStorageState, CypressRunnerAdapter, PlaywrightAdapter, PytestRunnerAdapter, readRunnerOutcomes, startSupervisorSpoolDrain, startWitnessProcess, SupervisorClient, TestDiscoveryError, VitestRunnerAdapter, RUN_HEADER, VERIFIER_HEADER, DEFAULT_RUN_TIMEOUT_MS, ENV_CHAOS_MAX_DELAY_MS, ENV_CHAOS_REORDER, ENV_CHAOS_SEED, ENV_PROXY_TARGET, ENV_TWIN_INVENTORY, ENV_TWIN_QUERY_KEYS, ENV_TWIN_SHAPES, autoSessionNodeOptions, } from '@gate-forge/pack-playwright';
64
64
  import { parseArgs, repeatableStringFlag, stringFlag } from '../args.js';
65
65
  import { resolveAdoptedBaseline } from '../adopted-baseline.js';
66
66
  import { UsageError } from '../errors.js';
@@ -85,9 +85,10 @@ import { computeEvaluationScope } from '../scope.js';
85
85
  import { candidateTreeCoversCommit, computeCandidateTreeSnapshot, listTrackedPaths, resolveGitDir, sanitizedAuthorityEnv } from '../candidate-tree.js';
86
86
  import { acceptedFreezeRequest, classifyGeneratedTargets, planNativeFreeze, preparedCandidateViolations, unfrozenPrerequisiteState, } from '../native-freeze.js';
87
87
  import { loadRuntimeConfigAt, resolveRuntimeReuseDigest } from '../runtime.js';
88
- import { mergeRequestScopePreflight, resolveProvider } from '../providers.js';
88
+ import { mergeRequestScopePreflight, resolveGithubBaseCommit, resolveProvider } from '../providers.js';
89
89
  import { engineIdentity, reportEngineLine } from '../engine-identity.js';
90
90
  import { assertReceiptApprovedPolicy, evaluateApprovedPolicy, resolveApprovedPolicyDigest } from '../trusted-policy.js';
91
+ import { resolveAdditionalAppOrigins } from '../additional-app-origins.js';
91
92
  import { unstagedPolicyInputs } from './enforcement.js';
92
93
  import { clearGateReceipt, clearRunRecord, httpRoutesView, readJsonArray, readStateDocument, resolveStateDir, stateObligations, writeClaimInjections, writeClassificationsView, writeEnv, writeExecutionResult, writeCandidateTreeEntries, writeGateReceipt, writeHttpRoutesView, writeInputSnapshot, writeManifest, writeObligations, writeLastFullRunSummary, writeReport, writeRunRecord, writeTwinInventory, writeTwinShapes, } from '../state.js';
93
94
  import { engineGeneratedStateFileFilter } from '../state-artifacts.js';
@@ -610,6 +611,7 @@ async function legacyTestGates(io, options) {
610
611
  [VERIFIER_KEY_ENV]: undefined,
611
612
  [VERIFIER_KEY_FILE_ENV]: undefined,
612
613
  ...suiteEnv,
614
+ ...(witnessUrl === undefined ? {} : { NODE_OPTIONS: autoSessionNodeOptions(suiteEnv['NODE_OPTIONS'] ?? io.env['NODE_OPTIONS']) }),
613
615
  },
614
616
  });
615
617
  suiteFailed = suiteStatus !== 0;
@@ -705,6 +707,7 @@ async function legacyTestGates(io, options) {
705
707
  ? {}
706
708
  : { advisories: [...evaluated.httpCallAdvisories] }),
707
709
  ...(evaluated.httpLedger === undefined ? {} : { httpLedger: evaluated.httpLedger }),
710
+ ...(evaluated.uiLedger === undefined ? {} : { uiLedger: evaluated.uiLedger }),
708
711
  httpCoverage: evaluated.httpCoverage.summary,
709
712
  });
710
713
  writeLine(io.stdout, report);
@@ -722,6 +725,7 @@ async function legacyTestGates(io, options) {
722
725
  ? {}
723
726
  : { advisories: [...evaluated.httpCallAdvisories] }),
724
727
  ...(evaluated.httpLedger === undefined ? {} : { httpLedger: evaluated.httpLedger }),
728
+ ...(evaluated.uiLedger === undefined ? {} : { uiLedger: evaluated.uiLedger }),
725
729
  httpCoverage: evaluated.httpCoverage.summary,
726
730
  }));
727
731
  const gateCode = runExitCode({ verdicts: evaluated.verdicts, blocking: evaluated.blocking });
@@ -877,7 +881,7 @@ export function twinPairNotComparedLine(link, witnessedObserved, rawObserved) {
877
881
  ].join(' and ');
878
882
  const fix = rawObserved
879
883
  ? ''
880
- : ' — a raw twin is observed only when it runs with the Gateforge test fixture, which opens an observation-only session for it (it issues no evidence)';
884
+ : ' — use a supported Playwright test import (@playwright/test or playwright/test) for automatic sessions, or the explicit Gateforge test fixture, and send browser requests through the session proxy; linked raw twins are observation-only (they issue no evidence)';
881
885
  return `test-gates: twin pair not compared: ${unobserved} sent no request through the witness${fix}`;
882
886
  }
883
887
  /** Candidate keys listed in an unresolved-selector error are capped at this many. */
@@ -966,19 +970,20 @@ export function resolveTestSelectors(selectors, rows) {
966
970
  * Returns:
967
971
  * string | null: verified 40-character base commit, or null when unavailable.
968
972
  */
969
- function resolveCarryForwardBaseSha(io, provider) {
973
+ export function resolveCarryForwardBaseSha(io, provider) {
970
974
  if (provider === 'gitlab-mr') {
971
975
  const sha = io.env['CI_MERGE_REQUEST_DIFF_BASE_SHA']?.trim() ?? '';
972
976
  return /^[0-9a-f]{40}$/.test(sha) ? sha : null;
973
977
  }
974
978
  if (provider !== 'github-pr')
975
979
  return null;
976
- const baseRef = io.env['GITHUB_BASE_REF']?.trim() ?? '';
977
- if (baseRef.length === 0 || baseRef.startsWith('-') || /[\\s\\0]/.test(baseRef))
980
+ const authorityEnv = sanitizedAuthorityEnv(io.env);
981
+ const baseCommit = resolveGithubBaseCommit(io.cwd, io.env['GITHUB_BASE_REF'] ?? '', authorityEnv);
982
+ if (baseCommit === null)
978
983
  return null;
979
- const result = spawnSync('git', ['--no-replace-objects', 'merge-base', 'HEAD', baseRef], {
984
+ const result = spawnSync('git', ['--no-replace-objects', 'merge-base', 'HEAD', baseCommit], {
980
985
  cwd: io.cwd,
981
- env: sanitizedAuthorityEnv(io.env),
986
+ env: authorityEnv,
982
987
  encoding: 'utf8',
983
988
  });
984
989
  const sha = (result.stdout ?? '').trim();
@@ -1098,7 +1103,7 @@ function verifyCarryForwardParent(input) {
1098
1103
  const treeId = receipt.candidateTreeId;
1099
1104
  if (input.gitDir === null ||
1100
1105
  treeId === null ||
1101
- !candidateTreeCoversCommit(input.gitDir, input.io.env, treeId, `${bound.sha}^{tree}`, input.docsExclusions, input.cacheExclusions)) {
1106
+ !candidateTreeCoversCommit(input.gitDir, input.io.env, treeId, `${bound.sha}^{tree}`, input.io.cwd, input.docsExclusions, input.cacheExclusions)) {
1102
1107
  return refuse(`its sealed tree is not the tree of commit ${shortSha(bound.sha)} (uncommitted changes were tested)`);
1103
1108
  }
1104
1109
  if (input.parentCommitBinding !== 'own-ancestor-commit' && receipt.gitSha !== input.baseSha) {
@@ -1242,7 +1247,7 @@ function verifyRunRecordParent(input) {
1242
1247
  const treeId = record.candidateTreeId;
1243
1248
  if (input.gitDir === null ||
1244
1249
  treeId === null ||
1245
- !candidateTreeCoversCommit(input.gitDir, input.io.env, treeId, `${bound.sha}^{tree}`, input.docsExclusions, input.cacheExclusions)) {
1250
+ !candidateTreeCoversCommit(input.gitDir, input.io.env, treeId, `${bound.sha}^{tree}`, input.io.cwd, input.docsExclusions, input.cacheExclusions)) {
1246
1251
  return refuse(`its sealed tree is not the tree of commit ${shortSha(bound.sha)} (uncommitted changes were tested)`);
1247
1252
  }
1248
1253
  if (input.parentCommitBinding !== 'own-ancestor-commit' && record.gitSha !== input.baseSha) {
@@ -1685,7 +1690,7 @@ function quarantinedInstanceKeys(catalog, quarantinedKeys) {
1685
1690
  for (const entry of catalog.entries) {
1686
1691
  if (!quarantinedKeys.has(entry.logicalKey))
1687
1692
  continue;
1688
- keys.add(`${entry.file}#${entry.titlePath.join('>')}`);
1693
+ keys.add(runnerLogicalKey(entry.file, entry.titlePath));
1689
1694
  }
1690
1695
  return keys;
1691
1696
  }
@@ -1777,7 +1782,7 @@ function plannedRowOfIdentity(test) {
1777
1782
  * @throws UsageError on a runner name with no adapter (the config
1778
1783
  * schema rejects unknown values first — this is a defensive seam).
1779
1784
  */
1780
- function runnerAdapterFor(runner, wiring = {}) {
1785
+ function runnerAdapterFor(runner, wiring = {}, adapterOptions = {}) {
1781
1786
  const witness = {
1782
1787
  ...(wiring.witnessUrl !== undefined && wiring.witnessUrl !== '' ? { url: wiring.witnessUrl } : {}),
1783
1788
  ...(wiring.runToken !== undefined && wiring.runToken !== '' ? { token: wiring.runToken } : {}),
@@ -1795,7 +1800,12 @@ function runnerAdapterFor(runner, wiring = {}) {
1795
1800
  case 'pytest':
1796
1801
  return new PytestRunnerAdapter({ witness, ...appBaseUrl });
1797
1802
  case 'vitest':
1798
- return new VitestRunnerAdapter({ witness: sessionWiring });
1803
+ return new VitestRunnerAdapter({
1804
+ witness: sessionWiring,
1805
+ ...(adapterOptions.enumerationTimeoutMs === undefined
1806
+ ? {}
1807
+ : { enumerationTimeoutMs: adapterOptions.enumerationTimeoutMs }),
1808
+ });
1799
1809
  case 'cypress':
1800
1810
  return new CypressRunnerAdapter({ witness: sessionWiring });
1801
1811
  default:
@@ -1888,6 +1898,9 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
1888
1898
  // RunnerAdapter contract behind the SAME witness session, run token,
1889
1899
  // supervision, receipts, and strictness machinery.
1890
1900
  const runnerName = config.runner;
1901
+ const vitestEnumerationTimeoutMs = config.witness.enumerationTimeoutSeconds !== undefined
1902
+ ? config.witness.enumerationTimeoutSeconds * 1000
1903
+ : undefined;
1891
1904
  // The timing-chaos plan for THIS run (E63). Null without the flag:
1892
1905
  // then the witness is spawned with no plan and every byte of the run
1893
1906
  // is exactly what it was before chaos existed. The bounds come from
@@ -2073,6 +2086,9 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
2073
2086
  cwd: io.cwd,
2074
2087
  config,
2075
2088
  collectPytest: true,
2089
+ ...(vitestEnumerationTimeoutMs === undefined
2090
+ ? {}
2091
+ : { vitestEnumerationTimeoutMs }),
2076
2092
  // The state directory this run ACTUALLY resolved (`--out` aware):
2077
2093
  // the supervised run's own generated config — and, for a
2078
2094
  // repository carrying one, an earlier build's freeze control files
@@ -2505,7 +2521,7 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
2505
2521
  // again. Nothing about the enumeration is assumed — an adapter that
2506
2522
  // cannot list its tests returns `status: 'unavailable'`, and that
2507
2523
  // plans nothing rather than planning a guessed half-set.
2508
- const enumeration = await runnerAdapterFor(runnerName).enumerate(io.cwd);
2524
+ const enumeration = await runnerAdapterFor(runnerName, {}, vitestEnumerationTimeoutMs === undefined ? {} : { enumerationTimeoutMs: vitestEnumerationTimeoutMs }).enumerate(io.cwd);
2509
2525
  runnerEnumeration = enumeration;
2510
2526
  if (enumeration.status === 'discovered') {
2511
2527
  const enumeratedRows = enumeration.tests.map(plannedRowOfIdentity);
@@ -2514,6 +2530,9 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
2514
2530
  options.scope === 'changed'
2515
2531
  ? enumeratedRows.filter((row) => affectedRequiredFiles.includes(row.planned.file))
2516
2532
  : enumeratedRows;
2533
+ if (catalog !== null && (runnerName === 'vitest' || runnerName === 'cypress')) {
2534
+ catalog = refreshCatalogAfterRunnerEnumeration(catalog, runnerName, enumeration, io.cwd);
2535
+ }
2517
2536
  }
2518
2537
  }
2519
2538
  // Named selection (`--test`): the plan is built from the FULL planned
@@ -2811,6 +2830,7 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
2811
2830
  ? {}
2812
2831
  : { advisories: [...evaluated.httpCallAdvisories] }),
2813
2832
  ...(evaluated.httpLedger === undefined ? {} : { httpLedger: evaluated.httpLedger }),
2833
+ ...(evaluated.uiLedger === undefined ? {} : { uiLedger: evaluated.uiLedger }),
2814
2834
  httpCoverage: evaluated.httpCoverage.summary,
2815
2835
  });
2816
2836
  writeLine(io.stdout, report);
@@ -3267,6 +3287,12 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
3267
3287
  const adapterBase = io.env['GATEFORGE_ADAPTER_BASE_URL'] !== undefined && io.env['GATEFORGE_ADAPTER_BASE_URL'] !== ''
3268
3288
  ? io.env['GATEFORGE_ADAPTER_BASE_URL']
3269
3289
  : targetBase;
3290
+ // The owner's DECLARED additional app origins (0.15.0), resolved
3291
+ // fail-closed from the trusted orchestrator environment. Each one
3292
+ // becomes an extra attested upstream with its own per-session
3293
+ // proxy; absent declaration = the variable is not passed at all and
3294
+ // the witness is byte-identical to every earlier one.
3295
+ const additionalAppOrigins = resolveAdditionalAppOrigins(config, io.env);
3270
3296
  spawnedWitness = await startWitnessProcess({
3271
3297
  GATEFORGE_RUN_ID: manifest.runId,
3272
3298
  GATEFORGE_RUN_TOKEN: runToken,
@@ -3279,6 +3305,9 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
3279
3305
  GATEFORGE_CLASSIFICATIONS: join(stateDir, 'classifications.json'),
3280
3306
  ...(targetBase !== '' ? { GATEFORGE_TARGET_BASE_URL: targetBase } : {}),
3281
3307
  ...(adapterBase !== '' ? { GATEFORGE_ADAPTER_BASE_URL: adapterBase } : {}),
3308
+ ...(additionalAppOrigins.length > 0
3309
+ ? { GATEFORGE_ADDITIONAL_APP_ORIGINS: JSON.stringify(additionalAppOrigins) }
3310
+ : {}),
3282
3311
  ...(io.env['GATEFORGE_TARGET_FINGERPRINT'] !== undefined && io.env['GATEFORGE_TARGET_FINGERPRINT'] !== ''
3283
3312
  ? { GATEFORGE_TARGET_FINGERPRINT: io.env['GATEFORGE_TARGET_FINGERPRINT'] }
3284
3313
  : {}),
@@ -3407,7 +3436,7 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
3407
3436
  // if it had. Say which, rather than reporting the fiction.
3408
3437
  if (chaosRun !== null && appliedOptions?.chaos == null) {
3409
3438
  if (spawnedWitness !== null)
3410
- await stopWitnessProcess(spawnedWitness);
3439
+ await stopWitnessProcess(io, spawnedWitness);
3411
3440
  throw new UsageError(`test-gates: --chaos ${String(chaosRun.seed)} needs a witness that accepts run options; the witness at ` +
3412
3441
  `'${effectiveWitnessUrl ?? ''}' confirmed no chaos plan, so no schedule was applied and this run would ` +
3413
3442
  'report a finding it never made — upgrade the witness');
@@ -3461,7 +3490,7 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
3461
3490
  // the suite's own account of execution — refuse it instead.
3462
3491
  if (effectiveWitnessUrl === undefined || witnessVerifierKey === undefined) {
3463
3492
  if (spawnedWitness !== null) {
3464
- await stopWitnessProcess(spawnedWitness);
3493
+ await stopWitnessProcess(io, spawnedWitness);
3465
3494
  }
3466
3495
  throw new UsageError(`test-gates --changed requires ${VERIFIER_KEY_ENV} or ${VERIFIER_KEY_FILE_ENV} in the orchestrating environment: ` +
3467
3496
  'the witness supervisor surface (expected set, session lifecycle, execution trace) is ' +
@@ -3628,7 +3657,7 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
3628
3657
  // a suite-controlled variable can disable observation but can never
3629
3658
  // enable false proof.
3630
3659
  if (pageObservation !== null) {
3631
- writeLine(io.stderr, 'PAGE_OBSERVATION_FIXTURE_REQUIRED: page records are issued only for tests using the Gateforge Playwright fixture; other tests produce no page-observation records.');
3660
+ writeLine(io.stderr, 'PAGE_OBSERVATION_ENABLED: page records are retained for passing tests with session-backed observation, including automatic Playwright sessions; uninstrumented tests produce no page-observation records.');
3632
3661
  const reportedTamperLocations = new Set();
3633
3662
  for (const risk of pageObservation.tamperRisks) {
3634
3663
  const key = `${risk.file}\u0000${risk.locationFile}\u0000${risk.line}`;
@@ -3716,7 +3745,7 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
3716
3745
  }
3717
3746
  catch (error) {
3718
3747
  if (spawnedWitness !== null)
3719
- await stopWitnessProcess(spawnedWitness);
3748
+ await stopWitnessProcess(io, spawnedWitness);
3720
3749
  throw new UsageError(`test-gates: the global native preparation freeze refuses this run — ${error.message}`);
3721
3750
  }
3722
3751
  }
@@ -3825,7 +3854,7 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
3825
3854
  }
3826
3855
  catch (error) {
3827
3856
  if (spawnedWitness !== null)
3828
- await stopWitnessProcess(spawnedWitness);
3857
+ await stopWitnessProcess(io, spawnedWitness);
3829
3858
  if (armedFreeze !== null)
3830
3859
  removeFreezeSpecDir(armedFreeze.control);
3831
3860
  throw error;
@@ -4066,7 +4095,7 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
4066
4095
  // completion signal — exactly as the progress stream below does.
4067
4096
  runActivity.onTestFinished?.(title);
4068
4097
  progress.endTest({
4069
- logicalKey: `${event.file ?? ''}#${event.titlePath.join('>')}`,
4098
+ logicalKey: runnerLogicalKey(event.file ?? '', event.titlePath),
4070
4099
  title,
4071
4100
  outcome: progressOutcomeOf(event.outcome),
4072
4101
  ...(event.errorMessage === undefined ? {} : { message: event.errorMessage }),
@@ -4085,6 +4114,10 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
4085
4114
  let sessionTrace = null;
4086
4115
  let lifecycleConflicts = [];
4087
4116
  let intentFailures = [];
4117
+ // The live attestation envelope (step 8 below) — fetched in the
4118
+ // `finally` while the spawned witness still serves, persisted as the
4119
+ // durable fallback, then the witness is stopped. `null` until then.
4120
+ let liveAttestation = null;
4088
4121
  // The FINAL control-spec verdict, decided in the `finally` below — at
4089
4122
  // the close of the supervised window, which is the last moment the
4090
4123
  // generated spec is read — and consumed below, after the run sealed.
@@ -4174,7 +4207,7 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
4174
4207
  witnessUrl: effectiveWitnessUrl,
4175
4208
  runToken,
4176
4209
  appBaseUrl: io.env['GATEFORGE_APP_BASE_URL'] ?? '',
4177
- }).execute(request);
4210
+ }, vitestEnumerationTimeoutMs === undefined ? {} : { enumerationTimeoutMs: vitestEnumerationTimeoutMs }).execute(request);
4178
4211
  }
4179
4212
  else {
4180
4213
  // The runner could not enumerate its expected set: nothing is
@@ -4399,11 +4432,26 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
4399
4432
  }
4400
4433
  }
4401
4434
  }
4402
- if (spawnedWitness !== null) {
4403
- // Graceful stop (the same contract as the consumer teardown): the
4404
- // witness appends its attested manifest envelope at shutdown, so
4405
- // the durable evidence channel is sealed before evaluation.
4406
- await stopWitnessProcess(spawnedWitness);
4435
+ // 8. Live attestation (same discipline as the legacy path). It is read
4436
+ // while the spawned witness still serves it: a stopped witness refuses
4437
+ // the read, so the stop below must come after it.
4438
+ // The stop sits in its own finally: a throwing read or persist must
4439
+ // still shut the spawned witness down, and the error still propagates.
4440
+ try {
4441
+ liveAttestation = await fetchWitnessAttestation(io, effectiveWitnessUrl, runToken, witnessVerifierKey, expectedDigest === null
4442
+ ? null
4443
+ : { runId: manifest.runId, invocationId, inputDigest: expectedDigest });
4444
+ if (liveAttestation !== null) {
4445
+ persistLiveAttestation(stateDir, liveAttestation);
4446
+ }
4447
+ }
4448
+ finally {
4449
+ if (spawnedWitness !== null) {
4450
+ // Graceful stop (the same contract as the consumer teardown): the
4451
+ // witness appends its attested manifest envelope at shutdown, so
4452
+ // the durable evidence channel is sealed before evaluation.
4453
+ await stopWitnessProcess(io, spawnedWitness);
4454
+ }
4407
4455
  }
4408
4456
  try {
4409
4457
  hostLoadCollector?.stop();
@@ -4510,7 +4558,7 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
4510
4558
  sessionTrace =
4511
4559
  sessionTrace === null
4512
4560
  ? null
4513
- : sessionTrace.filter((traced) => !ungradedKeys.has(`${traced.file}#${traced.titlePath.join('>')}`));
4561
+ : sessionTrace.filter((traced) => !ungradedKeys.has(runnerLogicalKey(traced.file, traced.titlePath)));
4514
4562
  }
4515
4563
  }
4516
4564
  if (options.runtimeReuseCheck !== undefined) {
@@ -4544,10 +4592,10 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
4544
4592
  ? rawOutcomesDoc
4545
4593
  : {
4546
4594
  ...rawOutcomesDoc,
4547
- outcomes: rawOutcomesDoc.outcomes.filter((row) => !unrequiredInstances.has(`${row.file}#${row.titlePath.join('>')}`)),
4595
+ outcomes: rawOutcomesDoc.outcomes.filter((row) => !unrequiredInstances.has(runnerLogicalKey(row.file, row.titlePath))),
4548
4596
  };
4549
4597
  if (sessionTrace !== null && unrequiredInstances.size > 0) {
4550
- sessionTrace = sessionTrace.filter((test) => !unrequiredInstances.has(`${test.file}#${test.titlePath.join('>')}`));
4598
+ sessionTrace = sessionTrace.filter((test) => !unrequiredInstances.has(runnerLogicalKey(test.file, test.titlePath)));
4551
4599
  }
4552
4600
  const sealed = sealExecutionResult({
4553
4601
  runId: manifest.runId,
@@ -4592,13 +4640,6 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
4592
4640
  changedInputs = true;
4593
4641
  }
4594
4642
  }
4595
- // 8. Live attestation (same discipline as the legacy path).
4596
- const liveAttestation = await fetchWitnessAttestation(io, effectiveWitnessUrl, runToken, witnessVerifierKey, expectedDigest === null
4597
- ? null
4598
- : { runId: manifest.runId, invocationId, inputDigest: expectedDigest });
4599
- if (liveAttestation !== null) {
4600
- persistLiveAttestation(stateDir, liveAttestation);
4601
- }
4602
4643
  // 9. Evaluate + project supervision/mapping/inventory/lifecycle findings
4603
4644
  // into blocking entries (never diff-scoped, never waived). Lifecycle
4604
4645
  // conflicts (duplicate begins, lone ends) are worker-side forgery or
@@ -5020,7 +5061,11 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
5020
5061
  }
5021
5062
  return 1;
5022
5063
  }
5064
+ if (envelope.startupDiagnostic !== undefined) {
5065
+ writeLine(io.stderr, envelope.incompleteDetail ?? 'RUNNER_STARTUP_FAILED');
5066
+ }
5023
5067
  const diagnosticContext = {
5068
+ ...(envelope.startupDiagnostic === undefined ? {} : { runnerStartup: envelope.startupDiagnostic }),
5024
5069
  scope: namedTestIds !== null ? 'named' : options.scope,
5025
5070
  candidateTreeId: testedTreeId,
5026
5071
  inputDigest: expectedDigest,
@@ -5093,6 +5138,7 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
5093
5138
  : { chaos: { ...chaosRun, ...(chaosSchedule === null ? {} : { schedule: chaosSchedule }) } }),
5094
5139
  ...(localFailures.length === 0 ? {} : { failedTests: localFailures }),
5095
5140
  ...(evaluated.httpLedger === undefined ? {} : { httpLedger: evaluated.httpLedger }),
5141
+ ...(evaluated.uiLedger === undefined ? {} : { uiLedger: evaluated.uiLedger }),
5096
5142
  httpCoverage: evaluated.httpCoverage.summary,
5097
5143
  });
5098
5144
  /**
@@ -5122,6 +5168,7 @@ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames)
5122
5168
  ? {}
5123
5169
  : { chaos: { ...chaosRun, ...(chaosSchedule === null ? {} : { schedule: chaosSchedule }) } }),
5124
5170
  ...(evaluated.httpLedger === undefined ? {} : { httpLedger: evaluated.httpLedger }),
5171
+ ...(evaluated.uiLedger === undefined ? {} : { uiLedger: evaluated.uiLedger }),
5125
5172
  httpCoverage: evaluated.httpCoverage.summary,
5126
5173
  })),
5127
5174
  ...(gateMode === 'strict'
@@ -5651,6 +5698,8 @@ function runExecutionSummaryOf(input) {
5651
5698
  scope: input.scope,
5652
5699
  mode: input.mode,
5653
5700
  testsPerformedThisInvocation: input.mode === 'executed' ? performed : 0,
5701
+ executedTests: input.executionResult.executedTests ?? performed,
5702
+ measuredTests: input.executionResult.measuredTests ?? input.executionResult.sessionTrace?.filter((test) => test.sessions.length > 0).length ?? 0,
5654
5703
  selectedTests: {
5655
5704
  selected,
5656
5705
  passed,
@@ -5679,26 +5728,46 @@ const EMPTY_CATALOG = {
5679
5728
  inventoryComplete: false,
5680
5729
  runnerSummaries: [],
5681
5730
  };
5731
+ /**
5732
+ * The grace a spawned witness gets between SIGTERM and SIGKILL. The
5733
+ * witness's shutdown sequence is long by design — proxy listeners,
5734
+ * session proxies, page observers, fixture leases, queue channel,
5735
+ * engine browser, HTTP server — and the attested manifest envelope is
5736
+ * appended LAST, so the bound must cover that whole sequence. The wait
5737
+ * itself is on the EXIT event: a witness that shuts down in half a
5738
+ * second is reaped immediately, and only a genuinely hung shutdown
5739
+ * ever reaches the bound.
5740
+ */
5741
+ const WITNESS_STOP_GRACE_MS = 30_000;
5682
5742
  /**
5683
5743
  * Gracefully stops a witness this command spawned (the same contract as
5684
- * the consumer teardown): SIGTERM with a short grace period so the
5685
- * witness appends its attested manifest envelope, then SIGKILL.
5744
+ * the consumer teardown): SIGTERM, then wait for the process to EXIT so
5745
+ * the witness can run its whole shutdown sequence and append the
5746
+ * attested manifest envelope. If the bounded grace expires first, the
5747
+ * SIGKILL is a REPORTED failure on stderr — the envelope is then known
5748
+ * to be absent, and a missing durable attestation must be explainable,
5749
+ * never silent.
5686
5750
  *
5687
5751
  * Args:
5752
+ * io: output target for the reported-SIGKILL failure line.
5688
5753
  * handle: the spawned witness handle.
5689
5754
  */
5690
- async function stopWitnessProcess(handle) {
5755
+ export async function stopWitnessProcess(io, handle) {
5756
+ if (handle.child.exitCode !== null || handle.child.signalCode !== null)
5757
+ return;
5691
5758
  handle.child.kill('SIGTERM');
5692
- await new Promise((resolveWait) => {
5693
- const timer = setTimeout(() => {
5694
- handle.child.kill('SIGKILL');
5695
- resolveWait();
5696
- }, 2000);
5759
+ const exited = await new Promise((resolveWait) => {
5760
+ const timer = setTimeout(() => resolveWait(false), WITNESS_STOP_GRACE_MS);
5697
5761
  handle.child.once('exit', () => {
5698
5762
  clearTimeout(timer);
5699
- resolveWait();
5763
+ resolveWait(true);
5700
5764
  });
5701
5765
  });
5766
+ if (exited)
5767
+ return;
5768
+ handle.child.kill('SIGKILL');
5769
+ writeLine(io.stderr, `test-gates: the spawned witness did not exit within ${String(Math.round(WITNESS_STOP_GRACE_MS / 1000))}s of SIGTERM — ` +
5770
+ 'SIGKILL sent before it appended its manifest envelope, so this run has no durable attestation');
5702
5771
  }
5703
5772
  /**
5704
5773
  * Binds the trusted run context on a wired witness (plan §11.4):
@@ -5996,8 +6065,9 @@ async function fetchWitnessAttestation(io, witnessUrl, runToken, verifierKey, ex
5996
6065
  }
5997
6066
  return attestation;
5998
6067
  }
5999
- catch {
6000
- writeLine(io.stderr, 'test-gates: live attestation unavailable (transport)');
6068
+ catch (error) {
6069
+ const label = error instanceof SyntaxError ? 'parse' : 'transport';
6070
+ writeLine(io.stderr, `test-gates: live attestation unavailable (${label})`);
6001
6071
  return null;
6002
6072
  }
6003
6073
  finally {