@ornexus/neocortex 4.61.4 → 4.61.6

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 (254) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +1 -108
  7. package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
  8. package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
  9. package/packages/client/dist/adapters/codex-adapter.js +2 -80
  10. package/packages/client/dist/adapters/cursor-adapter.js +4 -115
  11. package/packages/client/dist/adapters/gemini-adapter.js +2 -71
  12. package/packages/client/dist/adapters/grok-adapter.js +2 -42
  13. package/packages/client/dist/adapters/index.js +1 -22
  14. package/packages/client/dist/adapters/platform-detector.js +1 -220
  15. package/packages/client/dist/adapters/target-adapter.js +0 -12
  16. package/packages/client/dist/adapters/vscode-adapter.js +2 -72
  17. package/packages/client/dist/agent/refresh-stubs.js +2 -443
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.js +1 -260
  20. package/packages/client/dist/cache/crypto-utils.js +1 -78
  21. package/packages/client/dist/cache/encrypted-cache.js +1 -338
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  23. package/packages/client/dist/cache/index.js +1 -13
  24. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  26. package/packages/client/dist/checkpoint/index.js +1 -11
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  28. package/packages/client/dist/cli.js +5 -364
  29. package/packages/client/dist/commands/activate.js +8 -394
  30. package/packages/client/dist/commands/architecture-answers.js +7 -274
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  33. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  34. package/packages/client/dist/commands/cache-status.js +2 -112
  35. package/packages/client/dist/commands/config.js +1 -88
  36. package/packages/client/dist/commands/doctor.js +2 -635
  37. package/packages/client/dist/commands/invoke.js +148 -7822
  38. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  39. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  40. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  41. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  42. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  43. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  44. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  45. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  46. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  47. package/packages/client/dist/commands/mutation-qa.js +1 -220
  48. package/packages/client/dist/commands/native-agent.js +2 -136
  49. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  50. package/packages/client/dist/commands/planning-generation.js +1 -53
  51. package/packages/client/dist/commands/planning-memory.js +1 -40
  52. package/packages/client/dist/commands/planning-research.js +1 -42
  53. package/packages/client/dist/commands/private-session.js +1 -75
  54. package/packages/client/dist/commands/property-qa.js +1 -139
  55. package/packages/client/dist/commands/qa-control.js +1 -16
  56. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  57. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  58. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  59. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  60. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  61. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  62. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  63. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  64. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  65. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  66. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  67. package/packages/client/dist/commands/refactor-commit.js +13 -399
  68. package/packages/client/dist/commands/refactor-control.js +3 -142
  69. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  70. package/packages/client/dist/commands/refactor-review.js +5 -283
  71. package/packages/client/dist/commands/refactor-root.js +7 -588
  72. package/packages/client/dist/commands/refresh-memory.js +3 -174
  73. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  74. package/packages/client/dist/commands/story-checkpoint.d.ts +5 -1
  75. package/packages/client/dist/commands/story-checkpoint.js +1 -203
  76. package/packages/client/dist/commands/story-worktree.js +5 -258
  77. package/packages/client/dist/config/host-auth-broker.js +1 -60
  78. package/packages/client/dist/config/host-auth-reference.js +1 -93
  79. package/packages/client/dist/config/profile-directory.js +1 -13
  80. package/packages/client/dist/config/resolver-selection.js +1 -278
  81. package/packages/client/dist/config/secure-config.js +12 -281
  82. package/packages/client/dist/config.js +2 -224
  83. package/packages/client/dist/constants.js +1 -25
  84. package/packages/client/dist/context/context-collector.js +2 -222
  85. package/packages/client/dist/context/context-sanitizer.js +1 -145
  86. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  87. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  88. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  89. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  90. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  91. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  92. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  93. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  94. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  95. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  96. package/packages/client/dist/continuity/native-agent-types.js +1 -105
  97. package/packages/client/dist/continuity/outbox.js +1 -117
  98. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  99. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  100. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  101. package/packages/client/dist/errors/error-messages.js +2 -258
  102. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  103. package/packages/client/dist/evidence/collector.js +1 -347
  104. package/packages/client/dist/evidence/index.js +1 -1
  105. package/packages/client/dist/evidence/types.js +0 -2
  106. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  107. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  108. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  109. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  110. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +70 -0
  111. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1592
  112. package/packages/client/dist/git/epic-operational-state.js +2 -672
  113. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  114. package/packages/client/dist/git/git-lifecycle-store.d.ts +22 -0
  115. package/packages/client/dist/git/git-lifecycle-store.js +8 -2500
  116. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  117. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  118. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  119. package/packages/client/dist/git/neocortex-trailers.js +2 -53
  120. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  121. package/packages/client/dist/git/story-worktree-cleanup.js +4 -1058
  122. package/packages/client/dist/git/story-worktree-integration.d.ts +62 -0
  123. package/packages/client/dist/git/story-worktree-integration.js +3 -603
  124. package/packages/client/dist/git/story-worktree-manager.js +3 -843
  125. package/packages/client/dist/git/story-worktree-paths.js +1 -150
  126. package/packages/client/dist/git/story-write-set-extension.d.ts +44 -0
  127. package/packages/client/dist/git/story-write-set-extension.js +1 -0
  128. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  129. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  130. package/packages/client/dist/i18n/first-run.js +2 -60
  131. package/packages/client/dist/index.js +1 -50
  132. package/packages/client/dist/invocation/invoke-input.js +1 -24
  133. package/packages/client/dist/license/host-auth-recovery.js +1 -401
  134. package/packages/client/dist/license/index.js +1 -5
  135. package/packages/client/dist/license/license-client.js +1 -337
  136. package/packages/client/dist/machine/fingerprint.js +2 -163
  137. package/packages/client/dist/machine/index.js +1 -5
  138. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  139. package/packages/client/dist/memory/project-memory-writer.js +41 -1117
  140. package/packages/client/dist/memory/shared-project-memory-types.js +2 -259
  141. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  142. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  143. package/packages/client/dist/migrations/project-identity.js +7 -493
  144. package/packages/client/dist/migrations/state-json.js +4 -393
  145. package/packages/client/dist/policy/architecture-policy.js +2 -184
  146. package/packages/client/dist/policy/index.js +1 -7
  147. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  148. package/packages/client/dist/policy/subagent-approval-policy.js +1 -57
  149. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  150. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  151. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  152. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  153. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  154. package/packages/client/dist/private-execution/delivery.js +13 -410
  155. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  156. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  157. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  158. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  159. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  160. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  161. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  162. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  163. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  164. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  165. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  166. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  167. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  168. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  169. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  170. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  171. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  172. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  173. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  174. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  175. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  176. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  177. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  178. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  179. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  180. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  181. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  182. package/packages/client/dist/private-execution/session-lease.js +1 -63
  183. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  184. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  185. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  186. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  187. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  188. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  189. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  190. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  191. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  192. package/packages/client/dist/resilience/index.js +1 -8
  193. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  194. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  195. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  196. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  197. package/packages/client/dist/runner/binary.js +1 -404
  198. package/packages/client/dist/runner/cli.js +17 -1571
  199. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -124
  200. package/packages/client/dist/runner/headless/adapters.js +1 -49
  201. package/packages/client/dist/runner/headless/background-root.js +1 -85
  202. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  203. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1776
  204. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  205. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -111
  206. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1464
  207. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -357
  208. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  209. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -274
  210. package/packages/client/dist/runner/headless/managed-profile.js +1 -149
  211. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  212. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  213. package/packages/client/dist/runner/headless/resolver.js +1 -231
  214. package/packages/client/dist/runner/headless/run-yolo.js +1 -886
  215. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2657
  216. package/packages/client/dist/runner/headless/types.js +2 -575
  217. package/packages/client/dist/runner/host-capacity.js +1 -59
  218. package/packages/client/dist/runner/local-console.js +13 -396
  219. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  220. package/packages/client/dist/runner/project-identity.js +1 -106
  221. package/packages/client/dist/runner/scheduler.js +7 -995
  222. package/packages/client/dist/runner-cli.js +2 -18
  223. package/packages/client/dist/state/invocation-shape.js +1 -13
  224. package/packages/client/dist/state/project-state-snapshot.js +1 -1754
  225. package/packages/client/dist/state/state-json-repair.js +3 -785
  226. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  227. package/packages/client/dist/telemetry/index.js +1 -5
  228. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  229. package/packages/client/dist/tier/index.js +1 -5
  230. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  231. package/packages/client/dist/types/index.js +1 -38
  232. package/packages/client/dist/version.js +1 -27
  233. package/packages/client/dist/yolo/change-evidence-collector.d.ts +10 -0
  234. package/packages/client/dist/yolo/change-evidence-collector.js +1 -245
  235. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -65
  236. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  237. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  238. package/packages/client/dist/yoloop/index.js +1 -8
  239. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  240. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  241. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  242. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  243. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  244. package/targets-stubs/antigravity/gemini.md +1 -1
  245. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  246. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  247. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  248. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  249. package/targets-stubs/claude-code/neocortex.md +2 -2
  250. package/targets-stubs/codex/AGENTS.md +1 -1
  251. package/targets-stubs/cursor/agent.md +2 -2
  252. package/targets-stubs/gemini-cli/agent.md +2 -2
  253. package/targets-stubs/opencode/neocortex-root.md +1 -1
  254. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,669 +1,11 @@
1
- /** Opt-in, root-owned physical browser capture. This produces observations,
2
- * never a QA verdict or a story checkpoint. */
3
- import { createHash, randomUUID } from 'node:crypto';
4
- import { closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync, readSync, realpathSync, writeFileSync } from 'node:fs';
5
- import { join, resolve } from 'node:path';
6
- import axe from 'axe-core';
7
- import { planRootQaScan, rootQaScanEvidenceDirectory } from './qa-scan-review.js';
8
- import { routeRootQaScanRequest } from './qa-scan-browser-route.js';
9
- import { launchRootQaBrowser } from './qa-scan-browser-launch.js';
10
- const MAX_ARTIFACT_BYTES = 8 * 1024 * 1024;
11
- const LOAD_BUDGET_MS = 10_000;
12
- const SAFE_ACTION = /^[a-z][a-z0-9-]{0,50}$/;
13
- const SCENARIO_RATIONALE = 'Root executed the bounded SDD-linked synthetic UI scenario and checked local DOM results with all action-time network denied.';
14
- function exactScenarioObject(value, keys) {
15
- return !!value && typeof value === 'object' && !Array.isArray(value)
16
- && Object.keys(value).sort().join(',') === [...keys].sort().join(',');
17
- }
18
- const scenarioText = (value, maximum) => typeof value === 'string'
19
- && value.length <= maximum && !/[\x00-\x1f\x7f]/.test(value);
20
- /** Closed declarative plan. Selectors and values are data, never executable code. */
21
- function readScenario(value) {
22
- if (!exactScenarioObject(value, ['id', 'requirementSource', 'requirementIds', 'actions', 'checks'])
23
- || typeof value.id !== 'string' || !SAFE_ACTION.test(value.id)
24
- || typeof value.requirementSource !== 'string' || value.requirementSource.length > 256
25
- || !/^docs\/[A-Za-z0-9_./-]+\.md$/.test(value.requirementSource)
26
- || value.requirementSource.split('/').some(part => !part || part === '.' || part === '..')
27
- || !Array.isArray(value.requirementIds) || value.requirementIds.length < 1 || value.requirementIds.length > 32
28
- || value.requirementIds.some(id => typeof id !== 'string' || !/^[A-Z][A-Z0-9-]{1,63}$/.test(id))
29
- || new Set(value.requirementIds).size !== value.requirementIds.length
30
- || !Array.isArray(value.actions) || value.actions.length < 1 || value.actions.length > 32
31
- || !Array.isArray(value.checks) || value.checks.length < 1 || value.checks.length > 32
32
- || Buffer.byteLength(JSON.stringify(value)) > 16384)
33
- throw new Error('qa-scan-review-scenario-invalid');
34
- for (const item of value.actions) {
35
- const fields = item?.kind === 'click' ? ['kind', 'selector'] : item?.kind === 'press'
36
- ? ['kind', 'selector', 'key'] : ['kind', 'selector', 'value'];
37
- if (!exactScenarioObject(item, fields) || !scenarioText(item.selector, 256) || !item.selector
38
- || !['click', 'fill', 'select', 'press'].includes(String(item.kind))
39
- || ['fill', 'select'].includes(String(item.kind)) && !scenarioText(item.value, 512)
40
- || item.kind === 'press' && (typeof item.key !== 'string'
41
- || !['Tab', 'Enter', 'Space', 'Escape', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(item.key))) {
42
- throw new Error('qa-scan-review-scenario-invalid');
43
- }
44
- }
45
- const ids = new Set();
46
- for (const item of value.checks) {
47
- if (!exactScenarioObject(item, ['id', 'selector', 'kind', 'expected'])
48
- || typeof item.id !== 'string' || !SAFE_ACTION.test(item.id) || ids.has(item.id)
49
- || !scenarioText(item.selector, 256) || !item.selector
50
- || !['text', 'value', 'visible', 'enabled', 'checked'].includes(String(item.kind))
51
- || (item.kind === 'text' || item.kind === 'value' ? !scenarioText(item.expected, 512) : typeof item.expected !== 'boolean')) {
52
- throw new Error('qa-scan-review-scenario-invalid');
53
- }
54
- ids.add(item.id);
55
- }
56
- // Freeze a detached plan so a trusted caller cannot mutate it while the browser waits.
57
- const copy = structuredClone(value);
58
- return Object.freeze({ ...copy, requirementIds: Object.freeze([...copy.requirementIds]),
59
- actions: Object.freeze(copy.actions.map(action => Object.freeze(action))),
60
- checks: Object.freeze(copy.checks.map(check => Object.freeze(check))) });
61
- }
62
- export function validateRootQaScanScenario(value) {
63
- try {
64
- return readScenario(value);
65
- }
66
- catch {
67
- throw new Error('qa-scan-review-scenario-invalid');
68
- }
69
- }
70
- function sha(bytes) {
71
- return createHash('sha256').update(bytes).digest('hex');
72
- }
73
- function boundedJson(value) {
74
- return Buffer.from(`${JSON.stringify(value)}\n`, 'utf8');
75
- }
76
- function observation(kind, captureMethod, suffix, bytes, capturedAt, rationale) {
77
- if (bytes.length < 8 || bytes.length > MAX_ARTIFACT_BYTES) {
78
- throw new Error('qa-scan-review-capture-artifact-invalid');
79
- }
80
- return Object.freeze({ kind, artifactId: `${kind}-${randomUUID()}.${suffix}`,
81
- captureMethod, sha256: sha(bytes), capturedAt, rationale });
82
- }
83
- async function uniqueScenarioLocator(page, selector) {
84
- // Use CSS only; custom selector engines and script evaluation are not admitted.
85
- const locator = page.locator(`css=${selector}`);
86
- if (await locator.count() !== 1)
87
- throw new Error('qa-scan-review-scenario-target-ambiguous');
88
- return locator;
89
- }
90
- export function scenarioRequirementDigest(root, scenario) {
91
- const path = join(root, scenario.requirementSource);
92
- let fd;
93
- try {
94
- if (realpathSync(path) !== path)
95
- throw new Error();
96
- fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
97
- const stat = fstatSync(fd);
98
- if (!stat.isFile() || stat.nlink !== 1 || stat.size < 1 || stat.size > 65536)
99
- throw new Error();
100
- const bytes = Buffer.alloc(65537);
101
- let length = 0;
102
- while (length < bytes.length) {
103
- const count = readSync(fd, bytes, length, bytes.length - length, null);
104
- if (!count)
105
- break;
106
- length += count;
107
- }
108
- if (length !== stat.size || length > 65536)
109
- throw new Error();
110
- const source = new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, length));
111
- if (scenario.requirementIds.some(id => !new RegExp(`(^|[^A-Z0-9-])${id}([^A-Z0-9-]|$)`).test(source)))
112
- throw new Error();
113
- return sha(bytes.subarray(0, length));
114
- }
115
- catch {
116
- throw new Error('qa-scan-review-scenario-requirements-unbound');
117
- }
118
- finally {
119
- if (fd !== undefined)
120
- closeSync(fd);
121
- }
122
- }
123
- /** Private persisted linkage, reopened by root/worker triage after restart. */
124
- export function readRootQaScanScenarioReceipt(projectRoot, surface, targetUrl, scenarioRecordSha256) {
125
- try {
126
- if (!/^[a-f0-9]{64}$/.test(scenarioRecordSha256))
127
- throw new Error();
128
- const root = resolve(projectRoot);
129
- const plan = planRootQaScan(root, surface, targetUrl);
130
- const directory = rootQaScanEvidenceDirectory(root);
131
- const read = (path, limit) => {
132
- const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
133
- try {
134
- const stat = fstatSync(fd);
135
- if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid?.()
136
- || (stat.mode & 0o777) !== 0o600 || stat.size < 1 || stat.size > limit)
137
- throw new Error();
138
- const bytes = Buffer.alloc(limit + 1);
139
- let length = 0;
140
- while (length < bytes.length) {
141
- const count = readSync(fd, bytes, length, bytes.length - length, null);
142
- if (!count)
143
- break;
144
- length += count;
145
- }
146
- const after = lstatSync(path);
147
- if (length !== stat.size || length > limit || after.dev !== stat.dev || after.ino !== stat.ino
148
- || after.ctimeMs !== stat.ctimeMs || after.mtimeMs !== stat.mtimeMs || after.nlink !== 1)
149
- throw new Error();
150
- return bytes.subarray(0, length);
151
- }
152
- finally {
153
- closeSync(fd);
154
- }
155
- };
156
- const raw = read(join(directory, `scenario-${scenarioRecordSha256}.json`), 32768);
157
- if (sha(Buffer.concat([Buffer.from('root-qa-scenario-record-v1\0'), raw])) !== scenarioRecordSha256)
158
- throw new Error();
159
- const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(raw));
160
- if (!exactScenarioObject(value, ['scenario', 'receipt']))
161
- throw new Error();
162
- const scenario = validateRootQaScanScenario(value.scenario);
163
- const receipt = value.receipt;
164
- if (!exactScenarioObject(receipt, ['schemaVersion', 'evidenceContractVersion', 'kind', 'sourceHead',
165
- 'planSha256', 'surface', 'targetSha256', 'observation', 'scenarioSha256', 'requirementSourceSha256',
166
- 'requirementIds', 'qaAccepted', 'checkpointAccepted', 'workflowContinuationAuthorized', 'localOnly', 'publicSafe'])
167
- || receipt.schemaVersion !== 1 || receipt.evidenceContractVersion !== 2 || receipt.kind !== 'root-qa-scan-interaction'
168
- || receipt.sourceHead !== plan.sourceHead || receipt.planSha256 !== plan.planSha256
169
- || receipt.surface !== surface || receipt.targetSha256 !== plan.targetSha256
170
- || receipt.scenarioSha256 !== sha(Buffer.from(JSON.stringify(scenario)))
171
- || receipt.requirementSourceSha256 !== scenarioRequirementDigest(root, scenario)
172
- || JSON.stringify(receipt.requirementIds) !== JSON.stringify(scenario.requirementIds)
173
- || receipt.qaAccepted !== false || receipt.checkpointAccepted !== false || receipt.workflowContinuationAuthorized !== false
174
- || receipt.localOnly !== true || receipt.publicSafe !== true
175
- || !exactScenarioObject(receipt.observation, ['kind', 'artifactId', 'captureMethod', 'sha256', 'capturedAt', 'rationale'])
176
- || receipt.observation.kind !== 'interaction' || receipt.observation.captureMethod !== 'browser-interaction'
177
- || receipt.observation.rationale !== SCENARIO_RATIONALE
178
- || !/^interaction-[a-f0-9-]{36}\.json$/.test(receipt.observation.artifactId))
179
- throw new Error();
180
- const capturedMs = Date.parse(receipt.observation.capturedAt);
181
- if (!Number.isFinite(capturedMs) || new Date(capturedMs).toISOString() !== receipt.observation.capturedAt
182
- || capturedMs > Date.now() + 5 * 60000 || Date.now() - capturedMs > 60 * 60000)
183
- throw new Error();
184
- const artifact = read(join(directory, receipt.observation.artifactId), 16384);
185
- if (sha(artifact) !== receipt.observation.sha256)
186
- throw new Error();
187
- const actual = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(artifact));
188
- const expected = { schemaVersion: 2, syntheticTarget: true, networkAttemptsAfterAction: 0,
189
- checks: scenario.checks.map(check => ({ id: `functional-${check.id}`, passed: true })) };
190
- if (JSON.stringify(actual) !== JSON.stringify(expected)
191
- || planRootQaScan(root, surface, targetUrl).planSha256 !== plan.planSha256)
192
- throw new Error();
193
- return Object.freeze({ ...receipt, scenarioRecordSha256 });
194
- }
195
- catch {
196
- throw new Error('qa-scan-review-scenario-record-unverified');
197
- }
198
- }
199
- /** Generic synthetic UI scenarios. An operator grants the target, not a DOM marker.
200
- * Backend mutations, navigation, downloads and sockets remain denied. */
201
- export async function captureRootQaScanScenario(options) {
202
- if (!options.authorizeScenario || options.dataScope !== 'synthetic-public') {
203
- throw new Error('qa-scan-review-scenario-authorization-required');
204
- }
205
- const scenario = validateRootQaScanScenario(options.scenario);
206
- const scenarioSha256 = sha(Buffer.from(JSON.stringify(scenario)));
207
- const root = resolve(options.projectRoot);
208
- const plan = planRootQaScan(root, options.surface, options.targetUrl);
209
- const requirementSourceSha256 = scenarioRequirementDigest(root, scenario);
210
- const target = new URL(options.targetUrl);
211
- let browser;
212
- try {
213
- browser = await launchRootQaBrowser();
214
- }
215
- catch {
216
- throw new Error('qa-scan-review-browser-unavailable');
217
- }
218
- let budgetTimer;
219
- let budgetExceeded = false;
220
- try {
221
- const context = await browser.newContext({ serviceWorkers: 'block', acceptDownloads: false,
222
- permissions: [], ignoreHTTPSErrors: false, viewport: { width: 1280, height: 900 } });
223
- let started = false;
224
- let denied = 0;
225
- let disruptions = 0;
226
- await context.route('**/*', async (route) => {
227
- let allowed = false;
228
- try {
229
- const request = route.request();
230
- const url = new URL(request.url());
231
- allowed = !started && url.protocol === 'http:' && url.origin === target.origin
232
- && ['GET', 'HEAD'].includes(request.method());
233
- }
234
- catch { /* deny */ }
235
- await routeRootQaScanRequest(route, allowed, () => { denied++; });
236
- });
237
- await context.routeWebSocket(/.*/, async (socket) => { denied++; await socket.close({ code: 1008, reason: 'blocked' }); });
238
- const page = await context.newPage();
239
- context.on('page', opened => { if (opened !== page) {
240
- disruptions++;
241
- void opened.close();
242
- } });
243
- page.on('framenavigated', () => { if (started)
244
- disruptions++; });
245
- page.on('download', () => { disruptions++; });
246
- page.on('pageerror', () => { disruptions++; });
247
- page.on('console', message => { if (message.type() === 'error')
248
- disruptions++; });
249
- const response = await page.goto(target.href, { waitUntil: 'load', timeout: 15000 });
250
- if (!response || response.status() >= 400 || page.url() !== target.href || denied || disruptions) {
251
- throw new Error('qa-scan-review-scenario-target-unavailable');
252
- }
253
- started = true;
254
- budgetTimer = setTimeout(() => { budgetExceeded = true; void context.close().catch(() => undefined); }, 15000);
255
- // One absolute action/check budget; individual calls cannot extend it.
256
- const deadline = performance.now() + 15000;
257
- const remaining = () => {
258
- const value = Math.floor(deadline - performance.now());
259
- if (value < 1)
260
- throw new Error('qa-scan-review-scenario-budget-exhausted');
261
- return Math.min(value, 2000);
262
- };
263
- for (const action of scenario.actions) {
264
- const locator = await uniqueScenarioLocator(page, action.selector);
265
- if (!(await locator.isVisible()) || !(await locator.isEnabled()))
266
- throw new Error('qa-scan-review-scenario-action-unavailable');
267
- const timeout = remaining();
268
- if (action.kind === 'click')
269
- await locator.click({ timeout });
270
- else if (action.kind === 'fill')
271
- await locator.fill(action.value, { timeout });
272
- else if (action.kind === 'select')
273
- await locator.selectOption(action.value, { timeout });
274
- else if (action.kind === 'press')
275
- await locator.press(action.key, { timeout });
276
- if (denied || disruptions || page.url() !== target.href)
277
- throw new Error('qa-scan-review-scenario-effects-denied');
278
- }
279
- const checks = [];
280
- for (const check of scenario.checks) {
281
- const locator = await uniqueScenarioLocator(page, check.selector);
282
- const timeout = remaining();
283
- const observed = check.kind === 'text' ? (await locator.textContent({ timeout }))?.trim()
284
- : check.kind === 'value' ? await locator.inputValue({ timeout })
285
- : check.kind === 'visible' ? await locator.isVisible()
286
- : check.kind === 'enabled' ? await locator.isEnabled() : await locator.isChecked({ timeout });
287
- if (observed !== check.expected)
288
- throw new Error('qa-scan-review-scenario-check-failed');
289
- checks.push({ id: `functional-${check.id}`, passed: true });
290
- }
291
- await page.waitForTimeout(250);
292
- if (denied || disruptions || page.url() !== target.href)
293
- throw new Error('qa-scan-review-scenario-effects-denied');
294
- if (planRootQaScan(root, options.surface, options.targetUrl).planSha256 !== plan.planSha256) {
295
- throw new Error('qa-scan-review-capture-source-drift');
296
- }
297
- if (scenarioRequirementDigest(root, scenario) !== requirementSourceSha256)
298
- throw new Error('qa-scan-review-capture-source-drift');
299
- const bytes = boundedJson({ schemaVersion: 2, syntheticTarget: true, networkAttemptsAfterAction: 0, checks });
300
- const row = observation('interaction', 'browser-interaction', 'json', bytes, new Date().toISOString(), SCENARIO_RATIONALE);
301
- const directory = rootQaScanEvidenceDirectory(root);
302
- const handle = openSync(join(directory, row.artifactId), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
303
- try {
304
- writeFileSync(handle, bytes);
305
- fsyncSync(handle);
306
- }
307
- finally {
308
- closeSync(handle);
309
- }
310
- const directoryHandle = openSync(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
311
- try {
312
- fsyncSync(directoryHandle);
313
- }
314
- finally {
315
- closeSync(directoryHandle);
316
- }
317
- if (planRootQaScan(root, options.surface, options.targetUrl).planSha256 !== plan.planSha256)
318
- throw new Error('qa-scan-review-capture-source-drift');
319
- const receipt = Object.freeze({ schemaVersion: 1, evidenceContractVersion: 2, kind: 'root-qa-scan-interaction',
320
- sourceHead: plan.sourceHead, planSha256: plan.planSha256, surface: plan.surface, targetSha256: plan.targetSha256,
321
- observation: row, scenarioSha256, requirementSourceSha256, requirementIds: scenario.requirementIds,
322
- qaAccepted: false, checkpointAccepted: false, workflowContinuationAuthorized: false, localOnly: true, publicSafe: true });
323
- const record = Buffer.from(JSON.stringify({ scenario, receipt }));
324
- const scenarioRecordSha256 = sha(Buffer.concat([Buffer.from('root-qa-scenario-record-v1\0'), record]));
325
- const recordHandle = openSync(join(directory, `scenario-${scenarioRecordSha256}.json`), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
326
- try {
327
- writeFileSync(recordHandle, record);
328
- fsyncSync(recordHandle);
329
- }
330
- finally {
331
- closeSync(recordHandle);
332
- }
333
- const parentHandle = openSync(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
334
- try {
335
- fsyncSync(parentHandle);
336
- }
337
- finally {
338
- closeSync(parentHandle);
339
- }
340
- return readRootQaScanScenarioReceipt(root, options.surface, options.targetUrl, scenarioRecordSha256);
341
- }
342
- catch (error) {
343
- if (budgetExceeded)
344
- throw new Error('qa-scan-review-scenario-budget-exhausted');
345
- if (error instanceof Error && /^qa-scan-review-[a-z-]+$/.test(error.message))
346
- throw error;
347
- throw new Error('qa-scan-review-scenario-unavailable');
348
- }
349
- finally {
350
- if (budgetTimer)
351
- clearTimeout(budgetTimer);
352
- await browser.close().catch(() => undefined);
353
- }
354
- }
355
- /** Observe only loopback GET/HEAD loads, including popups. A page-initiated
356
- * mutation request or WebSocket is blocked even at the named origin; a fresh
357
- * browser profile/cookie jar is never borrowed from the user's host. */
358
- export async function captureRootQaScan(options) {
359
- if (!options.authorizeCapture)
360
- throw new Error('qa-scan-review-authorization-or-target-required');
361
- const root = resolve(options.projectRoot);
362
- const plan = planRootQaScan(root, options.surface, options.targetUrl);
363
- const target = new URL(options.targetUrl);
364
- let browser;
365
- try {
366
- browser = await launchRootQaBrowser();
367
- }
368
- catch {
369
- throw new Error('qa-scan-review-browser-unavailable');
370
- }
371
- try {
372
- const context = await browser.newContext({
373
- viewport: { width: 1440, height: 900 },
374
- serviceWorkers: 'block', acceptDownloads: false,
375
- permissions: [], ignoreHTTPSErrors: false,
376
- });
377
- let blockedRequests = 0;
378
- let blockedWebSockets = 0;
379
- await context.route('**/*', async (route) => {
380
- let allowed = false;
381
- try {
382
- const requested = new URL(route.request().url());
383
- allowed = requested.protocol === 'http:' && requested.origin === target.origin
384
- && (route.request().method() === 'GET' || route.request().method() === 'HEAD');
385
- }
386
- catch { /* Opaque or malformed browser requests are denied. */ }
387
- await routeRootQaScanRequest(route, allowed, () => { blockedRequests++; });
388
- });
389
- // HTTP routing does not cover WebSocket handshakes. Even a same-origin
390
- // socket can mutate server state during an allegedly passive scan.
391
- await context.routeWebSocket(/.*/, async (socket) => {
392
- blockedWebSockets++;
393
- await socket.close({ code: 1008, reason: 'blocked' });
394
- });
395
- const page = await context.newPage();
396
- context.on('page', (opened) => { if (opened !== page)
397
- void opened.close(); });
398
- let mainFrameNavigations = 0;
399
- page.on('framenavigated', (frame) => {
400
- if (frame === page.mainFrame() && frame.url() !== 'about:blank')
401
- mainFrameNavigations++;
402
- });
403
- page.setDefaultTimeout(15_000);
404
- let consoleErrors = 0;
405
- let pageErrors = 0;
406
- let failedRequests = 0;
407
- let requestsObserved = 0;
408
- // These listeners precede the first navigation. HTTP 4xx/5xx are failures
409
- // even though Playwright does not emit requestfailed for an HTTP response.
410
- page.on('console', (message) => { if (message.type() === 'error')
411
- consoleErrors++; });
412
- page.on('pageerror', () => { pageErrors++; });
413
- page.on('request', () => { requestsObserved++; });
414
- page.on('requestfailed', () => { failedRequests++; });
415
- page.on('response', (response) => { if (response.status() >= 400)
416
- failedRequests++; });
417
- const response = await page.goto(target.href, { waitUntil: 'load', timeout: 15_000 });
418
- if (!response || response.status() >= 400 || page.url() !== target.href
419
- || mainFrameNavigations !== 1) {
420
- throw new Error('qa-scan-review-capture-target-unavailable');
421
- }
422
- const stableTarget = () => {
423
- if (page.url() !== target.href || mainFrameNavigations !== 1) {
424
- throw new Error('qa-scan-review-capture-target-drift');
425
- }
426
- };
427
- stableTarget();
428
- const visual = await page.screenshot({ type: 'png', animations: 'disabled', timeout: 15_000 });
429
- stableTarget();
430
- await page.addScriptTag({ content: axe.source });
431
- const axeResult = await page.evaluate('window.axe.run(document)');
432
- stableTarget();
433
- if (!axeResult || typeof axeResult !== 'object') {
434
- throw new Error('qa-scan-review-capture-accessibility-unavailable');
435
- }
436
- const checkedAxe = axeResult;
437
- if (!Array.isArray(checkedAxe.violations) || !Array.isArray(checkedAxe.incomplete)
438
- || !Array.isArray(checkedAxe.passes)) {
439
- throw new Error('qa-scan-review-capture-accessibility-unavailable');
440
- }
441
- // A keyboard focus probe is non-activating: it never clicks an arbitrary
442
- // application control or performs a business mutation.
443
- await page.keyboard.press('Tab');
444
- const keyboardFocus = await page.evaluate(`(() => {
1
+ import{createHash as re,randomUUID as ae}from"node:crypto";import{closeSync as I,constants as l,fstatSync as Z,fsyncSync as D,lstatSync as oe,openSync as T,readSync as G,realpathSync as ne,writeFileSync as W}from"node:fs";import{join as z,resolve as B}from"node:path";import ie from"axe-core";import{planRootQaScan as R,rootQaScanEvidenceDirectory as $}from"./qa-scan-review.js";import{routeRootQaScanRequest as J}from"./qa-scan-browser-route.js";import{launchRootQaBrowser as Q}from"./qa-scan-browser-launch.js";const ce=8*1024*1024,se=1e4,M=/^[a-z][a-z0-9-]{0,50}$/,K="Root executed the bounded SDD-linked synthetic UI scenario and checked local DOM results with all action-time network denied.";function V(e,n){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).sort().join(",")===[...n].sort().join(",")}const Y=(e,n)=>typeof e=="string"&&e.length<=n&&!/[\x00-\x1f\x7f]/.test(e);function le(e){if(!V(e,["id","requirementSource","requirementIds","actions","checks"])||typeof e.id!="string"||!M.test(e.id)||typeof e.requirementSource!="string"||e.requirementSource.length>256||!/^docs\/[A-Za-z0-9_./-]+\.md$/.test(e.requirementSource)||e.requirementSource.split("/").some(t=>!t||t==="."||t==="..")||!Array.isArray(e.requirementIds)||e.requirementIds.length<1||e.requirementIds.length>32||e.requirementIds.some(t=>typeof t!="string"||!/^[A-Z][A-Z0-9-]{1,63}$/.test(t))||new Set(e.requirementIds).size!==e.requirementIds.length||!Array.isArray(e.actions)||e.actions.length<1||e.actions.length>32||!Array.isArray(e.checks)||e.checks.length<1||e.checks.length>32||Buffer.byteLength(JSON.stringify(e))>16384)throw new Error("qa-scan-review-scenario-invalid");for(const t of e.actions){const d=t?.kind==="click"?["kind","selector"]:t?.kind==="press"?["kind","selector","key"]:["kind","selector","value"];if(!V(t,d)||!Y(t.selector,256)||!t.selector||!["click","fill","select","press"].includes(String(t.kind))||["fill","select"].includes(String(t.kind))&&!Y(t.value,512)||t.kind==="press"&&(typeof t.key!="string"||!["Tab","Enter","Space","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Home","End"].includes(t.key)))throw new Error("qa-scan-review-scenario-invalid")}const n=new Set;for(const t of e.checks){if(!V(t,["id","selector","kind","expected"])||typeof t.id!="string"||!M.test(t.id)||n.has(t.id)||!Y(t.selector,256)||!t.selector||!["text","value","visible","enabled","checked"].includes(String(t.kind))||(t.kind==="text"||t.kind==="value"?!Y(t.expected,512):typeof t.expected!="boolean"))throw new Error("qa-scan-review-scenario-invalid");n.add(t.id)}const c=structuredClone(e);return Object.freeze({...c,requirementIds:Object.freeze([...c.requirementIds]),actions:Object.freeze(c.actions.map(t=>Object.freeze(t))),checks:Object.freeze(c.checks.map(t=>Object.freeze(t)))})}function ee(e){try{return le(e)}catch{throw new Error("qa-scan-review-scenario-invalid")}}function N(e){return re("sha256").update(e).digest("hex")}function H(e){return Buffer.from(`${JSON.stringify(e)}
2
+ `,"utf8")}function P(e,n,c,t,d,i){if(t.length<8||t.length>ce)throw new Error("qa-scan-review-capture-artifact-invalid");return Object.freeze({kind:e,artifactId:`${e}-${ae()}.${c}`,captureMethod:n,sha256:N(t),capturedAt:d,rationale:i})}async function te(e,n){const c=e.locator(`css=${n}`);if(await c.count()!==1)throw new Error("qa-scan-review-scenario-target-ambiguous");return c}function X(e,n){const c=z(e,n.requirementSource);let t;try{if(ne(c)!==c)throw new Error;t=T(c,l.O_RDONLY|l.O_NOFOLLOW);const d=Z(t);if(!d.isFile()||d.nlink!==1||d.size<1||d.size>65536)throw new Error;const i=Buffer.alloc(65537);let u=0;for(;u<i.length;){const a=G(t,i,u,i.length-u,null);if(!a)break;u+=a}if(u!==d.size||u>65536)throw new Error;const S=new TextDecoder("utf-8",{fatal:!0}).decode(i.subarray(0,u));if(n.requirementIds.some(a=>!new RegExp(`(^|[^A-Z0-9-])${a}([^A-Z0-9-]|$)`).test(S)))throw new Error;return N(i.subarray(0,u))}catch{throw new Error("qa-scan-review-scenario-requirements-unbound")}finally{t!==void 0&&I(t)}}function de(e,n,c,t){try{if(!/^[a-f0-9]{64}$/.test(t))throw new Error;const d=B(e),i=R(d,n,c),u=$(d),S=(x,q)=>{const k=T(x,l.O_RDONLY|l.O_NOFOLLOW);try{const p=Z(k);if(!p.isFile()||p.nlink!==1||p.uid!==process.getuid?.()||(p.mode&511)!==384||p.size<1||p.size>q)throw new Error;const E=Buffer.alloc(q+1);let g=0;for(;g<E.length;){const v=G(k,E,g,E.length-g,null);if(!v)break;g+=v}const A=oe(x);if(g!==p.size||g>q||A.dev!==p.dev||A.ino!==p.ino||A.ctimeMs!==p.ctimeMs||A.mtimeMs!==p.mtimeMs||A.nlink!==1)throw new Error;return E.subarray(0,g)}finally{I(k)}},a=S(z(u,`scenario-${t}.json`),32768);if(N(Buffer.concat([Buffer.from("root-qa-scenario-record-v1\0"),a]))!==t)throw new Error;const f=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a));if(!V(f,["scenario","receipt"]))throw new Error;const h=ee(f.scenario),o=f.receipt;if(!V(o,["schemaVersion","evidenceContractVersion","kind","sourceHead","planSha256","surface","targetSha256","observation","scenarioSha256","requirementSourceSha256","requirementIds","qaAccepted","checkpointAccepted","workflowContinuationAuthorized","localOnly","publicSafe"])||o.schemaVersion!==1||o.evidenceContractVersion!==2||o.kind!=="root-qa-scan-interaction"||o.sourceHead!==i.sourceHead||o.planSha256!==i.planSha256||o.surface!==n||o.targetSha256!==i.targetSha256||o.scenarioSha256!==N(Buffer.from(JSON.stringify(h)))||o.requirementSourceSha256!==X(d,h)||JSON.stringify(o.requirementIds)!==JSON.stringify(h.requirementIds)||o.qaAccepted!==!1||o.checkpointAccepted!==!1||o.workflowContinuationAuthorized!==!1||o.localOnly!==!0||o.publicSafe!==!0||!V(o.observation,["kind","artifactId","captureMethod","sha256","capturedAt","rationale"])||o.observation.kind!=="interaction"||o.observation.captureMethod!=="browser-interaction"||o.observation.rationale!==K||!/^interaction-[a-f0-9-]{36}\.json$/.test(o.observation.artifactId))throw new Error;const b=Date.parse(o.observation.capturedAt);if(!Number.isFinite(b)||new Date(b).toISOString()!==o.observation.capturedAt||b>Date.now()+5*6e4||Date.now()-b>60*6e4)throw new Error;const m=S(z(u,o.observation.artifactId),16384);if(N(m)!==o.observation.sha256)throw new Error;const w=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(m)),y={schemaVersion:2,syntheticTarget:!0,networkAttemptsAfterAction:0,checks:h.checks.map(x=>({id:`functional-${x.id}`,passed:!0}))};if(JSON.stringify(w)!==JSON.stringify(y)||R(d,n,c).planSha256!==i.planSha256)throw new Error;return Object.freeze({...o,scenarioRecordSha256:t})}catch{throw new Error("qa-scan-review-scenario-record-unverified")}}async function be(e){if(!e.authorizeScenario||e.dataScope!=="synthetic-public")throw new Error("qa-scan-review-scenario-authorization-required");const n=ee(e.scenario),c=N(Buffer.from(JSON.stringify(n))),t=B(e.projectRoot),d=R(t,e.surface,e.targetUrl),i=X(t,n),u=new URL(e.targetUrl);let S;try{S=await Q()}catch{throw new Error("qa-scan-review-browser-unavailable")}let a,f=!1;try{const h=await S.newContext({serviceWorkers:"block",acceptDownloads:!1,permissions:[],ignoreHTTPSErrors:!1,viewport:{width:1280,height:900}});let o=!1,b=0,m=0;await h.route("**/*",async s=>{let r=!1;try{const O=s.request(),_=new URL(O.url());r=!o&&_.protocol==="http:"&&_.origin===u.origin&&["GET","HEAD"].includes(O.method())}catch{}await J(s,r,()=>{b++})}),await h.routeWebSocket(/.*/,async s=>{b++,await s.close({code:1008,reason:"blocked"})});const w=await h.newPage();h.on("page",s=>{s!==w&&(m++,s.close())}),w.on("framenavigated",()=>{o&&m++}),w.on("download",()=>{m++}),w.on("pageerror",()=>{m++}),w.on("console",s=>{s.type()==="error"&&m++});const y=await w.goto(u.href,{waitUntil:"load",timeout:15e3});if(!y||y.status()>=400||w.url()!==u.href||b||m)throw new Error("qa-scan-review-scenario-target-unavailable");o=!0,a=setTimeout(()=>{f=!0,h.close().catch(()=>{})},15e3);const x=performance.now()+15e3,q=()=>{const s=Math.floor(x-performance.now());if(s<1)throw new Error("qa-scan-review-scenario-budget-exhausted");return Math.min(s,2e3)};for(const s of n.actions){const r=await te(w,s.selector);if(!await r.isVisible()||!await r.isEnabled())throw new Error("qa-scan-review-scenario-action-unavailable");const O=q();if(s.kind==="click"?await r.click({timeout:O}):s.kind==="fill"?await r.fill(s.value,{timeout:O}):s.kind==="select"?await r.selectOption(s.value,{timeout:O}):s.kind==="press"&&await r.press(s.key,{timeout:O}),b||m||w.url()!==u.href)throw new Error("qa-scan-review-scenario-effects-denied")}const k=[];for(const s of n.checks){const r=await te(w,s.selector),O=q();if((s.kind==="text"?(await r.textContent({timeout:O}))?.trim():s.kind==="value"?await r.inputValue({timeout:O}):s.kind==="visible"?await r.isVisible():s.kind==="enabled"?await r.isEnabled():await r.isChecked({timeout:O}))!==s.expected)throw new Error("qa-scan-review-scenario-check-failed");k.push({id:`functional-${s.id}`,passed:!0})}if(await w.waitForTimeout(250),b||m||w.url()!==u.href)throw new Error("qa-scan-review-scenario-effects-denied");if(R(t,e.surface,e.targetUrl).planSha256!==d.planSha256)throw new Error("qa-scan-review-capture-source-drift");if(X(t,n)!==i)throw new Error("qa-scan-review-capture-source-drift");const p=H({schemaVersion:2,syntheticTarget:!0,networkAttemptsAfterAction:0,checks:k}),E=P("interaction","browser-interaction","json",p,new Date().toISOString(),K),g=$(t),A=T(z(g,E.artifactId),l.O_WRONLY|l.O_CREAT|l.O_EXCL|l.O_NOFOLLOW,384);try{W(A,p),D(A)}finally{I(A)}const v=T(g,l.O_RDONLY|l.O_DIRECTORY|l.O_NOFOLLOW);try{D(v)}finally{I(v)}if(R(t,e.surface,e.targetUrl).planSha256!==d.planSha256)throw new Error("qa-scan-review-capture-source-drift");const j=Object.freeze({schemaVersion:1,evidenceContractVersion:2,kind:"root-qa-scan-interaction",sourceHead:d.sourceHead,planSha256:d.planSha256,surface:d.surface,targetSha256:d.targetSha256,observation:E,scenarioSha256:c,requirementSourceSha256:i,requirementIds:n.requirementIds,qaAccepted:!1,checkpointAccepted:!1,workflowContinuationAuthorized:!1,localOnly:!0,publicSafe:!0}),L=Buffer.from(JSON.stringify({scenario:n,receipt:j})),C=N(Buffer.concat([Buffer.from("root-qa-scenario-record-v1\0"),L])),U=T(z(g,`scenario-${C}.json`),l.O_WRONLY|l.O_CREAT|l.O_EXCL|l.O_NOFOLLOW,384);try{W(U,L),D(U)}finally{I(U)}const F=T(g,l.O_RDONLY|l.O_DIRECTORY|l.O_NOFOLLOW);try{D(F)}finally{I(F)}return de(t,e.surface,e.targetUrl,C)}catch(h){throw f?new Error("qa-scan-review-scenario-budget-exhausted"):h instanceof Error&&/^qa-scan-review-[a-z-]+$/.test(h.message)?h:new Error("qa-scan-review-scenario-unavailable")}finally{a&&clearTimeout(a),await S.close().catch(()=>{})}}async function ye(e){if(!e.authorizeCapture)throw new Error("qa-scan-review-authorization-or-target-required");const n=B(e.projectRoot),c=R(n,e.surface,e.targetUrl),t=new URL(e.targetUrl);let d;try{d=await Q()}catch{throw new Error("qa-scan-review-browser-unavailable")}try{const i=await d.newContext({viewport:{width:1440,height:900},serviceWorkers:"block",acceptDownloads:!1,permissions:[],ignoreHTTPSErrors:!1});let u=0,S=0;await i.route("**/*",async r=>{let O=!1;try{const _=new URL(r.request().url());O=_.protocol==="http:"&&_.origin===t.origin&&(r.request().method()==="GET"||r.request().method()==="HEAD")}catch{}await J(r,O,()=>{u++})}),await i.routeWebSocket(/.*/,async r=>{S++,await r.close({code:1008,reason:"blocked"})});const a=await i.newPage();i.on("page",r=>{r!==a&&r.close()});let f=0;a.on("framenavigated",r=>{r===a.mainFrame()&&r.url()!=="about:blank"&&f++}),a.setDefaultTimeout(15e3);let h=0,o=0,b=0,m=0;a.on("console",r=>{r.type()==="error"&&h++}),a.on("pageerror",()=>{o++}),a.on("request",()=>{m++}),a.on("requestfailed",()=>{b++}),a.on("response",r=>{r.status()>=400&&b++});const w=await a.goto(t.href,{waitUntil:"load",timeout:15e3});if(!w||w.status()>=400||a.url()!==t.href||f!==1)throw new Error("qa-scan-review-capture-target-unavailable");const y=()=>{if(a.url()!==t.href||f!==1)throw new Error("qa-scan-review-capture-target-drift")};y();const x=await a.screenshot({type:"png",animations:"disabled",timeout:15e3});y(),await a.addScriptTag({content:ie.source});const q=await a.evaluate("window.axe.run(document)");if(y(),!q||typeof q!="object")throw new Error("qa-scan-review-capture-accessibility-unavailable");const k=q;if(!Array.isArray(k.violations)||!Array.isArray(k.incomplete)||!Array.isArray(k.passes))throw new Error("qa-scan-review-capture-accessibility-unavailable");await a.keyboard.press("Tab");const p=await a.evaluate(`(() => {
445
3
  const active = document.activeElement;
446
4
  return !!active && active !== document.body && active !== document.documentElement
447
5
  && active.matches(':focus-visible');
448
- })()`);
449
- const navigationDuration = await page.evaluate(`(() => {
6
+ })()`),E=await a.evaluate(`(() => {
450
7
  const entry = performance.getEntriesByType('navigation')[0];
451
8
  return entry ? entry.duration : null;
452
- })()`);
453
- stableTarget();
454
- await page.setViewportSize({ width: 375, height: 812 });
455
- const responsive = await page.screenshot({ type: 'png', animations: 'disabled', timeout: 15_000 });
456
- stableTarget();
457
- await page.setViewportSize({ width: 768, height: 1024 });
458
- const responsiveTablet = await page.screenshot({ type: 'png', animations: 'disabled', timeout: 15_000 });
459
- stableTarget();
460
- await page.setViewportSize({ width: 1024, height: 768 });
461
- const responsiveDesktop = await page.screenshot({ type: 'png', animations: 'disabled', timeout: 15_000 });
462
- stableTarget();
463
- const observedMs = typeof navigationDuration === 'number' && Number.isFinite(navigationDuration)
464
- ? Math.max(0, Math.round(navigationDuration)) : null;
465
- const capturedAt = new Date().toISOString();
466
- const rows = [
467
- { kind: 'visual', method: 'browser-screenshot', suffix: 'png',
468
- bytes: Buffer.from(visual), rationale: 'Chrome headless desktop viewport 1440x900 at the exact local target before QA review.' },
469
- { kind: 'responsive', method: 'browser-screenshot', suffix: 'png',
470
- bytes: Buffer.from(responsive), rationale: 'Chrome headless mobile-width viewport 375x812 at the same local target.' },
471
- { kind: 'responsive-tablet', method: 'browser-screenshot', suffix: 'png',
472
- bytes: Buffer.from(responsiveTablet), rationale: 'Chrome headless tablet-width viewport 768x1024 at the same local target.' },
473
- { kind: 'responsive-desktop', method: 'browser-screenshot', suffix: 'png',
474
- bytes: Buffer.from(responsiveDesktop), rationale: 'Chrome headless compact-desktop viewport 1024x768 at the same local target.' },
475
- { kind: 'accessibility', method: 'axe-scan', suffix: 'json',
476
- bytes: boundedJson({ schemaVersion: 1, engine: 'axe-core',
477
- violationCount: checkedAxe.violations.length, incompleteCount: checkedAxe.incomplete.length,
478
- passCount: checkedAxe.passes.length }),
479
- rationale: 'Axe-core ran against the rendered local document; counts preserve incomplete and violated rules.' },
480
- { kind: 'interaction', method: 'browser-interaction', suffix: 'json',
481
- bytes: boundedJson({ schemaVersion: 1, checks: [{ id: 'keyboard-focus', passed: keyboardFocus === true }] }),
482
- rationale: 'Non-activating Tab key probe observed a visible focus target without clicking application controls.' },
483
- { kind: 'console-network', method: 'console-capture', suffix: 'json',
484
- bytes: boundedJson({ schemaVersion: 1, initialCapture: true, consoleErrors, pageErrors,
485
- failedRequests: failedRequests + blockedRequests + blockedWebSockets, requestsObserved }),
486
- rationale: 'Console, page-error, HTTP and WebSocket routing listeners were installed before navigation.' },
487
- { kind: 'performance', method: 'performance-trace', suffix: 'json',
488
- bytes: boundedJson({ schemaVersion: 1, metric: 'load', observedMs, budgetMs: LOAD_BUDGET_MS }),
489
- rationale: 'Browser Navigation Timing load duration was compared with the fixed 10000 ms local budget.' },
490
- ];
491
- const observations = rows.map((row) => observation(row.kind, row.method, row.suffix, row.bytes, capturedAt, row.rationale));
492
- stableTarget();
493
- if (planRootQaScan(root, options.surface, options.targetUrl).planSha256 !== plan.planSha256) {
494
- throw new Error('qa-scan-review-capture-source-drift');
495
- }
496
- const directory = rootQaScanEvidenceDirectory(root);
497
- for (let index = 0; index < rows.length; index++) {
498
- const path = join(directory, observations[index].artifactId);
499
- const handle = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL
500
- | (constants.O_NOFOLLOW ?? 0), 0o600);
501
- try {
502
- writeFileSync(handle, rows[index].bytes);
503
- fsyncSync(handle);
504
- }
505
- finally {
506
- closeSync(handle);
507
- }
508
- }
509
- const directoryHandle = openSync(directory, constants.O_RDONLY | (constants.O_DIRECTORY ?? 0));
510
- try {
511
- fsyncSync(directoryHandle);
512
- }
513
- finally {
514
- closeSync(directoryHandle);
515
- }
516
- stableTarget();
517
- if (planRootQaScan(root, options.surface, options.targetUrl).planSha256 !== plan.planSha256) {
518
- throw new Error('qa-scan-review-capture-source-drift');
519
- }
520
- return Object.freeze({ schemaVersion: 1, evidenceContractVersion: 2,
521
- kind: 'root-qa-scan-capture',
522
- sourceHead: plan.sourceHead, planSha256: plan.planSha256,
523
- surface: plan.surface, targetSha256: plan.targetSha256,
524
- evidenceCount: 8, observations: Object.freeze(observations),
525
- qaAccepted: false, checkpointAccepted: false,
526
- workflowContinuationAuthorized: false, localOnly: true, publicSafe: true });
527
- }
528
- catch (error) {
529
- if (error instanceof Error && error.message.startsWith('qa-scan-review-'))
530
- throw error;
531
- throw new Error('qa-scan-review-capture-unavailable');
532
- }
533
- finally {
534
- await browser.close().catch(() => undefined);
535
- }
536
- }
537
- /** Explicit synthetic-only local-state interaction. The click runs with every
538
- * subsequent browser network request denied, so it cannot authorize an
539
- * arbitrary live-app workflow or a server-side business mutation. */
540
- export async function captureRootQaScanInteraction(options) {
541
- if (!options.authorizeInteraction || !SAFE_ACTION.test(options.actionId)
542
- || !SAFE_ACTION.test(options.expectedStatus)) {
543
- throw new Error('qa-scan-review-interaction-authorization-required');
544
- }
545
- const root = resolve(options.projectRoot);
546
- const plan = planRootQaScan(root, options.surface, options.targetUrl);
547
- const target = new URL(options.targetUrl);
548
- let browser;
549
- try {
550
- browser = await launchRootQaBrowser();
551
- }
552
- catch {
553
- throw new Error('qa-scan-review-browser-unavailable');
554
- }
555
- try {
556
- const context = await browser.newContext({ viewport: { width: 1280, height: 800 },
557
- serviceWorkers: 'block', acceptDownloads: false, permissions: [],
558
- ignoreHTTPSErrors: false });
559
- let actionStarted = false;
560
- let networkAttempts = 0;
561
- let initialBlocked = 0;
562
- await context.route('**/*', async (route) => {
563
- let allowed = false;
564
- try {
565
- const request = route.request();
566
- const requested = new URL(request.url());
567
- allowed = !actionStarted && requested.protocol === 'http:'
568
- && requested.origin === target.origin
569
- && (request.method() === 'GET' || request.method() === 'HEAD');
570
- }
571
- catch { /* Unparseable requests are denied. */ }
572
- await routeRootQaScanRequest(route, allowed, () => {
573
- if (actionStarted)
574
- networkAttempts++;
575
- else
576
- initialBlocked++;
577
- });
578
- });
579
- await context.routeWebSocket(/.*/, async (socket) => {
580
- if (actionStarted)
581
- networkAttempts++;
582
- else
583
- initialBlocked++;
584
- await socket.close({ code: 1008, reason: 'blocked' });
585
- });
586
- const page = await context.newPage();
587
- let popups = 0;
588
- let navigationsAfterAction = 0;
589
- let downloadsAfterAction = 0;
590
- context.on('page', (opened) => { if (opened !== page) {
591
- popups++;
592
- void opened.close();
593
- } });
594
- page.on('framenavigated', () => { if (actionStarted)
595
- navigationsAfterAction++; });
596
- page.on('download', () => { if (actionStarted)
597
- downloadsAfterAction++; });
598
- let pageErrors = 0;
599
- let consoleErrors = 0;
600
- page.on('pageerror', () => { pageErrors++; });
601
- page.on('console', (message) => { if (message.type() === 'error')
602
- consoleErrors++; });
603
- const response = await page.goto(target.href, { waitUntil: 'load', timeout: 15_000 });
604
- if (!response || response.status() >= 400 || page.url() !== target.href
605
- || initialBlocked !== 0 || pageErrors !== 0 || consoleErrors !== 0) {
606
- throw new Error('qa-scan-review-interaction-target-unavailable');
607
- }
608
- const action = page.locator(`button[type="button"][data-neocortex-qa-safe="true"][data-neocortex-qa-action="${options.actionId}"]`);
609
- const status = page.locator(`[data-neocortex-qa-status="${options.actionId}"]`);
610
- if (await page.locator('body[data-neocortex-qa-synthetic="1"]').count() !== 1
611
- || await action.count() !== 1 || await status.count() !== 1
612
- || !(await action.isVisible()) || !(await status.isVisible())
613
- || (await status.textContent())?.trim() === options.expectedStatus) {
614
- throw new Error('qa-scan-review-interaction-contract-unavailable');
615
- }
616
- actionStarted = true;
617
- await action.click({ timeout: 5_000 });
618
- await page.waitForFunction(`({ actionId, expectedStatus }) =>
9
+ })()`);y(),await a.setViewportSize({width:375,height:812});const g=await a.screenshot({type:"png",animations:"disabled",timeout:15e3});y(),await a.setViewportSize({width:768,height:1024});const A=await a.screenshot({type:"png",animations:"disabled",timeout:15e3});y(),await a.setViewportSize({width:1024,height:768});const v=await a.screenshot({type:"png",animations:"disabled",timeout:15e3});y();const j=typeof E=="number"&&Number.isFinite(E)?Math.max(0,Math.round(E)):null,L=new Date().toISOString(),C=[{kind:"visual",method:"browser-screenshot",suffix:"png",bytes:Buffer.from(x),rationale:"Chrome headless desktop viewport 1440x900 at the exact local target before QA review."},{kind:"responsive",method:"browser-screenshot",suffix:"png",bytes:Buffer.from(g),rationale:"Chrome headless mobile-width viewport 375x812 at the same local target."},{kind:"responsive-tablet",method:"browser-screenshot",suffix:"png",bytes:Buffer.from(A),rationale:"Chrome headless tablet-width viewport 768x1024 at the same local target."},{kind:"responsive-desktop",method:"browser-screenshot",suffix:"png",bytes:Buffer.from(v),rationale:"Chrome headless compact-desktop viewport 1024x768 at the same local target."},{kind:"accessibility",method:"axe-scan",suffix:"json",bytes:H({schemaVersion:1,engine:"axe-core",violationCount:k.violations.length,incompleteCount:k.incomplete.length,passCount:k.passes.length}),rationale:"Axe-core ran against the rendered local document; counts preserve incomplete and violated rules."},{kind:"interaction",method:"browser-interaction",suffix:"json",bytes:H({schemaVersion:1,checks:[{id:"keyboard-focus",passed:p===!0}]}),rationale:"Non-activating Tab key probe observed a visible focus target without clicking application controls."},{kind:"console-network",method:"console-capture",suffix:"json",bytes:H({schemaVersion:1,initialCapture:!0,consoleErrors:h,pageErrors:o,failedRequests:b+u+S,requestsObserved:m}),rationale:"Console, page-error, HTTP and WebSocket routing listeners were installed before navigation."},{kind:"performance",method:"performance-trace",suffix:"json",bytes:H({schemaVersion:1,metric:"load",observedMs:j,budgetMs:se}),rationale:"Browser Navigation Timing load duration was compared with the fixed 10000 ms local budget."}],U=C.map(r=>P(r.kind,r.method,r.suffix,r.bytes,L,r.rationale));if(y(),R(n,e.surface,e.targetUrl).planSha256!==c.planSha256)throw new Error("qa-scan-review-capture-source-drift");const F=$(n);for(let r=0;r<C.length;r++){const O=z(F,U[r].artifactId),_=T(O,l.O_WRONLY|l.O_CREAT|l.O_EXCL|(l.O_NOFOLLOW??0),384);try{W(_,C[r].bytes),D(_)}finally{I(_)}}const s=T(F,l.O_RDONLY|(l.O_DIRECTORY??0));try{D(s)}finally{I(s)}if(y(),R(n,e.surface,e.targetUrl).planSha256!==c.planSha256)throw new Error("qa-scan-review-capture-source-drift");return Object.freeze({schemaVersion:1,evidenceContractVersion:2,kind:"root-qa-scan-capture",sourceHead:c.sourceHead,planSha256:c.planSha256,surface:c.surface,targetSha256:c.targetSha256,evidenceCount:8,observations:Object.freeze(U),qaAccepted:!1,checkpointAccepted:!1,workflowContinuationAuthorized:!1,localOnly:!0,publicSafe:!0})}catch(i){throw i instanceof Error&&i.message.startsWith("qa-scan-review-")?i:new Error("qa-scan-review-capture-unavailable")}finally{await d.close().catch(()=>{})}}async function ve(e){if(!e.authorizeInteraction||!M.test(e.actionId)||!M.test(e.expectedStatus))throw new Error("qa-scan-review-interaction-authorization-required");const n=B(e.projectRoot),c=R(n,e.surface,e.targetUrl),t=new URL(e.targetUrl);let d;try{d=await Q()}catch{throw new Error("qa-scan-review-browser-unavailable")}try{const i=await d.newContext({viewport:{width:1280,height:800},serviceWorkers:"block",acceptDownloads:!1,permissions:[],ignoreHTTPSErrors:!1});let u=!1,S=0,a=0;await i.route("**/*",async v=>{let j=!1;try{const L=v.request(),C=new URL(L.url());j=!u&&C.protocol==="http:"&&C.origin===t.origin&&(L.method()==="GET"||L.method()==="HEAD")}catch{}await J(v,j,()=>{u?S++:a++})}),await i.routeWebSocket(/.*/,async v=>{u?S++:a++,await v.close({code:1008,reason:"blocked"})});const f=await i.newPage();let h=0,o=0,b=0;i.on("page",v=>{v!==f&&(h++,v.close())}),f.on("framenavigated",()=>{u&&o++}),f.on("download",()=>{u&&b++});let m=0,w=0;f.on("pageerror",()=>{m++}),f.on("console",v=>{v.type()==="error"&&w++});const y=await f.goto(t.href,{waitUntil:"load",timeout:15e3});if(!y||y.status()>=400||f.url()!==t.href||a!==0||m!==0||w!==0)throw new Error("qa-scan-review-interaction-target-unavailable");const x=f.locator(`button[type="button"][data-neocortex-qa-safe="true"][data-neocortex-qa-action="${e.actionId}"]`),q=f.locator(`[data-neocortex-qa-status="${e.actionId}"]`);if(await f.locator('body[data-neocortex-qa-synthetic="1"]').count()!==1||await x.count()!==1||await q.count()!==1||!await x.isVisible()||!await q.isVisible()||(await q.textContent())?.trim()===e.expectedStatus)throw new Error("qa-scan-review-interaction-contract-unavailable");if(u=!0,await x.click({timeout:5e3}),await f.waitForFunction(`({ actionId, expectedStatus }) =>
619
10
  document.querySelector('[data-neocortex-qa-status="' + actionId + '"]')
620
- ?.textContent?.trim() === expectedStatus`, { actionId: options.actionId, expectedStatus: options.expectedStatus }, { timeout: 5_000 });
621
- await page.waitForTimeout(250);
622
- if (networkAttempts !== 0 || popups !== 0 || navigationsAfterAction !== 0
623
- || downloadsAfterAction !== 0 || pageErrors !== 0 || consoleErrors !== 0
624
- || page.url() !== target.href) {
625
- throw new Error('qa-scan-review-interaction-effects-denied');
626
- }
627
- const bytes = boundedJson({ schemaVersion: 2, syntheticTarget: true,
628
- networkAttemptsAfterAction: networkAttempts,
629
- checks: [{ id: `functional-${options.actionId}`, passed: true }] });
630
- const row = observation('interaction', 'browser-interaction', 'json', bytes, new Date().toISOString(), 'Root synthetic action changed one visible local status without browser network effects.');
631
- if (planRootQaScan(root, options.surface, options.targetUrl).planSha256 !== plan.planSha256) {
632
- throw new Error('qa-scan-review-capture-source-drift');
633
- }
634
- const directory = rootQaScanEvidenceDirectory(root);
635
- const handle = openSync(join(directory, row.artifactId), constants.O_WRONLY | constants.O_CREAT
636
- | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600);
637
- try {
638
- writeFileSync(handle, bytes);
639
- fsyncSync(handle);
640
- }
641
- finally {
642
- closeSync(handle);
643
- }
644
- const directoryHandle = openSync(directory, constants.O_RDONLY | (constants.O_DIRECTORY ?? 0));
645
- try {
646
- fsyncSync(directoryHandle);
647
- }
648
- finally {
649
- closeSync(directoryHandle);
650
- }
651
- if (planRootQaScan(root, options.surface, options.targetUrl).planSha256 !== plan.planSha256) {
652
- throw new Error('qa-scan-review-capture-source-drift');
653
- }
654
- return Object.freeze({ schemaVersion: 1, evidenceContractVersion: 2,
655
- kind: 'root-qa-scan-interaction',
656
- sourceHead: plan.sourceHead, planSha256: plan.planSha256,
657
- surface: plan.surface, targetSha256: plan.targetSha256,
658
- observation: row, qaAccepted: false, checkpointAccepted: false,
659
- workflowContinuationAuthorized: false, localOnly: true, publicSafe: true });
660
- }
661
- catch (error) {
662
- if (error instanceof Error && error.message.startsWith('qa-scan-review-'))
663
- throw error;
664
- throw new Error('qa-scan-review-interaction-unavailable');
665
- }
666
- finally {
667
- await browser.close().catch(() => undefined);
668
- }
669
- }
11
+ ?.textContent?.trim() === expectedStatus`,{actionId:e.actionId,expectedStatus:e.expectedStatus},{timeout:5e3}),await f.waitForTimeout(250),S!==0||h!==0||o!==0||b!==0||m!==0||w!==0||f.url()!==t.href)throw new Error("qa-scan-review-interaction-effects-denied");const k=H({schemaVersion:2,syntheticTarget:!0,networkAttemptsAfterAction:S,checks:[{id:`functional-${e.actionId}`,passed:!0}]}),p=P("interaction","browser-interaction","json",k,new Date().toISOString(),"Root synthetic action changed one visible local status without browser network effects.");if(R(n,e.surface,e.targetUrl).planSha256!==c.planSha256)throw new Error("qa-scan-review-capture-source-drift");const E=$(n),g=T(z(E,p.artifactId),l.O_WRONLY|l.O_CREAT|l.O_EXCL|(l.O_NOFOLLOW??0),384);try{W(g,k),D(g)}finally{I(g)}const A=T(E,l.O_RDONLY|(l.O_DIRECTORY??0));try{D(A)}finally{I(A)}if(R(n,e.surface,e.targetUrl).planSha256!==c.planSha256)throw new Error("qa-scan-review-capture-source-drift");return Object.freeze({schemaVersion:1,evidenceContractVersion:2,kind:"root-qa-scan-interaction",sourceHead:c.sourceHead,planSha256:c.planSha256,surface:c.surface,targetSha256:c.targetSha256,observation:p,qaAccepted:!1,checkpointAccepted:!1,workflowContinuationAuthorized:!1,localOnly:!0,publicSafe:!0})}catch(i){throw i instanceof Error&&i.message.startsWith("qa-scan-review-")?i:new Error("qa-scan-review-interaction-unavailable")}finally{await d.close().catch(()=>{})}}export{ye as captureRootQaScan,ve as captureRootQaScanInteraction,be as captureRootQaScanScenario,de as readRootQaScanScenarioReceipt,X as scenarioRequirementDigest,ee as validateRootQaScanScenario};