@open-mercato/cli 0.6.6 → 0.6.7-canary.316.1.e6c38e0bef

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 (250) hide show
  1. package/.turbo/turbo-build.log +3 -3
  2. package/AGENTS.md +6 -3
  3. package/build.mjs +15 -0
  4. package/dist/agentic/claude-code/hooks/entity-migration-check.ts +32 -88
  5. package/dist/agentic/codex/enforcement-rules.md +6 -15
  6. package/dist/agentic/cursor/hooks/entity-migration-check.mjs +19 -50
  7. package/dist/agentic/cursor/rules/entity-guard.mdc +9 -21
  8. package/dist/agentic/cursor/rules/generated-guard.mdc +3 -5
  9. package/dist/agentic/cursor/rules/open-mercato.mdc +3 -29
  10. package/dist/agentic/guides/ai-workflows.md +76 -0
  11. package/dist/agentic/guides/architecture.md +107 -0
  12. package/dist/agentic/guides/backend-ui.md +70 -0
  13. package/dist/agentic/guides/contracts.md +92 -0
  14. package/dist/agentic/guides/extensions.md +98 -0
  15. package/dist/agentic/guides/integrations.md +81 -0
  16. package/dist/agentic/guides/module-facts.json +216 -79
  17. package/dist/agentic/guides/module-system.md +12 -127
  18. package/dist/agentic/guides/modules/ai_assistant.md +2 -2
  19. package/dist/agentic/guides/modules/api_docs.md +1 -1
  20. package/dist/agentic/guides/modules/api_keys.md +1 -1
  21. package/dist/agentic/guides/modules/attachments.md +2 -2
  22. package/dist/agentic/guides/modules/audit_logs.md +2 -2
  23. package/dist/agentic/guides/modules/auth.md +1 -1
  24. package/dist/agentic/guides/modules/business_rules.md +1 -1
  25. package/dist/agentic/guides/modules/catalog.md +5 -5
  26. package/dist/agentic/guides/modules/channel_gmail.md +1 -1
  27. package/dist/agentic/guides/modules/channel_imap.md +1 -1
  28. package/dist/agentic/guides/modules/checkout.md +1 -1
  29. package/dist/agentic/guides/modules/communication_channels.md +1 -1
  30. package/dist/agentic/guides/modules/configs.md +1 -1
  31. package/dist/agentic/guides/modules/content.md +1 -1
  32. package/dist/agentic/guides/modules/currencies.md +1 -1
  33. package/dist/agentic/guides/modules/customer_accounts.md +1 -1
  34. package/dist/agentic/guides/modules/customers.md +2 -2
  35. package/dist/agentic/guides/modules/dashboards.md +1 -1
  36. package/dist/agentic/guides/modules/data_sync.md +1 -1
  37. package/dist/agentic/guides/modules/dictionaries.md +1 -1
  38. package/dist/agentic/guides/modules/directory.md +1 -1
  39. package/dist/agentic/guides/modules/entities.md +2 -2
  40. package/dist/agentic/guides/modules/events.md +1 -1
  41. package/dist/agentic/guides/modules/feature_toggles.md +1 -1
  42. package/dist/agentic/guides/modules/gateway_stripe.md +1 -1
  43. package/dist/agentic/guides/modules/generators.md +1 -1
  44. package/dist/agentic/guides/modules/inbox_ops.md +1 -1
  45. package/dist/agentic/guides/modules/integrations.md +1 -1
  46. package/dist/agentic/guides/modules/messages.md +1 -1
  47. package/dist/agentic/guides/modules/notifications.md +1 -1
  48. package/dist/agentic/guides/modules/onboarding.md +1 -1
  49. package/dist/agentic/guides/modules/payment_gateways.md +3 -1
  50. package/dist/agentic/guides/modules/perspectives.md +1 -1
  51. package/dist/agentic/guides/modules/planner.md +1 -1
  52. package/dist/agentic/guides/modules/portal.md +1 -1
  53. package/dist/agentic/guides/modules/progress.md +1 -1
  54. package/dist/agentic/guides/modules/query_index.md +2 -2
  55. package/dist/agentic/guides/modules/record_locks.md +1 -1
  56. package/dist/agentic/guides/modules/resources.md +1 -1
  57. package/dist/agentic/guides/modules/sales.md +17 -17
  58. package/dist/agentic/guides/modules/scheduler.md +1 -1
  59. package/dist/agentic/guides/modules/search.md +1 -1
  60. package/dist/agentic/guides/modules/security.md +1 -1
  61. package/dist/agentic/guides/modules/shipping_carriers.md +1 -1
  62. package/dist/agentic/guides/modules/sso.md +1 -1
  63. package/dist/agentic/guides/modules/staff.md +2 -2
  64. package/dist/agentic/guides/modules/storage_s3.md +1 -1
  65. package/dist/agentic/guides/modules/sync_akeneo.md +1 -1
  66. package/dist/agentic/guides/modules/sync_excel.md +1 -1
  67. package/dist/agentic/guides/modules/system_status_overlays.md +1 -1
  68. package/dist/agentic/guides/modules/translations.md +1 -1
  69. package/dist/agentic/guides/modules/webhooks.md +2 -2
  70. package/dist/agentic/guides/modules/workflows.md +1 -1
  71. package/dist/agentic/guides/testing-debugging.md +62 -0
  72. package/dist/agentic/guides/upstream/AGENTS.md +297 -0
  73. package/dist/agentic/guides/upstream/BACKWARD_COMPATIBILITY.md +303 -0
  74. package/dist/agentic/guides/upstream/manifest.json +8 -0
  75. package/dist/agentic/shared/AGENTS.md.template +129 -296
  76. package/dist/agentic/shared/ai/harness/README.md +42 -0
  77. package/dist/agentic/shared/ai/harness/RELEASE.md +53 -0
  78. package/dist/agentic/shared/ai/harness/cases.json +12608 -0
  79. package/dist/agentic/shared/ai/harness/cases.schema.json +115 -0
  80. package/dist/agentic/shared/ai/harness/fixtures/index.json +43 -0
  81. package/dist/agentic/shared/ai/harness/fixtures/seeds.json +150 -0
  82. package/dist/agentic/shared/ai/harness/generated-code-review-policy.md +20 -0
  83. package/dist/agentic/shared/ai/harness/generated-code-review-response.schema.json +43 -0
  84. package/dist/agentic/shared/ai/harness/generated-code-review-result.schema.json +109 -0
  85. package/dist/agentic/shared/ai/harness/release-matrix.json +119 -0
  86. package/dist/agentic/shared/ai/harness/release-result.schema.json +219 -0
  87. package/dist/agentic/shared/ai/harness/result.schema.json +74 -0
  88. package/dist/agentic/shared/ai/harness/routing-response.schema.json +12 -0
  89. package/dist/agentic/shared/ai/harness/target-validation-result.schema.json +73 -0
  90. package/dist/agentic/shared/ai/harness/validators.json +68 -0
  91. package/dist/agentic/shared/ai/harness/writable-ast-oracles.mjs +1120 -0
  92. package/dist/agentic/shared/ai/harness/writable-behavior-oracles.mjs +811 -0
  93. package/dist/agentic/shared/ai/skills/om-backend-ui-design/SKILL.md +17 -241
  94. package/dist/agentic/shared/ai/skills/om-backend-ui-design/references/crud-surfaces.md +12 -0
  95. package/dist/agentic/shared/ai/skills/om-backend-ui-design/references/frontend-and-design-system.md +53 -0
  96. package/dist/agentic/shared/ai/skills/om-backend-ui-design/references/page-and-navigation.md +12 -0
  97. package/dist/agentic/shared/ai/skills/om-backend-ui-design/references/quality-states.md +11 -0
  98. package/dist/agentic/shared/ai/skills/om-build-workflow/SKILL.md +25 -0
  99. package/dist/agentic/shared/ai/skills/om-build-workflow/references/activity-contracts.md +12 -0
  100. package/dist/agentic/shared/ai/skills/om-build-workflow/references/durability-and-progress.md +13 -0
  101. package/dist/agentic/shared/ai/skills/om-build-workflow/references/workflow-design.md +12 -0
  102. package/dist/agentic/shared/ai/skills/om-create-ai-agent/SKILL.md +27 -0
  103. package/dist/agentic/shared/ai/skills/om-create-ai-agent/references/attachments-and-overrides.md +12 -0
  104. package/dist/agentic/shared/ai/skills/om-create-ai-agent/references/module-agents-and-tools.md +22 -0
  105. package/dist/agentic/shared/ai/skills/om-create-ai-agent/references/orchestrator-agents.md +12 -0
  106. package/dist/agentic/shared/ai/skills/om-create-ai-agent/references/surface-selector.md +19 -0
  107. package/dist/agentic/shared/ai/skills/om-data-model-design/SKILL.md +15 -601
  108. package/dist/agentic/shared/ai/skills/om-data-model-design/references/integrity-and-concurrency.md +13 -0
  109. package/dist/agentic/shared/ai/skills/om-data-model-design/references/migration-workflow.md +13 -0
  110. package/dist/agentic/shared/ai/skills/om-data-model-design/references/schema-design.md +14 -0
  111. package/dist/agentic/shared/ai/skills/om-data-model-design/references/sensitive-data.md +10 -0
  112. package/dist/agentic/shared/ai/skills/om-eject-and-customize/SKILL.md +14 -310
  113. package/dist/agentic/shared/ai/skills/om-eject-and-customize/references/decision-and-procedure.md +17 -0
  114. package/dist/agentic/shared/ai/skills/om-evolve-harness/SKILL.md +28 -0
  115. package/dist/agentic/shared/ai/skills/om-evolve-harness/references/case-template.md +84 -0
  116. package/dist/agentic/shared/ai/skills/om-evolve-harness/references/case-workflow.md +16 -0
  117. package/dist/agentic/shared/ai/skills/om-evolve-harness/references/owner-selection.md +17 -0
  118. package/dist/agentic/shared/ai/skills/om-framework-context/SKILL.md +24 -0
  119. package/dist/agentic/shared/ai/skills/om-framework-context/references/resolver-procedure.md +11 -0
  120. package/dist/agentic/shared/ai/skills/om-framework-context/references/skew-and-escalation.md +13 -0
  121. package/dist/agentic/shared/ai/skills/om-help/SKILL.md +15 -97
  122. package/dist/agentic/shared/ai/skills/om-help/references/delivery-workflows.md +17 -0
  123. package/dist/agentic/shared/ai/skills/om-help/references/task-families.md +20 -0
  124. package/dist/agentic/shared/ai/skills/om-implement-spec/SKILL.md +14 -156
  125. package/dist/agentic/shared/ai/skills/om-implement-spec/references/phases-and-gates.md +12 -0
  126. package/dist/agentic/shared/ai/skills/om-integration-builder/SKILL.md +18 -710
  127. package/dist/agentic/shared/ai/skills/om-integration-builder/references/package-and-activation.md +14 -0
  128. package/dist/agentic/shared/ai/skills/om-integration-builder/references/provider-families.md +14 -0
  129. package/dist/agentic/shared/ai/skills/om-integration-builder/references/security-and-reliability.md +14 -0
  130. package/dist/agentic/shared/ai/skills/om-integration-builder/references/sync-and-files.md +12 -0
  131. package/dist/agentic/shared/ai/skills/om-module-scaffold/SKILL.md +19 -821
  132. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/api-and-domain.md +18 -0
  133. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/business-one-shot-blueprints.md +104 -0
  134. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/data-and-migrations.md +12 -0
  135. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/discovery-surface-catalog.md +83 -0
  136. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/module-surfaces.md +20 -0
  137. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/planning.md +11 -0
  138. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/verification.md +13 -0
  139. package/dist/agentic/shared/ai/skills/om-system-extension/SKILL.md +16 -846
  140. package/dist/agentic/shared/ai/skills/om-system-extension/references/extension-branches.md +18 -0
  141. package/dist/agentic/shared/ai/skills/om-system-extension/references/mechanism-selector.md +23 -0
  142. package/dist/agentic/shared/ai/skills/om-system-extension/references/read-write-roundtrip.md +13 -0
  143. package/dist/agentic/shared/ai/skills/om-system-extension/references/unified-overrides.md +38 -0
  144. package/dist/agentic/shared/ai/skills/om-system-extension/references/verification.md +11 -0
  145. package/dist/agentic/shared/ai/skills/om-trim-unused-modules/SKILL.md +15 -63
  146. package/dist/agentic/shared/ai/skills/om-trim-unused-modules/references/dependency-and-redirect.md +15 -0
  147. package/dist/agentic/shared/ai/skills/om-troubleshooter/SKILL.md +15 -467
  148. package/dist/agentic/shared/ai/skills/om-troubleshooter/references/diagnosis-map.md +16 -0
  149. package/dist/agentic/shared/ai/skills/om-troubleshooter/references/regression-oracles.md +14 -0
  150. package/dist/agentic/shared/ai/skills/tiers.json +137 -20
  151. package/dist/agentic/shared/ai/skills/tiers.schema.json +61 -34
  152. package/dist/agentic/shared/scripts/agent-harness-tool-server.mjs +174 -0
  153. package/dist/agentic/shared/scripts/evaluate-agent-harness.mjs +2371 -0
  154. package/dist/agentic/shared/scripts/execution-sandbox.mjs +314 -0
  155. package/dist/agentic/shared/scripts/framework-context.mjs +869 -0
  156. package/dist/agentic/shared/scripts/install-skills.mjs +925 -0
  157. package/dist/agentic/shared/scripts/install-skills.sh +4 -487
  158. package/dist/agentic/shared/scripts/prepare-agent-harness-fixture.mjs +221 -0
  159. package/dist/agentic/shared/scripts/run-agent-harness-release.mjs +1751 -0
  160. package/dist/lib/__integration__/TC-INT-008.spec.js +94 -18
  161. package/dist/lib/__integration__/TC-INT-008.spec.js.map +2 -2
  162. package/dist/lib/agentic-init.js +9 -3
  163. package/dist/lib/agentic-init.js.map +2 -2
  164. package/dist/lib/agentic-setup.js +427 -187
  165. package/dist/lib/agentic-setup.js.map +2 -2
  166. package/dist/lib/db/commands.js +1 -1
  167. package/dist/lib/db/commands.js.map +1 -1
  168. package/dist/lib/eject.js +17 -2
  169. package/dist/lib/eject.js.map +2 -2
  170. package/dist/lib/generate-watch-events.js +106 -0
  171. package/dist/lib/generate-watch-events.js.map +7 -0
  172. package/dist/lib/generators/ast/imports.js +1 -1
  173. package/dist/lib/generators/ast/imports.js.map +1 -1
  174. package/dist/lib/generators/entity-ids.js +21 -14
  175. package/dist/lib/generators/entity-ids.js.map +2 -2
  176. package/dist/lib/generators/extensions/injection-widgets.js +1 -1
  177. package/dist/lib/generators/extensions/injection-widgets.js.map +1 -1
  178. package/dist/lib/generators/index.js +7 -1
  179. package/dist/lib/generators/index.js.map +2 -2
  180. package/dist/lib/generators/module-facts-discovery.js +39 -7
  181. package/dist/lib/generators/module-facts-discovery.js.map +2 -2
  182. package/dist/lib/generators/module-facts.js +66 -18
  183. package/dist/lib/generators/module-facts.js.map +2 -2
  184. package/dist/lib/generators/module-registry.js +257 -273
  185. package/dist/lib/generators/module-registry.js.map +3 -3
  186. package/dist/lib/generators/openapi.js +114 -12
  187. package/dist/lib/generators/openapi.js.map +2 -2
  188. package/dist/lib/in-process-generate-watcher.js +13 -2
  189. package/dist/lib/in-process-generate-watcher.js.map +2 -2
  190. package/dist/lib/module-install.js +2 -6
  191. package/dist/lib/module-install.js.map +2 -2
  192. package/dist/lib/modules-config.js +1 -1
  193. package/dist/lib/modules-config.js.map +1 -1
  194. package/dist/lib/post-generate-invalidation.js +49 -0
  195. package/dist/lib/post-generate-invalidation.js.map +7 -0
  196. package/dist/lib/resolver.js +3 -1
  197. package/dist/lib/resolver.js.map +2 -2
  198. package/dist/mercato.js +89 -52
  199. package/dist/mercato.js.map +2 -2
  200. package/package.json +11 -9
  201. package/src/__tests__/mercato.test.ts +118 -39
  202. package/src/lib/__integration__/TC-INT-008.spec.ts +116 -22
  203. package/src/lib/__tests__/agentic-init.test.ts +25 -5
  204. package/src/lib/__tests__/agentic-setup.ownership.test.ts +315 -0
  205. package/src/lib/__tests__/eject.test.ts +85 -0
  206. package/src/lib/__tests__/generate-watch-events.test.ts +112 -0
  207. package/src/lib/__tests__/generate-watch-structure.test.ts +20 -0
  208. package/src/lib/__tests__/in-process-generate-watcher.test.ts +193 -2
  209. package/src/lib/__tests__/post-generate-invalidation.test.ts +81 -0
  210. package/src/lib/agentic-init.ts +10 -3
  211. package/src/lib/agentic-setup.ts +539 -226
  212. package/src/lib/db/commands.ts +1 -1
  213. package/src/lib/eject.ts +24 -2
  214. package/src/lib/generate-watch-events.ts +125 -0
  215. package/src/lib/generators/__tests__/entity-ids.test.ts +98 -1
  216. package/src/lib/generators/__tests__/generators.test.ts +5 -0
  217. package/src/lib/generators/__tests__/module-facts.bc-guard.test.ts +6 -0
  218. package/src/lib/generators/__tests__/module-facts.customers.fixture.test.ts +1 -0
  219. package/src/lib/generators/__tests__/module-facts.discovery.test.ts +38 -10
  220. package/src/lib/generators/__tests__/module-facts.extension-hosts.test.ts +108 -0
  221. package/src/lib/generators/__tests__/openapi.test.ts +174 -0
  222. package/src/lib/generators/__tests__/output-snapshots.test.ts +37 -1
  223. package/src/lib/generators/__tests__/route-collision-guard.test.ts +123 -0
  224. package/src/lib/generators/__tests__/structural-contracts.test.ts +1 -1
  225. package/src/lib/generators/ast/imports.ts +1 -1
  226. package/src/lib/generators/entity-ids.ts +34 -14
  227. package/src/lib/generators/extensions/injection-widgets.ts +1 -1
  228. package/src/lib/generators/index.ts +7 -1
  229. package/src/lib/generators/module-facts-discovery.ts +54 -7
  230. package/src/lib/generators/module-facts.ts +85 -21
  231. package/src/lib/generators/module-registry.ts +337 -299
  232. package/src/lib/generators/openapi.ts +167 -14
  233. package/src/lib/in-process-generate-watcher.ts +35 -6
  234. package/src/lib/module-install.ts +2 -6
  235. package/src/lib/modules-config.ts +1 -1
  236. package/src/lib/post-generate-invalidation.ts +62 -0
  237. package/src/lib/resolver.ts +4 -1
  238. package/src/mercato.ts +96 -56
  239. package/dist/agentic/shared/ai/skills/om-auto-continue-pr-loop/SKILL.md +0 -27
  240. package/dist/agentic/shared/ai/skills/om-auto-create-pr-loop/SKILL.md +0 -27
  241. package/dist/agentic/shared/ai/skills/om-backend-ui-design/references/ui-components.md +0 -260
  242. package/dist/agentic/shared/ai/skills/om-data-model-design/references/mikro-orm-cheatsheet.md +0 -146
  243. package/dist/agentic/shared/ai/skills/om-help/references/skills-catalog.md +0 -84
  244. package/dist/agentic/shared/ai/skills/om-help/references/workflow-sequences.md +0 -193
  245. package/dist/agentic/shared/ai/skills/om-integration-builder/STANDALONE.md +0 -34
  246. package/dist/agentic/shared/ai/skills/om-integration-builder/references/adapter-contracts.md +0 -762
  247. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/naming-conventions.md +0 -50
  248. package/dist/agentic/shared/ai/skills/om-module-scaffold/references/navigation-patterns.md +0 -97
  249. package/dist/agentic/shared/ai/skills/om-system-extension/references/extension-contracts.md +0 -271
  250. package/dist/agentic/shared/ai/skills/om-troubleshooter/references/diagnostic-commands.md +0 -101
@@ -0,0 +1,1751 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { spawnSync } from 'node:child_process'
4
+ import { createHash } from 'node:crypto'
5
+ import fs from 'node:fs'
6
+ import { createRequire } from 'node:module'
7
+ import os from 'node:os'
8
+ import path from 'node:path'
9
+ import process from 'node:process'
10
+ import { pathToFileURL } from 'node:url'
11
+ import { assertSandboxRuntimeAvailable, sandboxedInvocation, verifyLinuxSandboxIsolation } from './execution-sandbox.mjs'
12
+
13
+ const WRITABLE_KINDS = new Set(['implementation', 'regression'])
14
+ const RELEASE_SUPPORTED_RUNNERS = ['codex', 'claude']
15
+ const RELEASE_VALIDATION_COMMANDS = ['yarn generate', 'yarn typecheck', 'yarn lint', 'yarn build']
16
+ const RELEASE_VALIDATION_OUTPUT_ROOTS = new Map([
17
+ ['yarn generate', ['.mercato/generated']],
18
+ ['yarn typecheck', ['tsconfig.tsbuildinfo']],
19
+ ['yarn lint', []],
20
+ ['yarn build', ['.mercato/generated', '.mercato/next', 'next-env.d.ts', 'tsconfig.tsbuildinfo']],
21
+ ])
22
+ const RUNNERS = new Set(RELEASE_SUPPORTED_RUNNERS)
23
+ const ALLOWED_VALIDATION_COMMANDS = new Set(RELEASE_VALIDATION_COMMANDS)
24
+ const GENERATED_TEST_RUNNERS = new Set(['jest', 'playwright-api', 'playwright-browser'])
25
+ const RESULT_LIMIT = 262_144
26
+ const ERROR_LIMIT = 2_000
27
+ const VIOLATION_LIMIT = 300
28
+ const COPY_EXCLUDED_PREFIXES = [
29
+ '.git', '.next', '.turbo', '.cache', 'build', 'coverage', 'dist', 'node_modules', 'out',
30
+ '.ai/framework-context', '.ai/harness/results', '.ai/reports',
31
+ '.mercato/generated', '.mercato/next', 'next-env.d.ts', 'tsconfig.tsbuildinfo',
32
+ ]
33
+ const SAFE_ENV_TEMPLATES = new Set(['.env.example', '.env.sample', '.env.template'])
34
+ const SENSITIVE_AUTH_FILES = new Set(['.git-credentials', '.netrc', '.npmrc', '.pypirc', '.yarnrc', '.yarnrc.yml', '.yarnrc.yaml'])
35
+ const SENSITIVE_AUTH_DATA_FILE = /^(?:auth|credentials?|secrets?|tokens?)(?:\.(?:conf(?:ig)?|ini|json|toml|txt|ya?ml))?$/
36
+ const SENSITIVE_ENV_KEY = /(?:^|_)(?:api_?key|auth|credential|credentials|password|passwd|private_?key|secret|token)(?:_|$)/i
37
+ const GENERATED_YARN_CONFIG_PATH = '.yarnrc.yml'
38
+ const GENERATED_YARN_CONFIG_LIMIT = 16_384
39
+
40
+ function usage() {
41
+ return `Run the complete standalone agent-harness release gate.
42
+
43
+ Usage:
44
+ yarn harness:release --runner <codex|claude> --prepare-targets /absolute/empty-directory --acknowledge-writes
45
+ yarn harness:release --runner <codex|claude> --writable-targets /absolute/release-targets.json --acknowledge-writes
46
+
47
+ Options:
48
+ --root <absolute-app> Controller/generated app root (default: current directory)
49
+ --runner <codex|claude> Required primary runner for every blocking live lane
50
+ --portability-runner <runner> Optional different runner for the 39-case read-only portability lane
51
+ --prepare-targets <absolute> Clone this fresh scaffold once per writable case under an empty/new directory
52
+ --writable-targets <absolute> JSON map of every writable case to a fresh disposable app
53
+ --case-timeout <ms> Per-model invocation timeout (default: 120000)
54
+ --validation-timeout <ms> Timeout for each yarn validation (default: 1800000)
55
+ --acknowledge-writes Required: fixture preparation and validation commands write files
56
+ --help Show this help
57
+
58
+ Exactly one target option is required. Automatic targets require a fresh controller
59
+ without local environment, credential, or private-key files; safe .env.example/sample/template
60
+ files are retained. Targets exclude dependencies, build outputs, harness results, and
61
+ generated framework context, then safely reference the controller's protected dependency
62
+ tree. Externally supplied targets must use the same
63
+ node_modules link to that protected tree; nested dependency copies are rejected.
64
+ The complete release requires trusted Bubblewrap plus working user/network namespaces on Linux;
65
+ native macOS, Windows, untrusted runtimes, and unavailable isolation fail closed. The command preflights complete matrix,
66
+ fixture, review, and target coverage before
67
+ running deterministic validation, selected primary routing, optional portability routing, writable trusted-oracle
68
+ gates, explicit om-code-review, and the release-matrix validation commands. It stores
69
+ only a sanitized aggregate report under .ai/harness/results/.`
70
+ }
71
+
72
+ function parseArgs(argv) {
73
+ const options = {
74
+ root: process.cwd(),
75
+ runner: undefined,
76
+ portabilityRunner: undefined,
77
+ prepareTargets: undefined,
78
+ writableTargets: undefined,
79
+ caseTimeout: 120_000,
80
+ validationTimeout: 1_800_000,
81
+ acknowledgeWrites: false,
82
+ help: false,
83
+ }
84
+ for (let index = 0; index < argv.length; index += 1) {
85
+ const arg = argv[index]
86
+ const value = () => {
87
+ index += 1
88
+ if (index >= argv.length) throw new Error(`${arg} requires a value`)
89
+ return argv[index]
90
+ }
91
+ if (arg === '--help' || arg === '-h') options.help = true
92
+ else if (arg === '--root') options.root = value()
93
+ else if (arg === '--runner') options.runner = value()
94
+ else if (arg === '--portability-runner') options.portabilityRunner = value()
95
+ else if (arg === '--prepare-targets') options.prepareTargets = value()
96
+ else if (arg === '--writable-targets') options.writableTargets = value()
97
+ else if (arg === '--case-timeout') options.caseTimeout = Number(value())
98
+ else if (arg === '--validation-timeout') options.validationTimeout = Number(value())
99
+ else if (arg === '--acknowledge-writes') options.acknowledgeWrites = true
100
+ else throw new Error(`unknown argument: ${arg}`)
101
+ }
102
+ if (options.help) return options
103
+ if (!path.isAbsolute(options.root)) throw new Error('--root must be an absolute path')
104
+ if (!RUNNERS.has(options.runner)) throw new Error('--runner must be codex or claude')
105
+ if (options.portabilityRunner !== undefined && !RUNNERS.has(options.portabilityRunner)) throw new Error('--portability-runner must be codex or claude')
106
+ if (options.portabilityRunner === options.runner) throw new Error('--portability-runner must differ from --runner')
107
+ if (Boolean(options.prepareTargets) === Boolean(options.writableTargets)) throw new Error('pass exactly one of --prepare-targets or --writable-targets')
108
+ if (options.prepareTargets && !path.isAbsolute(options.prepareTargets)) throw new Error('--prepare-targets must be an absolute path')
109
+ if (options.writableTargets && !path.isAbsolute(options.writableTargets)) throw new Error('--writable-targets must be an absolute path')
110
+ if (!options.acknowledgeWrites) throw new Error('the full release gate requires --acknowledge-writes')
111
+ if (!Number.isInteger(options.caseTimeout) || options.caseTimeout < 1_000 || options.caseTimeout > 3_600_000) throw new Error('--case-timeout must be from 1000 to 3600000 milliseconds')
112
+ if (!Number.isInteger(options.validationTimeout) || options.validationTimeout < 1_000 || options.validationTimeout > 7_200_000) throw new Error('--validation-timeout must be from 1000 to 7200000 milliseconds')
113
+ return options
114
+ }
115
+
116
+ function readJson(file) {
117
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
118
+ }
119
+
120
+ function sha256(value) {
121
+ return createHash('sha256').update(value).digest('hex')
122
+ }
123
+
124
+ function isPathInside(parent, child) {
125
+ const relative = path.relative(parent, child)
126
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
127
+ }
128
+
129
+ function validModelSelector(value) {
130
+ return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,99}$/.test(value)
131
+ }
132
+
133
+ function normalizedRelative(root, absolute) {
134
+ return path.relative(root, absolute).replaceAll(path.sep, '/')
135
+ }
136
+
137
+ function copyPathExcluded(relative) {
138
+ return COPY_EXCLUDED_PREFIXES.some((prefix) => relative === prefix || relative.startsWith(`${prefix}/`))
139
+ }
140
+
141
+ function sensitiveScaffoldPath(relative, stat) {
142
+ const basename = path.posix.basename(relative).toLowerCase()
143
+ const lowerRelative = relative.toLowerCase()
144
+ if ((basename === '.env' || basename.startsWith('.env.')) && !SAFE_ENV_TEMPLATES.has(basename)) return true
145
+ // A fresh create-mercato-app scaffold always contains this generated root file.
146
+ // Its contents are checked separately against the exact credential-free shape.
147
+ if (lowerRelative === GENERATED_YARN_CONFIG_PATH) return relative !== GENERATED_YARN_CONFIG_PATH
148
+ if (SENSITIVE_AUTH_FILES.has(basename)) return true
149
+ if (/^(?:\.aws|\.azure|\.config\/gcloud|\.config\/gh|\.docker|\.gnupg|\.kube|\.oci|\.pulumi|\.ssh|\.terraform\.d)(?:\/|$)/.test(lowerRelative)) return true
150
+ if (stat?.isDirectory()) return false
151
+ if (SENSITIVE_AUTH_DATA_FILE.test(basename)) return true
152
+ if (/\.(?:key|pem|p12|pfx|jks|keystore)$/.test(basename)) return true
153
+ if (/^(?:id_rsa|id_dsa|id_ecdsa|id_ed25519)$/.test(basename)) return true
154
+ return /(?:^|[._-])(?:credential|credentials|private[._-]?key|service[._-]?account)(?:[._-]|$)/.test(basename)
155
+ }
156
+
157
+ function parseGeneratedQuotedValue(line, prefix) {
158
+ if (!line.startsWith(prefix)) return undefined
159
+ try {
160
+ const serialized = line.slice(prefix.length)
161
+ const value = JSON.parse(serialized)
162
+ return typeof value === 'string' && value.length > 0 && JSON.stringify(value) === serialized ? value : undefined
163
+ } catch {
164
+ return undefined
165
+ }
166
+ }
167
+
168
+ function validGeneratedYarnConfig(contents) {
169
+ if (Buffer.byteLength(contents, 'utf8') > GENERATED_YARN_CONFIG_LIMIT || contents.includes('\0')) return false
170
+ const lines = contents.replaceAll('\r\n', '\n').split('\n').filter((line) => line !== '')
171
+ const migrated = lines[0] === 'approvedGitRepositories:'
172
+ if (migrated) {
173
+ if (
174
+ lines.shift() !== 'approvedGitRepositories:'
175
+ || lines.shift() !== ' - "**"'
176
+ || lines.shift() !== 'enableScripts: true'
177
+ ) return false
178
+ }
179
+ if (lines.shift() !== 'nodeLinker: node-modules') return false
180
+ if (migrated && lines.shift() !== 'npmMinimalAgeGate: 0') return false
181
+ if (!lines.length) return true
182
+
183
+ const unsafeHttpHosts = []
184
+ const readUnsafeHttpHosts = () => {
185
+ if (lines[0] !== 'unsafeHttpWhitelist:') return true
186
+ lines.shift()
187
+ while (lines[0]?.startsWith(' - ')) {
188
+ const host = parseGeneratedQuotedValue(lines.shift(), ' - ')
189
+ if (!host) return false
190
+ unsafeHttpHosts.push(host)
191
+ }
192
+ return unsafeHttpHosts.length > 0
193
+ }
194
+ if (!migrated && !readUnsafeHttpHosts()) return false
195
+
196
+ if (lines.shift() !== 'npmScopes:' || lines.shift() !== ' open-mercato:') return false
197
+ if (migrated && lines.shift() !== ' npmMinimalAgeGate: 0') return false
198
+ const registryUrl = parseGeneratedQuotedValue(lines.shift() ?? '', ' npmRegistryServer: ')
199
+ if (!registryUrl || (!migrated && lines.shift() !== ' npmMinimalAgeGate: 0')) return false
200
+ if (migrated && !readUnsafeHttpHosts()) return false
201
+ if (lines.length) return false
202
+
203
+ let parsedRegistryUrl
204
+ try {
205
+ parsedRegistryUrl = new URL(registryUrl)
206
+ } catch {
207
+ return false
208
+ }
209
+ if (!['http:', 'https:'].includes(parsedRegistryUrl.protocol)) return false
210
+ if (parsedRegistryUrl.username || parsedRegistryUrl.password || parsedRegistryUrl.search || parsedRegistryUrl.hash) return false
211
+
212
+ const expectedUnsafeHosts = parsedRegistryUrl.protocol === 'http:' ? [parsedRegistryUrl.hostname] : []
213
+ if (parsedRegistryUrl.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(parsedRegistryUrl.hostname)) {
214
+ expectedUnsafeHosts.push('host.docker.internal')
215
+ }
216
+ return JSON.stringify(unsafeHttpHosts) === JSON.stringify(expectedUnsafeHosts)
217
+ }
218
+
219
+ function validateGeneratedYarnConfig(source, relative, stat) {
220
+ if (relative !== GENERATED_YARN_CONFIG_PATH) return
221
+ if (!stat.isFile() || stat.isSymbolicLink() || !validGeneratedYarnConfig(fs.readFileSync(source, 'utf8'))) {
222
+ throw new Error('fresh controller contains an unsafe Yarn registry configuration; use a credential-free fresh scaffold')
223
+ }
224
+ }
225
+
226
+ function validateScaffoldCopySource(root) {
227
+ const realRoot = fs.realpathSync(root)
228
+ const visit = (directory) => {
229
+ for (const name of fs.readdirSync(directory).sort()) {
230
+ const source = path.join(directory, name)
231
+ const relative = normalizedRelative(realRoot, source)
232
+ if (copyPathExcluded(relative)) continue
233
+ const stat = fs.lstatSync(source)
234
+ if (sensitiveScaffoldPath(relative, stat)) {
235
+ throw new Error('fresh controller contains a local environment, credential, or private-key file; use a sanitized fresh scaffold')
236
+ }
237
+ validateGeneratedYarnConfig(source, relative, stat)
238
+ if (stat.isSymbolicLink()) {
239
+ const resolved = fs.realpathSync(source)
240
+ const resolvedRelative = normalizedRelative(realRoot, resolved)
241
+ if (!isPathInside(realRoot, resolved) || copyPathExcluded(resolvedRelative)) {
242
+ throw new Error(`fresh scaffold contains an unsafe copied symlink: ${relative}`)
243
+ }
244
+ } else if (stat.isDirectory()) visit(source)
245
+ else if (!stat.isFile()) throw new Error(`fresh scaffold contains an unsupported entry: ${relative}`)
246
+ }
247
+ }
248
+ visit(realRoot)
249
+ }
250
+
251
+ function copyFreshScaffold(sourceRoot, targetRoot) {
252
+ const realSourceRoot = fs.realpathSync(sourceRoot)
253
+ const visit = (sourceDirectory, targetDirectory) => {
254
+ fs.mkdirSync(targetDirectory, { recursive: true, mode: 0o755 })
255
+ for (const name of fs.readdirSync(sourceDirectory).sort()) {
256
+ const source = path.join(sourceDirectory, name)
257
+ const relative = normalizedRelative(realSourceRoot, source)
258
+ if (copyPathExcluded(relative)) continue
259
+ const stat = fs.lstatSync(source)
260
+ // Fail closed if a sensitive file appears between validation and copy.
261
+ if (sensitiveScaffoldPath(relative, stat)) {
262
+ throw new Error('fresh controller contains a local environment, credential, or private-key file; use a sanitized fresh scaffold')
263
+ }
264
+ const destination = path.join(targetDirectory, name)
265
+ validateGeneratedYarnConfig(source, relative, stat)
266
+ if (stat.isDirectory()) visit(source, destination)
267
+ else if (stat.isFile()) {
268
+ fs.copyFileSync(source, destination, fs.constants.COPYFILE_FICLONE)
269
+ fs.chmodSync(destination, stat.mode & 0o777)
270
+ } else if (stat.isSymbolicLink()) {
271
+ const resolved = fs.realpathSync(source)
272
+ const resolvedRelative = normalizedRelative(realSourceRoot, resolved)
273
+ const target = path.join(targetRoot, resolvedRelative)
274
+ const type = fs.statSync(resolved).isDirectory() ? (process.platform === 'win32' ? 'junction' : 'dir') : 'file'
275
+ fs.symlinkSync(path.relative(path.dirname(destination), target), destination, type)
276
+ }
277
+ }
278
+ }
279
+ visit(realSourceRoot, targetRoot)
280
+ }
281
+
282
+ export function resolvePreparationRoot(requested, controllerRoot) {
283
+ if (!path.isAbsolute(requested)) throw new Error('--prepare-targets must be an absolute path')
284
+ const resolved = path.resolve(requested)
285
+ if (resolved === path.parse(resolved).root) throw new Error('--prepare-targets cannot be a filesystem root')
286
+ let actual
287
+ if (fs.existsSync(resolved)) {
288
+ const stat = fs.lstatSync(resolved)
289
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('--prepare-targets must be a regular directory')
290
+ if (fs.readdirSync(resolved).length) throw new Error('--prepare-targets must be empty')
291
+ actual = fs.realpathSync(resolved)
292
+ } else {
293
+ const parent = path.dirname(resolved)
294
+ if (!fs.existsSync(parent)) throw new Error('--prepare-targets parent directory must already exist')
295
+ const stat = fs.lstatSync(parent)
296
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('--prepare-targets parent must be a regular directory')
297
+ actual = path.join(fs.realpathSync(parent), path.basename(resolved))
298
+ }
299
+ const controller = fs.realpathSync(controllerRoot)
300
+ if (isPathInside(controller, actual) || isPathInside(actual, controller)) {
301
+ throw new Error('--prepare-targets must be separate from the controller app')
302
+ }
303
+ return actual
304
+ }
305
+
306
+ export function prepareWritableTargets({ root, prepareRoot, caseIds }) {
307
+ const controller = fs.realpathSync(root)
308
+ if (fs.existsSync(path.join(controller, '.ai', 'harness', 'DISPOSABLE'))) {
309
+ throw new Error('automatic target preparation requires an unmodified fresh controller scaffold')
310
+ }
311
+ const targetRoot = resolvePreparationRoot(prepareRoot, controller)
312
+ if (!Array.isArray(caseIds) || new Set(caseIds).size !== caseIds.length || caseIds.some((id) => !/^OMH-[0-9]{3}$/.test(id))) {
313
+ throw new Error('automatic writable target case IDs are invalid or duplicated')
314
+ }
315
+ const dependencyRoot = path.join(controller, 'node_modules')
316
+ let dependencyStat
317
+ try { dependencyStat = fs.lstatSync(dependencyRoot) } catch { throw new Error('controller node_modules is unavailable; run yarn install') }
318
+ if (!dependencyStat.isDirectory() || dependencyStat.isSymbolicLink()) throw new Error('controller node_modules must be a regular installed dependency directory')
319
+ validateScaffoldCopySource(controller)
320
+ if (!fs.existsSync(targetRoot)) fs.mkdirSync(targetRoot, { mode: 0o700 })
321
+ const targetRootStat = fs.lstatSync(targetRoot)
322
+ if (!targetRootStat.isDirectory() || targetRootStat.isSymbolicLink() || fs.readdirSync(targetRoot).length) {
323
+ throw new Error('automatic writable target root stopped being an empty regular directory')
324
+ }
325
+ const targets = {}
326
+ for (const caseId of caseIds) {
327
+ const target = path.join(targetRoot, caseId)
328
+ fs.mkdirSync(target, { mode: 0o700 })
329
+ copyFreshScaffold(controller, target)
330
+ fs.symlinkSync(dependencyRoot, path.join(target, 'node_modules'), process.platform === 'win32' ? 'junction' : 'dir')
331
+ targets[caseId] = fs.realpathSync(target)
332
+ }
333
+ const manifest = { schemaVersion: 1, targets }
334
+ fs.writeFileSync(path.join(targetRoot, 'release-targets.json'), `${JSON.stringify(manifest, null, 2)}\n`, { mode: 0o600 })
335
+ return manifest
336
+ }
337
+
338
+ function sortedUnique(values) {
339
+ return [...new Set(values)].sort()
340
+ }
341
+
342
+ function difference(left, right) {
343
+ const rightSet = new Set(right)
344
+ return sortedUnique(left.filter((value) => !rightSet.has(value)))
345
+ }
346
+
347
+ function duplicates(values) {
348
+ const seen = new Set()
349
+ const repeated = new Set()
350
+ for (const value of values) {
351
+ if (seen.has(value)) repeated.add(value)
352
+ seen.add(value)
353
+ }
354
+ return [...repeated].sort()
355
+ }
356
+
357
+ function resolveCaseSelector(selector, allCaseIds) {
358
+ if (selector === 'all') return [...allCaseIds]
359
+ return Array.isArray(selector) ? [...selector] : []
360
+ }
361
+
362
+ function addCoverageViolation(violations, label, ids) {
363
+ if (ids.length) violations.push(`${label}: ${ids.join(', ')}`)
364
+ }
365
+
366
+ function validTargetsManifest(targetsManifest) {
367
+ return targetsManifest?.schemaVersion === 1 && targetsManifest?.targets && typeof targetsManifest.targets === 'object' && !Array.isArray(targetsManifest.targets)
368
+ }
369
+
370
+ export function generatedTestExecutionContract(entry) {
371
+ const cliPackage = entry.runner === 'jest' ? 'jest' : '@playwright/test'
372
+ const argv = entry.runner === 'jest'
373
+ ? ['<resolved-cli>', '--config', 'jest.config.cjs', '--runInBand', '--runTestsByPath', entry.artifact, '--cacheDirectory', '<isolated-temp>/jest-cache', '--json', '--outputFile', '<isolated-temp>/jest-results.json']
374
+ : ['<resolved-cli>', 'test', '--config', '.ai/qa/tests/playwright.config.ts', entry.artifact, '--retries=0', '--workers=1', '--forbid-only', '--reporter=json', '--output', '<isolated-temp>/playwright-output', '--update-snapshots=none']
375
+ return { executor: 'node', cliPackage, argv, command: ['node', ...argv].join(' ') }
376
+ }
377
+
378
+ function readGeneratedTestReport(file, tempRoot, label) {
379
+ const stat = fs.lstatSync(file)
380
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size < 2 || stat.size > 8 * 1024 * 1024
381
+ || !isPathInside(fs.realpathSync(tempRoot), fs.realpathSync(file))) {
382
+ throw new Error(`${label} report must be a bounded regular file in the isolated output root`)
383
+ }
384
+ return readJson(file)
385
+ }
386
+
387
+ function collectPlaywrightTests(suites, output = []) {
388
+ for (const suite of Array.isArray(suites) ? suites : []) {
389
+ for (const spec of Array.isArray(suite?.specs) ? suite.specs : []) {
390
+ for (const test of Array.isArray(spec?.tests) ? spec.tests : []) output.push(test)
391
+ }
392
+ collectPlaywrightTests(suite?.suites, output)
393
+ }
394
+ return output
395
+ }
396
+
397
+ function generatedTestCounts(testRunner, tempRoot) {
398
+ if (testRunner === 'jest') {
399
+ const report = readGeneratedTestReport(path.join(tempRoot, 'jest-results.json'), tempRoot, 'Jest')
400
+ const counts = {
401
+ passedTests: Number(report.numPassedTests ?? 0),
402
+ skippedTests: Number(report.numPendingTests ?? 0),
403
+ todoTests: Number(report.numTodoTests ?? 0),
404
+ expectedFailureTests: 0,
405
+ }
406
+ const assertions = (Array.isArray(report.testResults) ? report.testResults : [])
407
+ .flatMap((suite) => Array.isArray(suite?.assertionResults) ? suite.assertionResults : [])
408
+ if (report.success !== true || Number(report.numFailedTests ?? 0) !== 0 || counts.passedTests < 1
409
+ || counts.skippedTests !== 0 || counts.todoTests !== 0
410
+ || assertions.some((assertion) => assertion?.status !== 'passed')) {
411
+ throw new Error('generated Jest report must contain at least one passing test and zero failed, skipped, todo, or expected-failure tests')
412
+ }
413
+ return counts
414
+ }
415
+ const report = readGeneratedTestReport(path.join(tempRoot, 'playwright-results.json'), tempRoot, 'Playwright')
416
+ const tests = collectPlaywrightTests(report.suites)
417
+ const skippedTests = tests.filter((test) => test?.expectedStatus === 'skipped' || test?.status === 'skipped').length
418
+ const expectedFailureTests = tests.filter((test) => !['passed', 'skipped'].includes(test?.expectedStatus)).length
419
+ const passedTests = tests.filter((test) => test?.expectedStatus === 'passed' && test?.status === 'expected'
420
+ && Array.isArray(test.results) && test.results.length > 0 && test.results.every((result) => result?.status === 'passed')).length
421
+ const counts = { passedTests, skippedTests, todoTests: 0, expectedFailureTests }
422
+ if (tests.length < 1 || passedTests !== tests.length || skippedTests !== 0 || expectedFailureTests !== 0
423
+ || Number(report?.stats?.skipped ?? 0) !== 0 || Number(report?.stats?.unexpected ?? 0) !== 0
424
+ || Number(report?.stats?.flaky ?? 0) !== 0 || (Array.isArray(report?.errors) && report.errors.length > 0)) {
425
+ throw new Error('generated Playwright report must contain at least one passing test and zero skipped, focused, flaky, unexpected, or expected-failure tests')
426
+ }
427
+ return counts
428
+ }
429
+
430
+ function resolveTargetTestCli(target, runner) {
431
+ const dependencyRoot = fs.realpathSync(path.join(target, 'node_modules'))
432
+ const requireFromTarget = createRequire(path.join(target, 'package.json'))
433
+ const cli = runner === 'jest'
434
+ ? path.join(path.dirname(requireFromTarget.resolve('jest/package.json')), 'bin', 'jest.js')
435
+ : requireFromTarget.resolve('@playwright/test/cli')
436
+ const realCli = fs.realpathSync(cli)
437
+ const stat = fs.lstatSync(cli)
438
+ if (!isPathInside(dependencyRoot, realCli) || !stat.isFile() || stat.isSymbolicLink()) {
439
+ throw new Error(`${runner} CLI must be a regular file in the protected target dependency tree`)
440
+ }
441
+ return realCli
442
+ }
443
+
444
+ function resolveBrowserRuntime(target, isolatedCache) {
445
+ const dependencyRoot = fs.realpathSync(path.join(target, 'node_modules'))
446
+ const requireFromTarget = createRequire(path.join(target, 'package.json'))
447
+ const playwrightCoreEntry = fs.realpathSync(requireFromTarget.resolve('playwright-core'))
448
+ if (!isPathInside(dependencyRoot, playwrightCoreEntry)) throw new Error('playwright-core must resolve from the protected target dependency tree')
449
+ let playwrightCoreRoot = path.dirname(playwrightCoreEntry)
450
+ while (path.dirname(playwrightCoreRoot) !== playwrightCoreRoot && path.basename(playwrightCoreRoot) !== 'playwright-core') playwrightCoreRoot = path.dirname(playwrightCoreRoot)
451
+ const browsersFile = path.join(playwrightCoreRoot, 'browsers.json')
452
+ const browsersStat = fs.lstatSync(browsersFile)
453
+ if (!browsersStat.isFile() || browsersStat.isSymbolicLink() || browsersStat.size > 262_144) throw new Error('playwright-core browsers.json is unsafe')
454
+ const browserDeclaration = readJson(browsersFile)?.browsers?.find((entry) => entry.name === 'chromium-headless-shell')
455
+ if (!/^[0-9]+$/.test(browserDeclaration?.revision ?? '')) throw new Error('Playwright does not declare a bounded Chromium headless-shell revision')
456
+ const chromiumExecutable = requireFromTarget('@playwright/test').chromium.executablePath()
457
+ let chromiumRoot = path.dirname(fs.realpathSync(chromiumExecutable))
458
+ while (path.dirname(chromiumRoot) !== chromiumRoot && !/^chromium-[0-9]+$/.test(path.basename(chromiumRoot))) chromiumRoot = path.dirname(chromiumRoot)
459
+ if (!/^chromium-[0-9]+$/.test(path.basename(chromiumRoot))) throw new Error('the Playwright browser cache root could not be bounded')
460
+ const browserRoot = path.join(path.dirname(chromiumRoot), `chromium_headless_shell-${browserDeclaration.revision}`)
461
+ const browserStat = fs.lstatSync(browserRoot)
462
+ if (!browserStat.isDirectory() || browserStat.isSymbolicLink()) throw new Error('the exact Playwright Chromium headless-shell runtime is unavailable')
463
+ const marker = path.join(browserRoot, 'INSTALLATION_COMPLETE')
464
+ if (!fs.lstatSync(marker).isFile()) throw new Error('the Playwright Chromium headless-shell runtime is incomplete')
465
+ const executableNames = new Set(process.platform === 'win32' ? ['headless_shell.exe'] : ['chrome-headless-shell', 'headless_shell'])
466
+ const executables = []
467
+ const visit = (directory) => {
468
+ for (const name of fs.readdirSync(directory)) {
469
+ const child = path.join(directory, name)
470
+ const entry = fs.lstatSync(child)
471
+ if (entry.isSymbolicLink() || (!entry.isDirectory() && !entry.isFile())) throw new Error('the Playwright Chromium headless-shell runtime contains an unsafe entry')
472
+ if (entry.isDirectory()) visit(child)
473
+ else if (executableNames.has(name)) executables.push(child)
474
+ }
475
+ }
476
+ visit(browserRoot)
477
+ if (executables.length !== 1) throw new Error('the Playwright Chromium headless-shell executable could not be identified exactly')
478
+ const cacheLink = path.join(isolatedCache, path.basename(browserRoot))
479
+ fs.symlinkSync(browserRoot, cacheLink, process.platform === 'win32' ? 'junction' : 'dir')
480
+ return { browserRoot: fs.realpathSync(browserRoot), isolatedCache, executable: fs.realpathSync(executables[0]) }
481
+ }
482
+
483
+ export function buildReleasePlan({ cases, registry, releaseMatrix, fixtures, seeds, targetsManifest, root, primaryRunner, portabilityRunner, targetsMayNotExist = false }) {
484
+ const allCaseIds = cases.map((item) => item.id)
485
+ const writableCases = cases.filter((item) => WRITABLE_KINDS.has(item.evaluationKind))
486
+ const writableCaseIds = writableCases.map((item) => item.id)
487
+ const reviewEligibleCaseIds = [...writableCaseIds]
488
+ const violations = []
489
+ const release = releaseMatrix?.releaseSuite ?? {}
490
+ const deterministicIds = resolveCaseSelector(releaseMatrix?.deterministic?.caseIds, allCaseIds)
491
+ const deterministicMissingCaseIds = difference(allCaseIds, deterministicIds)
492
+ const deterministicUnexpectedCaseIds = difference(deterministicIds, allCaseIds)
493
+ addCoverageViolation(violations, 'deterministic matrix is missing cases', deterministicMissingCaseIds)
494
+ addCoverageViolation(violations, 'deterministic matrix contains unknown cases', deterministicUnexpectedCaseIds)
495
+ if (releaseMatrix?.deterministic?.caseIds !== 'all') violations.push('deterministic matrix must use the exact all-cases selector')
496
+
497
+ const supportedRunners = Array.isArray(release.supportedRunners) ? release.supportedRunners : []
498
+ if (JSON.stringify(supportedRunners) !== JSON.stringify(RELEASE_SUPPORTED_RUNNERS)) {
499
+ violations.push(`release supported runners must be exactly: ${RELEASE_SUPPORTED_RUNNERS.join(', ')}`)
500
+ }
501
+ if (!RUNNERS.has(primaryRunner)) violations.push('release requires one valid primary runner')
502
+ if (portabilityRunner !== undefined && !RUNNERS.has(portabilityRunner)) violations.push('release portability runner is invalid')
503
+ if (portabilityRunner !== undefined && portabilityRunner === primaryRunner) violations.push('release portability runner must differ from the primary runner')
504
+ const configuredRunnerNames = Object.keys(releaseMatrix?.routing?.runners ?? {})
505
+ if (JSON.stringify(configuredRunnerNames) !== JSON.stringify(RELEASE_SUPPORTED_RUNNERS)) {
506
+ violations.push(`routing matrix must configure exactly: ${RELEASE_SUPPORTED_RUNNERS.join(', ')}`)
507
+ }
508
+ for (const runner of RELEASE_SUPPORTED_RUNNERS) {
509
+ if (!validModelSelector(releaseMatrix?.routing?.runners?.[runner]?.modelSelector)) violations.push(`routing matrix lacks a valid bounded ${runner} model selector`)
510
+ }
511
+ const requiredCaseIds = resolveCaseSelector(releaseMatrix?.routing?.required?.caseIds, allCaseIds)
512
+ const requiredUnknownCaseIds = difference(requiredCaseIds, allCaseIds)
513
+ addCoverageViolation(violations, 'primary routing matrix contains unknown cases', requiredUnknownCaseIds)
514
+ if (releaseMatrix?.routing?.required?.caseIds !== 'all') violations.push('primary routing matrix must use the exact all-cases selector')
515
+ const portabilityCaseIds = resolveCaseSelector(releaseMatrix?.routing?.portability?.caseIds, allCaseIds)
516
+ const portabilityUnknownCaseIds = difference(portabilityCaseIds, allCaseIds)
517
+ addCoverageViolation(violations, 'portability routing matrix contains unknown cases', portabilityUnknownCaseIds)
518
+ if (JSON.stringify(portabilityCaseIds) !== JSON.stringify(writableCaseIds)) {
519
+ violations.push('portability routing matrix must match the exact writable case set in catalog order')
520
+ }
521
+ const routing = []
522
+ if (RUNNERS.has(primaryRunner)) routing.push({ lane: 'primary', runner: primaryRunner, expectedCaseIds: requiredCaseIds, unknownCaseIds: requiredUnknownCaseIds })
523
+ if (RUNNERS.has(portabilityRunner) && portabilityRunner !== primaryRunner) {
524
+ routing.push({ lane: 'portability', runner: portabilityRunner, expectedCaseIds: portabilityCaseIds, unknownCaseIds: portabilityUnknownCaseIds })
525
+ }
526
+
527
+ const writableEntries = Array.isArray(releaseMatrix?.writable) ? releaseMatrix.writable : []
528
+ const assignedWritableIds = writableEntries.map((entry) => entry?.caseId)
529
+ const missingWritableMatrixCaseIds = difference(writableCaseIds, assignedWritableIds)
530
+ const unexpectedWritableMatrixCaseIds = difference(assignedWritableIds, writableCaseIds)
531
+ const duplicateWritableMatrixCaseIds = duplicates(assignedWritableIds)
532
+ addCoverageViolation(violations, 'writable release matrix is missing cases', missingWritableMatrixCaseIds)
533
+ addCoverageViolation(violations, 'writable release matrix contains non-writable cases', unexpectedWritableMatrixCaseIds)
534
+ addCoverageViolation(violations, 'writable release matrix contains duplicate cases', duplicateWritableMatrixCaseIds)
535
+ for (const entry of writableEntries) {
536
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry) || Object.keys(entry).length !== 1 || typeof entry.caseId !== 'string') violations.push(`writable release assignment must be runner-neutral: ${String(entry?.caseId)}`)
537
+ }
538
+
539
+ const configuredReviewIds = Array.isArray(releaseMatrix?.generatedCodeReview?.caseIds)
540
+ ? releaseMatrix.generatedCodeReview.caseIds
541
+ : []
542
+ const missingReviewMatrixCaseIds = difference(reviewEligibleCaseIds, configuredReviewIds)
543
+ const unexpectedReviewMatrixCaseIds = difference(configuredReviewIds, reviewEligibleCaseIds)
544
+ const duplicateReviewMatrixCaseIds = duplicates(configuredReviewIds)
545
+ addCoverageViolation(violations, 'generated-code review matrix is missing eligible cases', missingReviewMatrixCaseIds)
546
+ addCoverageViolation(violations, 'generated-code review matrix contains ineligible cases', unexpectedReviewMatrixCaseIds)
547
+ addCoverageViolation(violations, 'generated-code review matrix contains duplicate cases', duplicateReviewMatrixCaseIds)
548
+ if (JSON.stringify(configuredReviewIds) !== JSON.stringify(reviewEligibleCaseIds)) {
549
+ violations.push('generated-code review matrix must list every writable case exactly once in catalog order')
550
+ }
551
+ if (release.requireGeneratedCodeReview !== true) violations.push('release suite must require generated-code review')
552
+ if (releaseMatrix?.generatedCodeReview?.skill !== 'om-code-review') violations.push('generated-code review must explicitly use om-code-review')
553
+ if (releaseMatrix?.generatedCodeReview?.required !== true) violations.push('generated-code review must be mandatory for every writable case')
554
+ const reviewRunners = releaseMatrix?.generatedCodeReview?.runners ?? {}
555
+ for (const runner of RELEASE_SUPPORTED_RUNNERS) {
556
+ if (!validModelSelector(reviewRunners?.[runner]?.modelSelector)) violations.push(`generated-code review lacks a valid bounded ${runner} model selector`)
557
+ }
558
+ for (const runner of Object.keys(reviewRunners)) {
559
+ if (!RUNNERS.has(runner)) violations.push(`generated-code review declares an invalid runner: ${runner}`)
560
+ }
561
+ const reviewSkillFiles = [
562
+ '.agents/skills/om-code-review/SKILL.md',
563
+ '.agents/skills/om-code-review/references/agentic-setup.md',
564
+ '.agents/skills/om-code-review/references/output-format.md',
565
+ '.agents/skills/om-code-review/references/review-checklist.md',
566
+ '.agents/skills/om-code-review/references/rules.md',
567
+ '.agents/skills/.om-external-ownership.json',
568
+ ]
569
+ const reviewSkillReady = !root || reviewSkillFiles.every((relative) => fs.existsSync(path.join(root, relative)))
570
+ if (!reviewSkillReady) violations.push('generated-code review skill is not installed with ownership evidence')
571
+
572
+ const registryCaseCountMatches = registry?.catalog?.expectedCaseCount === cases.length
573
+ if (!registryCaseCountMatches) violations.push(`validator registry expects ${String(registry?.catalog?.expectedCaseCount)} cases but catalog contains ${cases.length}`)
574
+ const registryWritableIds = Array.isArray(registry?.catalog?.writableCaseIds) ? registry.catalog.writableCaseIds : []
575
+ const registryMissingWritableCaseIds = difference(writableCaseIds, registryWritableIds)
576
+ const registryUnexpectedWritableCaseIds = difference(registryWritableIds, writableCaseIds)
577
+ addCoverageViolation(violations, 'validator registry is missing writable cases', registryMissingWritableCaseIds)
578
+ addCoverageViolation(violations, 'validator registry contains non-writable cases', registryUnexpectedWritableCaseIds)
579
+
580
+ const missingFixtureCaseIds = []
581
+ const missingOracleCaseIds = []
582
+ for (const item of writableCases) {
583
+ const setupEntries = Array.isArray(item.fixture?.setup) ? item.fixture.setup : []
584
+ const setupIds = setupEntries
585
+ .filter((entry) => typeof entry === 'string' && /^fixture:[a-z0-9-]+$/.test(entry))
586
+ .map((entry) => entry.slice('fixture:'.length))
587
+ const fixtureComplete = item.fixture?.scaffold === 'fresh-standalone'
588
+ && setupIds.length > 0
589
+ && setupIds.length === setupEntries.length
590
+ && setupIds.every((id) => fixtures?.fixtures?.[id] && seeds?.fixtures?.[id])
591
+ if (!fixtureComplete) missingFixtureCaseIds.push(item.id)
592
+ const oracleIds = Array.isArray(item.oracle?.validatorIds) ? item.oracle.validatorIds : []
593
+ const oracleComplete = oracleIds.some((id) => {
594
+ const declaration = registry?.validators?.[id]
595
+ return declaration?.implementation === 'trusted-executable' && Array.isArray(declaration.runners) && declaration.runners.length > 0
596
+ }) && Array.isArray(item.oracle?.expectedArtifacts) && item.oracle.expectedArtifacts.length > 0
597
+ if (!oracleComplete) missingOracleCaseIds.push(item.id)
598
+ }
599
+ addCoverageViolation(violations, 'writable cases lack complete fixture coverage', missingFixtureCaseIds)
600
+ addCoverageViolation(violations, 'writable cases lack trusted oracle coverage', missingOracleCaseIds)
601
+
602
+ const targetEntries = validTargetsManifest(targetsManifest) ? targetsManifest.targets : {}
603
+ if (!validTargetsManifest(targetsManifest)) violations.push('writable target manifest must use schemaVersion 1 and a targets object')
604
+ const targetIds = Object.keys(targetEntries)
605
+ const missingTargetCaseIds = writableCaseIds.filter((id) => typeof targetEntries[id] !== 'string' || !path.isAbsolute(targetEntries[id]))
606
+ const unexpectedTargetCaseIds = difference(targetIds, writableCaseIds)
607
+ const duplicateTargetCaseIds = []
608
+ const invalidTargetCaseIds = []
609
+ const targetOwners = new Map()
610
+ const controllerRoot = root ? fs.realpathSync(root) : undefined
611
+ for (const id of writableCaseIds) {
612
+ const target = targetEntries[id]
613
+ if (typeof target !== 'string' || !path.isAbsolute(target)) continue
614
+ let normalized = path.resolve(target)
615
+ if (root && !targetsMayNotExist) {
616
+ try {
617
+ const stat = fs.lstatSync(target)
618
+ normalized = fs.realpathSync(target)
619
+ const required = ['package.json', 'src/modules.ts', '.ai/harness/cases.json']
620
+ const requiredAreSafe = required.every((relative) => {
621
+ const absolute = path.join(normalized, relative)
622
+ try {
623
+ const entry = fs.lstatSync(absolute)
624
+ return entry.isFile() && !entry.isSymbolicLink() && isPathInside(normalized, fs.realpathSync(absolute))
625
+ } catch { return false }
626
+ })
627
+ const dependencyPath = path.join(normalized, 'node_modules')
628
+ let dependenciesAreSafe = false
629
+ try {
630
+ const dependencyEntry = fs.lstatSync(dependencyPath)
631
+ dependenciesAreSafe = dependencyEntry.isSymbolicLink()
632
+ && fs.statSync(dependencyPath).isDirectory()
633
+ && root
634
+ && fs.realpathSync(dependencyPath) === fs.realpathSync(path.join(root, 'node_modules'))
635
+ } catch { /* invalid target below */ }
636
+ if (!stat.isDirectory() || stat.isSymbolicLink() || normalized === root
637
+ || !requiredAreSafe || !dependenciesAreSafe
638
+ || fs.existsSync(path.join(normalized, '.ai', 'harness', 'DISPOSABLE'))) invalidTargetCaseIds.push(id)
639
+ } catch { invalidTargetCaseIds.push(id) }
640
+ }
641
+ if (controllerRoot && (isPathInside(controllerRoot, normalized) || isPathInside(normalized, controllerRoot))) invalidTargetCaseIds.push(id)
642
+ for (const [ownedRoot, ownerId] of targetOwners) {
643
+ if (isPathInside(ownedRoot, normalized) || isPathInside(normalized, ownedRoot)) duplicateTargetCaseIds.push(id, ownerId)
644
+ }
645
+ targetOwners.set(normalized, id)
646
+ }
647
+ addCoverageViolation(violations, 'writable target manifest is missing absolute targets', sortedUnique(missingTargetCaseIds))
648
+ addCoverageViolation(violations, 'writable target manifest contains unknown cases', unexpectedTargetCaseIds)
649
+ addCoverageViolation(violations, 'writable target manifest reuses targets', sortedUnique(duplicateTargetCaseIds))
650
+ addCoverageViolation(violations, 'writable target manifest contains invalid or reused app roots', sortedUnique(invalidTargetCaseIds))
651
+
652
+ const validationCommands = Array.isArray(release.validationCommands) ? release.validationCommands : []
653
+ if (validationCommands.length === 0) violations.push('release suite must declare validation commands')
654
+ for (const command of validationCommands) {
655
+ if (!ALLOWED_VALIDATION_COMMANDS.has(command)) violations.push(`release validation command is not allowed: ${String(command)}`)
656
+ }
657
+ const missingValidationCommands = difference([...ALLOWED_VALIDATION_COMMANDS], validationCommands)
658
+ addCoverageViolation(violations, 'release suite is missing validation commands', missingValidationCommands)
659
+ if (JSON.stringify(validationCommands) !== JSON.stringify(RELEASE_VALIDATION_COMMANDS)) {
660
+ violations.push('release validation commands must be the exact ordered four-command gate')
661
+ }
662
+
663
+ const generatedTestCases = writableCases.filter((item) => item.tags?.some((tag) => ['unit-tests', 'api-tests', 'browser-tests'].includes(tag)))
664
+ const expectedGeneratedTestIds = generatedTestCases.map((item) => item.id)
665
+ const generatedTestEntries = Array.isArray(releaseMatrix?.generatedTests?.entries) ? releaseMatrix.generatedTests.entries : []
666
+ const configuredGeneratedTestIds = generatedTestEntries.map((entry) => entry.caseId)
667
+ const missingGeneratedTestIds = difference(expectedGeneratedTestIds, configuredGeneratedTestIds)
668
+ const unexpectedGeneratedTestIds = difference(configuredGeneratedTestIds, expectedGeneratedTestIds)
669
+ const duplicateGeneratedTestIds = duplicates(configuredGeneratedTestIds)
670
+ if (releaseMatrix?.generatedTests?.required !== true) violations.push('generated test execution must be required')
671
+ addCoverageViolation(violations, 'generated test execution matrix is missing cases', missingGeneratedTestIds)
672
+ addCoverageViolation(violations, 'generated test execution matrix contains ineligible cases', unexpectedGeneratedTestIds)
673
+ addCoverageViolation(violations, 'generated test execution matrix contains duplicate cases', duplicateGeneratedTestIds)
674
+ for (const entry of generatedTestEntries) {
675
+ const item = generatedTestCases.find((candidate) => candidate.id === entry.caseId)
676
+ const expectedRunner = item?.tags?.includes('unit-tests') ? 'jest'
677
+ : item?.tags?.includes('api-tests') ? 'playwright-api'
678
+ : item?.tags?.includes('browser-tests') ? 'playwright-browser' : undefined
679
+ const expectedNetwork = expectedRunner === 'jest' ? 'none' : 'loopback'
680
+ const canonicalPath = expectedRunner === 'jest'
681
+ ? /^src\/modules\/[a-z0-9_]+\/(?:[^/]+\/)*__tests__\/[A-Za-z0-9._-]+\.(?:test|spec)\.tsx?$/
682
+ : /^src\/modules\/[a-z0-9_]+\/(?:[^/]+\/)*__integration__\/[A-Za-z0-9._-]+\.spec\.tsx?$/
683
+ if (!item || !GENERATED_TEST_RUNNERS.has(entry.runner) || entry.runner !== expectedRunner
684
+ || entry.network !== expectedNetwork || typeof entry.artifact !== 'string'
685
+ || !canonicalPath.test(entry.artifact) || !item.oracle?.expectedArtifacts?.includes(entry.artifact)
686
+ || !item.allowedWrites?.includes(entry.artifact)) {
687
+ violations.push(`generated test execution assignment is invalid: ${String(entry.caseId)}`)
688
+ }
689
+ }
690
+
691
+ const steps = [
692
+ { id: 'deterministic:all', kind: 'deterministic', expectedCaseIds: deterministicIds },
693
+ ...validationCommands.map((command) => ({ id: `validation:${command.slice('yarn '.length)}`, kind: 'validation', command })),
694
+ ...routing.map((entry) => ({ id: `routing:${entry.lane}:${entry.runner}`, kind: 'routing', lane: entry.lane, runner: entry.runner, modelSelector: releaseMatrix.routing.runners[entry.runner].modelSelector, expectedCaseIds: entry.expectedCaseIds })),
695
+ ]
696
+ for (const caseId of writableCaseIds) {
697
+ const assignment = writableEntries.find((entry) => entry?.caseId === caseId)
698
+ if (!assignment || !RUNNERS.has(primaryRunner)) continue
699
+ steps.push({ id: `fixture:${caseId}`, kind: 'fixture', caseId })
700
+ steps.push({ id: `writable:${caseId}`, kind: 'writable', caseId, runner: primaryRunner, modelSelector: releaseMatrix.routing.runners[primaryRunner].modelSelector })
701
+ for (const command of validationCommands) {
702
+ steps.push({ id: `target-validation:${caseId}:${command.slice('yarn '.length)}`, kind: 'target-validation', caseId, command })
703
+ }
704
+ const generatedTest = generatedTestEntries.find((entry) => entry.caseId === caseId)
705
+ if (generatedTest) {
706
+ const executionContract = generatedTestExecutionContract(generatedTest)
707
+ steps.push({
708
+ id: `generated-test:${caseId}:${generatedTest.runner}`,
709
+ kind: 'generated-test',
710
+ caseId,
711
+ testRunner: generatedTest.runner,
712
+ artifact: generatedTest.artifact,
713
+ network: generatedTest.network,
714
+ ...executionContract,
715
+ })
716
+ }
717
+ if (configuredReviewIds.includes(caseId)) {
718
+ const modelSelector = releaseMatrix.generatedCodeReview?.runners?.[primaryRunner]?.modelSelector
719
+ if (!validModelSelector(modelSelector)) violations.push(`generated-code review lacks a valid bounded ${primaryRunner} model selector for ${caseId}`)
720
+ steps.push({ id: `review:${caseId}`, kind: 'review', caseId, runner: primaryRunner, modelSelector })
721
+ }
722
+ }
723
+
724
+ return {
725
+ runnerPolicy: { primaryRunner: RUNNERS.has(primaryRunner) ? primaryRunner : null, portabilityRunner: RUNNERS.has(portabilityRunner) ? portabilityRunner : null },
726
+ catalog: {
727
+ caseCount: cases.length,
728
+ writableCaseCount: writableCaseIds.length,
729
+ reviewEligibleCaseCount: reviewEligibleCaseIds.length,
730
+ },
731
+ coverage: {
732
+ deterministic: { expectedCaseIds: allCaseIds, configuredCaseIds: deterministicIds, missingMatrixCaseIds: deterministicMissingCaseIds, unexpectedMatrixCaseIds: deterministicUnexpectedCaseIds },
733
+ routing,
734
+ writable: {
735
+ expectedCaseIds: writableCaseIds,
736
+ configuredCaseIds: assignedWritableIds,
737
+ missingMatrixCaseIds: missingWritableMatrixCaseIds,
738
+ unexpectedMatrixCaseIds: unexpectedWritableMatrixCaseIds,
739
+ duplicateMatrixCaseIds: duplicateWritableMatrixCaseIds,
740
+ missingTargetCaseIds: sortedUnique(missingTargetCaseIds),
741
+ unexpectedTargetCaseIds,
742
+ duplicateTargetCaseIds: sortedUnique(duplicateTargetCaseIds),
743
+ invalidTargetCaseIds: sortedUnique(invalidTargetCaseIds),
744
+ missingFixtureCaseIds: sortedUnique(missingFixtureCaseIds),
745
+ missingOracleCaseIds: sortedUnique(missingOracleCaseIds),
746
+ },
747
+ review: { expectedCaseIds: reviewEligibleCaseIds, configuredCaseIds: configuredReviewIds, missingMatrixCaseIds: missingReviewMatrixCaseIds, unexpectedMatrixCaseIds: unexpectedReviewMatrixCaseIds, skillReady: reviewSkillReady },
748
+ registry: { caseCountMatches: registryCaseCountMatches, missingWritableCaseIds: registryMissingWritableCaseIds, unexpectedWritableCaseIds: registryUnexpectedWritableCaseIds },
749
+ validation: { expectedCommands: [...ALLOWED_VALIDATION_COMMANDS], configuredCommands: validationCommands, missingCommands: missingValidationCommands },
750
+ targetValidation: { expectedCaseIds: writableCaseIds, commands: validationCommands },
751
+ generatedTests: {
752
+ expectedCaseIds: expectedGeneratedTestIds,
753
+ configuredCaseIds: configuredGeneratedTestIds,
754
+ missingMatrixCaseIds: missingGeneratedTestIds,
755
+ unexpectedMatrixCaseIds: unexpectedGeneratedTestIds,
756
+ duplicateMatrixCaseIds: duplicateGeneratedTestIds,
757
+ },
758
+ },
759
+ targets: targetEntries,
760
+ steps,
761
+ violations: sortedUnique(violations),
762
+ }
763
+ }
764
+
765
+ export function releaseHostPrerequisiteViolations(releaseMatrix, platform = process.platform, env = process.env) {
766
+ const entries = Array.isArray(releaseMatrix?.generatedTests?.entries) ? releaseMatrix.generatedTests.entries : []
767
+ const requiresLoopback = entries.some((entry) => entry?.network === 'loopback')
768
+ const modes = ['none', ...(requiresLoopback ? ['loopback'] : [])]
769
+ const violations = []
770
+ for (const mode of modes) {
771
+ try {
772
+ assertSandboxRuntimeAvailable(mode, platform, env)
773
+ } catch (error) {
774
+ violations.push(error instanceof Error ? error.message : String(error))
775
+ }
776
+ }
777
+ if (platform === 'linux' && requiresLoopback && violations.length === 0) {
778
+ try {
779
+ verifyLinuxSandboxIsolation(env)
780
+ } catch (error) {
781
+ violations.push(error instanceof Error ? error.message : String(error))
782
+ }
783
+ }
784
+ return [...new Set(violations)]
785
+ }
786
+
787
+ function percentage(numerator, denominator) {
788
+ return denominator === 0 ? 0 : Math.round((numerator / denominator) * 10_000) / 100
789
+ }
790
+
791
+ function percentile(values, value) {
792
+ if (values.length === 0) return 0
793
+ const sorted = [...values].sort((left, right) => left - right)
794
+ return sorted[Math.min(sorted.length - 1, Math.ceil(sorted.length * value) - 1)]
795
+ }
796
+
797
+ function violationCategory(value) {
798
+ const text = String(value)
799
+ if (/forbidden|unsafe|out-of-root|outside allowlist|protected roots|inspection|modified (?:target|bundle)|trace unavailable|no observed context/i.test(text)) return 'safety'
800
+ if (/route|skill|context|decision|pattern|budget|missing|required|unexpected|mismatch/i.test(text)) return 'contract'
801
+ if (/process|environment|structured output|timed out|runner/i.test(text)) return 'execution'
802
+ return 'quality'
803
+ }
804
+
805
+ export function aggregateQualityMetrics(results) {
806
+ const contextTokens = []
807
+ const initialContextTokens = []
808
+ let passed = 0
809
+ let corrections = 0
810
+ let resultsWithCorrections = 0
811
+ let firstPassPassed = 0
812
+ let totalViolations = 0
813
+ let resultsWithViolations = 0
814
+ const violationsByCategory = { safety: 0, contract: 0, execution: 0, quality: 0 }
815
+ const verdicts = { approve: 0, requestChanges: 0, error: 0 }
816
+ for (const result of results) {
817
+ if (result.status === 'pass') passed += 1
818
+ const resultCorrections = Number.isInteger(result.corrections) ? result.corrections : Math.max(0, (result.attempts ?? 1) - 1)
819
+ corrections += resultCorrections
820
+ if (resultCorrections > 0) resultsWithCorrections += 1
821
+ if (result.status === 'pass' && resultCorrections === 0) firstPassPassed += 1
822
+ if (Number.isInteger(result.actualContext?.estimatedTokens)) contextTokens.push(result.actualContext.estimatedTokens)
823
+ if (Number.isInteger(result.actualContext?.estimatedInitialTokens)) initialContextTokens.push(result.actualContext.estimatedInitialTokens)
824
+ const resultViolations = Array.isArray(result.violations) ? result.violations : []
825
+ if (resultViolations.length) resultsWithViolations += 1
826
+ totalViolations += resultViolations.length
827
+ for (const violation of resultViolations) violationsByCategory[violationCategory(violation)] += 1
828
+ if (result.verdict === 'approve') verdicts.approve += 1
829
+ else if (result.verdict === 'request changes') verdicts.requestChanges += 1
830
+ else if (result.verdict === 'error') verdicts.error += 1
831
+ }
832
+ const totalContextTokens = contextTokens.reduce((sum, value) => sum + value, 0)
833
+ const totalInitialContextTokens = initialContextTokens.reduce((sum, value) => sum + value, 0)
834
+ return {
835
+ outcomes: { results: results.length, passed, failed: results.length - passed },
836
+ firstPass: { eligibleResults: results.length, passedFirstPass: firstPassPassed, ratePct: percentage(firstPassPassed, results.length) },
837
+ corrections: { total: corrections, resultsWithCorrections, ratePct: percentage(resultsWithCorrections, results.length) },
838
+ context: {
839
+ measuredResults: contextTokens.length,
840
+ totalEstimatedTokens: totalContextTokens,
841
+ averageEstimatedTokens: contextTokens.length ? Math.round(totalContextTokens / contextTokens.length) : 0,
842
+ p95EstimatedTokens: percentile(contextTokens, 0.95),
843
+ maxEstimatedTokens: contextTokens.length ? Math.max(...contextTokens) : 0,
844
+ totalEstimatedInitialTokens: totalInitialContextTokens,
845
+ averageEstimatedInitialTokens: initialContextTokens.length ? Math.round(totalInitialContextTokens / initialContextTokens.length) : 0,
846
+ },
847
+ misuse: { totalViolations, resultsWithViolations, ratePct: percentage(resultsWithViolations, results.length), byCategory: violationsByCategory },
848
+ reviewVerdicts: verdicts,
849
+ }
850
+ }
851
+
852
+ export function sanitizeReportText(value, roots = []) {
853
+ let result = String(value ?? '')
854
+ for (const root of [...roots, os.homedir()].filter(Boolean).sort((left, right) => right.length - left.length)) result = result.split(root).join('<redacted-path>')
855
+ const environmentSecrets = [...new Set(Object.entries(process.env)
856
+ .filter(([key, entry]) => SENSITIVE_ENV_KEY.test(key) && typeof entry === 'string' && entry.length >= 4)
857
+ .map(([, entry]) => entry))]
858
+ .sort((left, right) => right.length - left.length)
859
+ for (const secret of environmentSecrets) result = result.split(secret).join('<redacted-secret>')
860
+ result = result.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/@]+@/gi, '$1<redacted-secret>@')
861
+ result = result.replace(/\b(?:sk|pk|ghp|github_pat|xox[baprs]|AKIA)[-_A-Za-z0-9]{10,}\b/g, '<redacted-secret>')
862
+ result = result.replace(/\b(?:api[_-]?key|token|secret|password)\s*[:=]\s*[^\s,;]+/gi, '<redacted-secret>')
863
+ return result.slice(0, ERROR_LIMIT)
864
+ }
865
+
866
+ function sanitizeObject(value, roots) {
867
+ if (typeof value === 'string') return sanitizeReportText(value, roots)
868
+ if (Array.isArray(value)) return value.map((entry) => sanitizeObject(entry, roots))
869
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, sanitizeObject(entry, roots)]))
870
+ return value
871
+ }
872
+
873
+ function schemaTypeMatches(value, expected) {
874
+ if (expected === 'null') return value === null
875
+ if (expected === 'array') return Array.isArray(value)
876
+ if (expected === 'object') return value !== null && typeof value === 'object' && !Array.isArray(value)
877
+ if (expected === 'integer') return Number.isInteger(value)
878
+ if (expected === 'number') return typeof value === 'number' && Number.isFinite(value)
879
+ return typeof value === expected
880
+ }
881
+
882
+ function resolveSchemaReference(rootSchema, reference) {
883
+ if (!reference.startsWith('#/')) throw new Error(`unsupported release schema reference ${reference}`)
884
+ return reference.slice(2).split('/').reduce((value, key) => value?.[key.replaceAll('~1', '/').replaceAll('~0', '~')], rootSchema)
885
+ }
886
+
887
+ function validateJsonSchema(value, schema, rootSchema = schema, location = '$') {
888
+ if (schema.$ref) return validateJsonSchema(value, resolveSchemaReference(rootSchema, schema.$ref), rootSchema, location)
889
+ const errors = []
890
+ const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : []
891
+ if (types.length && !types.some((type) => schemaTypeMatches(value, type))) return [`${location} has the wrong type`]
892
+ if (Object.hasOwn(schema, 'const') && value !== schema.const) errors.push(`${location} differs from its constant`)
893
+ if (schema.enum && !schema.enum.some((entry) => JSON.stringify(entry) === JSON.stringify(value))) errors.push(`${location} is outside its enum`)
894
+ if (typeof value === 'string') {
895
+ if (Number.isInteger(schema.maxLength) && value.length > schema.maxLength) errors.push(`${location} exceeds maxLength`)
896
+ if (schema.pattern && !new RegExp(schema.pattern).test(value)) errors.push(`${location} does not match its pattern`)
897
+ }
898
+ if (typeof value === 'number') {
899
+ if (Number.isFinite(schema.minimum) && value < schema.minimum) errors.push(`${location} is below minimum`)
900
+ if (Number.isFinite(schema.maximum) && value > schema.maximum) errors.push(`${location} exceeds maximum`)
901
+ }
902
+ if (Array.isArray(value)) {
903
+ if (Number.isInteger(schema.maxItems) && value.length > schema.maxItems) errors.push(`${location} exceeds maxItems`)
904
+ if (schema.uniqueItems && new Set(value.map((entry) => JSON.stringify(entry))).size !== value.length) errors.push(`${location} must contain unique items`)
905
+ if (schema.items) value.forEach((entry, index) => errors.push(...validateJsonSchema(entry, schema.items, rootSchema, `${location}[${index}]`)))
906
+ }
907
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
908
+ for (const required of schema.required ?? []) if (!Object.hasOwn(value, required)) errors.push(`${location}.${required} is required`)
909
+ if (schema.additionalProperties === false) {
910
+ for (const key of Object.keys(value)) if (!Object.hasOwn(schema.properties ?? {}, key)) errors.push(`${location}.${key} is not allowed`)
911
+ }
912
+ for (const [key, childSchema] of Object.entries(schema.properties ?? {})) {
913
+ if (Object.hasOwn(value, key)) errors.push(...validateJsonSchema(value[key], childSchema, rootSchema, `${location}.${key}`))
914
+ }
915
+ }
916
+ return errors
917
+ }
918
+
919
+ function resultFiles(root) {
920
+ const directory = path.join(root, '.ai', 'harness', 'results')
921
+ if (!fs.existsSync(directory)) return new Set()
922
+ return new Set(fs.readdirSync(directory).filter((file) => file.endsWith('.json')))
923
+ }
924
+
925
+ function readNewResults(root, before) {
926
+ const directory = path.join(root, '.ai', 'harness', 'results')
927
+ if (!fs.existsSync(directory)) return []
928
+ const results = []
929
+ for (const file of fs.readdirSync(directory).filter((entry) => entry.endsWith('.json') && !before.has(entry)).sort()) {
930
+ const absolute = path.join(directory, file)
931
+ const stat = fs.lstatSync(absolute)
932
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > RESULT_LIMIT || file.includes('-release-')) continue
933
+ try { results.push({ path: path.relative(root, absolute).replaceAll(path.sep, '/'), value: readJson(absolute) }) } catch { /* evaluator owns schema validation */ }
934
+ }
935
+ return results
936
+ }
937
+
938
+ function execute(command, args, cwd, timeout, env = process.env) {
939
+ const started = Date.now()
940
+ const result = spawnSync(command, args, { cwd, encoding: 'utf8', timeout, maxBuffer: 8 * 1024 * 1024, env })
941
+ return { ...result, durationMs: Date.now() - started }
942
+ }
943
+
944
+ function protectedTreeFingerprint(target) {
945
+ if (!fs.existsSync(target)) return '<missing>'
946
+ const hash = createHash('sha256')
947
+ const visit = (absolute, relative = '.') => {
948
+ let stat
949
+ try { stat = fs.lstatSync(absolute) } catch { hash.update(`${relative}:<unreadable>\n`); return }
950
+ hash.update(`${relative}:${stat.mode}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}\n`)
951
+ if (stat.isSymbolicLink()) {
952
+ try { hash.update(`link:${fs.readlinkSync(absolute)}\n`) } catch { /* metadata still detects the entry */ }
953
+ return
954
+ }
955
+ if (!stat.isDirectory()) return
956
+ for (const entry of fs.readdirSync(absolute).sort()) visit(path.join(absolute, entry), relative === '.' ? entry : `${relative}/${entry}`)
957
+ }
958
+ visit(target)
959
+ return hash.digest('hex')
960
+ }
961
+
962
+ export function dependencyContentFingerprint(appRoot) {
963
+ const dependencyRoot = path.join(appRoot, 'node_modules')
964
+ const stat = fs.lstatSync(dependencyRoot)
965
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('controller node_modules must remain a regular directory')
966
+ const hash = createHash('sha256')
967
+ const ownershipFiles = ['package.json', 'yarn.lock']
968
+ for (const relative of ownershipFiles) {
969
+ const absolute = path.join(appRoot, relative)
970
+ if (!fs.existsSync(absolute)) continue
971
+ const fileStat = fs.lstatSync(absolute)
972
+ if (!fileStat.isFile() || fileStat.isSymbolicLink() || fileStat.size > 8 * 1024 * 1024) throw new Error(`dependency ownership file is unsafe: ${relative}`)
973
+ hash.update(relative)
974
+ hash.update(fs.readFileSync(absolute))
975
+ }
976
+ let entries = 0
977
+ const visit = (directory, relativeDirectory = '') => {
978
+ for (const name of fs.readdirSync(directory).sort()) {
979
+ entries += 1
980
+ if (entries > 500_000) throw new Error('dependency content fingerprint exceeds its 500000-entry safety bound')
981
+ const absolute = path.join(directory, name)
982
+ const relative = relativeDirectory ? `${relativeDirectory}/${name}` : name
983
+ const entry = fs.lstatSync(absolute)
984
+ hash.update(`${relative}:${entry.mode}:${entry.size}\n`)
985
+ if (entry.isSymbolicLink()) hash.update(`link:${fs.readlinkSync(absolute)}\n`)
986
+ else if (entry.isDirectory()) visit(absolute, relative)
987
+ else if (entry.isFile()) hash.update(fs.readFileSync(absolute))
988
+ else throw new Error(`dependency tree contains an unsupported entry: ${relative}`)
989
+ }
990
+ }
991
+ visit(dependencyRoot)
992
+ return hash.digest('hex')
993
+ }
994
+
995
+ function targetSnapshot(root) {
996
+ const result = new Map()
997
+ const protectedRoots = new Set(['.git', 'node_modules', '.next', 'dist', '.ai/harness/results'])
998
+ const visit = (directory, relativeDirectory = '') => {
999
+ for (const name of fs.readdirSync(directory).sort()) {
1000
+ const relative = relativeDirectory ? `${relativeDirectory}/${name}` : name
1001
+ if ([...protectedRoots].some((entry) => relative === entry || relative.startsWith(`${entry}/`))) continue
1002
+ const absolute = path.join(directory, name)
1003
+ let entry
1004
+ try { entry = fs.lstatSync(absolute) } catch { result.set(relative, '<unreadable>'); continue }
1005
+ if (entry.isSymbolicLink()) {
1006
+ try { result.set(relative, `<symlink:${fs.readlinkSync(absolute)}>`) } catch { result.set(relative, '<symlink:unreadable>') }
1007
+ } else if (entry.isDirectory()) {
1008
+ result.set(relative, `<directory:${entry.mode & 0o777}>`)
1009
+ visit(absolute, relative)
1010
+ }
1011
+ else if (entry.isFile()) {
1012
+ try { result.set(relative, `<file:${entry.mode & 0o777}:${sha256(fs.readFileSync(absolute))}>`) } catch { result.set(relative, '<unreadable>') }
1013
+ } else result.set(relative, `<special:${entry.mode & 0o170000}>`)
1014
+ }
1015
+ }
1016
+ visit(root)
1017
+ for (const relative of ['.git', 'node_modules', '.next', 'dist', '.ai/harness/results']) {
1018
+ result.set(relative, protectedTreeFingerprint(path.join(root, relative)))
1019
+ }
1020
+ return result
1021
+ }
1022
+
1023
+ function containedValidationSymlink(relative, fingerprint, command, after) {
1024
+ if (!validationOutputRoot(relative, command, after)) return false
1025
+ const target = fingerprint.slice('<symlink:'.length, -1)
1026
+ if (!target || path.isAbsolute(target)) return false
1027
+ const resolved = path.normalize(path.join(path.dirname(relative), target))
1028
+ return resolved !== '..' && !resolved.startsWith(`..${path.sep}`) && !path.isAbsolute(resolved)
1029
+ }
1030
+
1031
+ function unsafeChangedTargetEntries(after, changed, command) {
1032
+ const protectedRoots = new Set(['.git', 'node_modules', '.next', 'dist', '.ai/harness/results'])
1033
+ return changed.flatMap((relative) => {
1034
+ if (protectedRoots.has(relative)) return []
1035
+ const fingerprint = after.get(relative)
1036
+ if (typeof fingerprint !== 'string') return []
1037
+ if (fingerprint.startsWith('<symlink:') && !containedValidationSymlink(relative, fingerprint, command, after)) return [`${relative} (symbolic link)`]
1038
+ if (fingerprint.startsWith('<special:')) return [`${relative} (special file)`]
1039
+ if (fingerprint === '<unreadable>') return [`${relative} (unreadable)`]
1040
+ return []
1041
+ })
1042
+ }
1043
+
1044
+ function targetSnapshotFingerprint(snapshot) {
1045
+ const hash = createHash('sha256')
1046
+ for (const [relative, fingerprint] of [...snapshot.entries()].sort(([left], [right]) => left.localeCompare(right))) {
1047
+ hash.update(relative)
1048
+ hash.update('\0')
1049
+ hash.update(fingerprint)
1050
+ hash.update('\0')
1051
+ }
1052
+ return hash.digest('hex')
1053
+ }
1054
+
1055
+ export function targetContentFingerprint(root) {
1056
+ return targetSnapshotFingerprint(targetSnapshot(root))
1057
+ }
1058
+
1059
+ function stepResult(step, execution, artifacts, roots, expectedArtifacts) {
1060
+ const artifactMismatch = Number.isInteger(expectedArtifacts) && artifacts.length !== expectedArtifacts
1061
+ const status = execution.status === 0 && !execution.error && !artifactMismatch ? 'pass' : 'fail'
1062
+ const diagnostic = artifactMismatch
1063
+ ? `expected ${expectedArtifacts} result artifacts, found ${artifacts.length}`
1064
+ : execution.error?.message || (status === 'fail'
1065
+ ? [execution.stderr, execution.stdout].filter(Boolean).join('\n')
1066
+ : execution.stderr)
1067
+ return {
1068
+ id: step.id,
1069
+ kind: step.kind,
1070
+ ...(step.caseId ? { caseId: step.caseId } : {}),
1071
+ ...(step.runner ? { runner: step.runner } : {}),
1072
+ ...(step.testRunner ? { testRunner: step.testRunner } : {}),
1073
+ ...(step.artifact ? { artifact: step.artifact } : {}),
1074
+ ...(step.network ? { network: step.network } : {}),
1075
+ ...(step.executor ? { executor: step.executor } : {}),
1076
+ ...(step.cliPackage ? { cliPackage: step.cliPackage } : {}),
1077
+ ...(step.cliSha256 ? { cliSha256: step.cliSha256 } : {}),
1078
+ ...(step.argv ? { argv: step.argv } : {}),
1079
+ ...(step.command ? { command: step.command } : {}),
1080
+ status,
1081
+ exitStatus: execution.status,
1082
+ durationMs: execution.durationMs,
1083
+ resultPaths: artifacts.map((entry) => entry.path),
1084
+ ...(diagnostic ? { sanitizedError: sanitizeReportText(diagnostic, roots) } : {}),
1085
+ }
1086
+ }
1087
+
1088
+ function skippedStep(step, reason) {
1089
+ return {
1090
+ id: step.id,
1091
+ kind: step.kind,
1092
+ ...(step.caseId ? { caseId: step.caseId } : {}),
1093
+ ...(step.runner ? { runner: step.runner } : {}),
1094
+ ...(step.testRunner ? { testRunner: step.testRunner } : {}),
1095
+ ...(step.artifact ? { artifact: step.artifact } : {}),
1096
+ ...(step.network ? { network: step.network } : {}),
1097
+ ...(step.executor ? { executor: step.executor } : {}),
1098
+ ...(step.cliPackage ? { cliPackage: step.cliPackage } : {}),
1099
+ ...(step.cliSha256 ? { cliSha256: step.cliSha256 } : {}),
1100
+ ...(step.argv ? { argv: step.argv } : {}),
1101
+ ...(step.command ? { command: step.command } : {}),
1102
+ status: 'skipped',
1103
+ exitStatus: null,
1104
+ durationMs: 0,
1105
+ resultPaths: [],
1106
+ sanitizedError: reason,
1107
+ }
1108
+ }
1109
+
1110
+ export function createMinimalValidationEnvironment(tempRoot, pathValue = process.env.PATH ?? '') {
1111
+ const home = path.join(tempRoot, 'home')
1112
+ const temporary = path.join(tempRoot, 'tmp')
1113
+ const cache = path.join(tempRoot, 'cache')
1114
+ for (const directory of [home, temporary, cache]) fs.mkdirSync(directory, { recursive: true, mode: 0o700 })
1115
+ const env = {
1116
+ PATH: pathValue,
1117
+ HOME: home,
1118
+ TMPDIR: temporary,
1119
+ TEMP: temporary,
1120
+ TMP: temporary,
1121
+ XDG_CONFIG_HOME: path.join(home, '.config'),
1122
+ XDG_CACHE_HOME: cache,
1123
+ XDG_DATA_HOME: path.join(home, '.local', 'share'),
1124
+ CI: '1',
1125
+ NO_COLOR: '1',
1126
+ NEXT_TELEMETRY_DISABLED: '1',
1127
+ YARN_ENABLE_TELEMETRY: '0',
1128
+ COREPACK_ENABLE_DOWNLOAD_PROMPT: '0',
1129
+ TZ: 'UTC',
1130
+ __CF_USER_TEXT_ENCODING: '0x1F5:0x0:0x0',
1131
+ }
1132
+ const configuredCorepackHome = process.env.COREPACK_HOME || path.join(os.homedir(), '.cache', 'node', 'corepack')
1133
+ const corepackHome = fs.existsSync(configuredCorepackHome) && fs.statSync(configuredCorepackHome).isDirectory()
1134
+ ? fs.realpathSync(configuredCorepackHome)
1135
+ : undefined
1136
+ if (corepackHome) env.COREPACK_HOME = corepackHome
1137
+ for (const key of ['SystemRoot', 'WINDIR', 'PATHEXT', 'ComSpec']) {
1138
+ if (typeof process.env[key] === 'string') env[key] = process.env[key]
1139
+ }
1140
+ return { env, toolReadRoots: corepackHome ? [corepackHome] : [] }
1141
+ }
1142
+
1143
+ function validationOutputRoot(relative, command, after) {
1144
+ if (
1145
+ relative === '.env'
1146
+ && (command === 'yarn generate' || command === 'yarn build')
1147
+ && after.get('.env') === after.get('.env.example')
1148
+ ) return '.env'
1149
+ return (RELEASE_VALIDATION_OUTPUT_ROOTS.get(command) ?? []).find((root) => relative === root
1150
+ || relative.startsWith(`${root}/`)
1151
+ || (root.startsWith(`${relative}/`) && after.get(relative)?.startsWith('<directory:')))
1152
+ }
1153
+
1154
+ function cloneValidationDependencies(source, destination) {
1155
+ const sourceRoot = fs.realpathSync(source)
1156
+ const visit = (directory) => {
1157
+ for (const name of fs.readdirSync(directory)) {
1158
+ const absolute = path.join(directory, name)
1159
+ const entry = fs.lstatSync(absolute)
1160
+ if (entry.isSymbolicLink()) {
1161
+ const resolved = fs.realpathSync(absolute)
1162
+ if (resolved !== sourceRoot && !isPathInside(sourceRoot, resolved)) {
1163
+ throw new Error(`dependency tree contains an escaping symbolic link: ${path.relative(sourceRoot, absolute)}`)
1164
+ }
1165
+ } else if (entry.isDirectory()) visit(absolute)
1166
+ else if (!entry.isFile()) throw new Error(`dependency tree contains an unsupported entry: ${path.relative(sourceRoot, absolute)}`)
1167
+ }
1168
+ }
1169
+ visit(sourceRoot)
1170
+ fs.cpSync(sourceRoot, destination, {
1171
+ recursive: true,
1172
+ dereference: false,
1173
+ verbatimSymlinks: true,
1174
+ mode: fs.constants.COPYFILE_FICLONE,
1175
+ })
1176
+ }
1177
+
1178
+ function prepareValidationWorkspace(target, tempRoot, { allowContainedDependencies = false } = {}) {
1179
+ validateScaffoldCopySource(target)
1180
+ const workspace = path.join(tempRoot, 'target')
1181
+ copyFreshScaffold(target, workspace)
1182
+ const dependencyPath = path.join(target, 'node_modules')
1183
+ let dependencyRoot
1184
+ if (fs.existsSync(dependencyPath)) {
1185
+ const sourceDependencyRoot = fs.realpathSync(dependencyPath)
1186
+ if (!allowContainedDependencies && isPathInside(fs.realpathSync(target), sourceDependencyRoot)) {
1187
+ throw new Error('writable target node_modules must resolve outside the writable target')
1188
+ }
1189
+ cloneValidationDependencies(sourceDependencyRoot, path.join(workspace, 'node_modules'))
1190
+ dependencyRoot = fs.realpathSync(path.join(workspace, 'node_modules'))
1191
+ }
1192
+ return { workspace: fs.realpathSync(workspace), dependencyRoot }
1193
+ }
1194
+
1195
+ export function runTargetValidationSteps({ steps, target, timeout, roots, yarnCommand = process.platform === 'win32' ? 'yarn.cmd' : 'yarn', pathValue, allowContainedDependencies = false }) {
1196
+ const results = []
1197
+ const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'om-harness-validation-'))
1198
+ const reportRoots = [...roots, tempRoot, fs.realpathSync(tempRoot)]
1199
+ const { env, toolReadRoots } = createMinimalValidationEnvironment(tempRoot, pathValue)
1200
+ const originalFingerprint = targetContentFingerprint(target)
1201
+ let workspace
1202
+ let dependencyRoot
1203
+ let workspaceError
1204
+ try {
1205
+ ({ workspace, dependencyRoot } = prepareValidationWorkspace(target, tempRoot, { allowContainedDependencies }))
1206
+ } catch (error) {
1207
+ workspaceError = error
1208
+ }
1209
+ let before = workspace ? targetSnapshot(workspace) : new Map()
1210
+ let workspaceTainted = false
1211
+ try {
1212
+ for (const step of steps) {
1213
+ if (workspaceTainted) {
1214
+ results.push(skippedStep(step, 'validation workspace was tainted by an out-of-contract mutation'))
1215
+ continue
1216
+ }
1217
+ let execution
1218
+ if (workspaceError) {
1219
+ execution = { status: null, error: workspaceError, stdout: '', stderr: '', durationMs: 0 }
1220
+ } else try {
1221
+ const readOnlyRoots = [...toolReadRoots]
1222
+ if (dependencyRoot) readOnlyRoots.unshift(dependencyRoot)
1223
+ const invocation = sandboxedInvocation({
1224
+ command: yarnCommand,
1225
+ args: [step.command.slice('yarn '.length)],
1226
+ cwd: workspace,
1227
+ writableRoots: [workspace, tempRoot],
1228
+ readOnlyRoots,
1229
+ networkMode: 'none',
1230
+ env,
1231
+ })
1232
+ execution = execute(invocation.command, invocation.args, invocation.cwd, timeout, invocation.env)
1233
+ } catch (error) {
1234
+ execution = { status: null, error, stdout: '', stderr: '', durationMs: 0 }
1235
+ }
1236
+ const after = workspace ? targetSnapshot(workspace) : before
1237
+ const changed = [...new Set([...before.keys(), ...after.keys()])].filter((key) => before.get(key) !== after.get(key)).sort()
1238
+ const unsafeEntries = unsafeChangedTargetEntries(after, changed, step.command)
1239
+ const disallowedEntries = changed.filter((relative) => !validationOutputRoot(relative, step.command, after))
1240
+ const touchedOutputRoots = [...new Set(changed.map((relative) => validationOutputRoot(relative, step.command, after)).filter(Boolean))].sort()
1241
+ const result = stepResult(step, execution, [], reportRoots)
1242
+ result.resultPaths = touchedOutputRoots
1243
+ if (disallowedEntries.length || unsafeEntries.length) {
1244
+ result.status = 'fail'
1245
+ const diagnostics = [
1246
+ ...(disallowedEntries.length ? [`validation mutated paths outside explicit command outputs: ${disallowedEntries.join(', ')}`] : []),
1247
+ ...(unsafeEntries.length ? [`validation created unsafe filesystem entries: ${unsafeEntries.join(', ')}`] : []),
1248
+ ]
1249
+ result.sanitizedError = sanitizeReportText(diagnostics.join('; '), reportRoots)
1250
+ workspaceTainted = true
1251
+ }
1252
+ if (targetContentFingerprint(target) !== originalFingerprint) {
1253
+ result.status = 'fail'
1254
+ result.sanitizedError = sanitizeReportText('original writable target changed during isolated validation', roots)
1255
+ workspaceTainted = true
1256
+ }
1257
+ results.push(result)
1258
+ before = after
1259
+ }
1260
+ return results
1261
+ } finally {
1262
+ fs.rmSync(tempRoot, { recursive: true, force: true })
1263
+ }
1264
+ }
1265
+
1266
+ export function runGeneratedTestStep({ step, target, timeout, roots, browserRuntimeResolver = resolveBrowserRuntime }) {
1267
+ const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'om-harness-generated-test-'))
1268
+ const { env, toolReadRoots } = createMinimalValidationEnvironment(tempRoot)
1269
+ const dependencyPath = path.join(target, 'node_modules')
1270
+ const readOnlyRoots = [fs.realpathSync(target), ...(fs.existsSync(dependencyPath) ? [fs.realpathSync(dependencyPath)] : []), ...toolReadRoots]
1271
+ let execution
1272
+ let before
1273
+ let cli
1274
+ let testCounts
1275
+ try {
1276
+ const artifact = path.resolve(target, step.artifact)
1277
+ const artifactStat = fs.lstatSync(artifact)
1278
+ if (!isPathInside(fs.realpathSync(target), fs.realpathSync(artifact)) || !artifactStat.isFile() || artifactStat.isSymbolicLink()) {
1279
+ throw new Error('generated test artifact must be a regular file inside the target')
1280
+ }
1281
+ if (!GENERATED_TEST_RUNNERS.has(step.testRunner) || !['none', 'loopback'].includes(step.network)) {
1282
+ throw new Error('generated test runner contract is invalid')
1283
+ }
1284
+ if (step.testRunner === 'jest' && step.network !== 'none') throw new Error('generated Jest tests must run without network access')
1285
+ if (step.testRunner !== 'jest' && step.network !== 'loopback') throw new Error('generated Playwright tests must run with isolated loopback only')
1286
+ cli = resolveTargetTestCli(target, step.testRunner)
1287
+ if (step.testRunner === 'playwright-browser') {
1288
+ const isolatedBrowserCache = path.join(tempRoot, 'browser-cache')
1289
+ fs.mkdirSync(isolatedBrowserCache, { mode: 0o700 })
1290
+ const browser = browserRuntimeResolver(target, isolatedBrowserCache)
1291
+ readOnlyRoots.push(browser.browserRoot)
1292
+ env.PLAYWRIGHT_BROWSERS_PATH = browser.isolatedCache
1293
+ }
1294
+ if (step.testRunner !== 'jest') env.PLAYWRIGHT_JSON_OUTPUT_FILE = path.join(tempRoot, 'playwright-results.json')
1295
+ const contract = generatedTestExecutionContract({ runner: step.testRunner, artifact: step.artifact })
1296
+ if (step.executor !== contract.executor || step.cliPackage !== contract.cliPackage
1297
+ || JSON.stringify(step.argv) !== JSON.stringify(contract.argv) || step.command !== contract.command) {
1298
+ throw new Error('generated test execution differs from the fixed direct controller contract')
1299
+ }
1300
+ const runnerArgs = contract.argv.map((value) => value
1301
+ .replace('<resolved-cli>', cli)
1302
+ .replace('<isolated-temp>', tempRoot))
1303
+ before = targetSnapshot(target)
1304
+ const invocation = sandboxedInvocation({
1305
+ command: process.execPath,
1306
+ args: runnerArgs,
1307
+ cwd: target,
1308
+ writableRoots: [tempRoot],
1309
+ readOnlyRoots,
1310
+ networkMode: step.network,
1311
+ env,
1312
+ })
1313
+ execution = execute(invocation.command, invocation.args, invocation.cwd, timeout, invocation.env)
1314
+ if (execution.status === 0 && !execution.error) testCounts = generatedTestCounts(step.testRunner, tempRoot)
1315
+ } catch (error) {
1316
+ execution = { status: null, error, stdout: '', stderr: '', durationMs: 0 }
1317
+ }
1318
+ try {
1319
+ const after = targetSnapshot(target)
1320
+ const changed = before
1321
+ ? [...new Set([...before.keys(), ...after.keys()])].filter((key) => before.get(key) !== after.get(key)).sort()
1322
+ : []
1323
+ const unsafeEntries = unsafeChangedTargetEntries(after, changed)
1324
+ const result = {
1325
+ ...stepResult(step, execution, [], roots),
1326
+ ...(typeof cli === 'string' && fs.existsSync(cli) ? { cliSha256: sha256(fs.readFileSync(cli)) } : {}),
1327
+ ...(testCounts ? { testCounts } : {}),
1328
+ }
1329
+ if (unsafeEntries.length) {
1330
+ result.status = 'fail'
1331
+ result.sanitizedError = sanitizeReportText(`generated test created unsafe filesystem entries: ${unsafeEntries.join(', ')}`, roots)
1332
+ }
1333
+ return result
1334
+ } finally {
1335
+ fs.rmSync(tempRoot, { recursive: true, force: true })
1336
+ }
1337
+ }
1338
+
1339
+ function executedCoverage(plan, steps, results) {
1340
+ const deterministic = steps.find((step) => step.kind === 'deterministic')?.observedCaseIds ?? []
1341
+ const routing = plan.coverage.routing.map((entry) => {
1342
+ const executedCaseIds = sortedUnique(results.filter((result) => result.runner === entry.runner && result.evaluationKind === 'routing' && !result.sourceResult).map((result) => result.caseId))
1343
+ return { runner: entry.runner, expectedCaseIds: entry.expectedCaseIds, executedCaseIds, missingCaseIds: difference(entry.expectedCaseIds, executedCaseIds) }
1344
+ })
1345
+ const writableExecuted = sortedUnique(results.filter((result) => WRITABLE_KINDS.has(result.evaluationKind) && !result.sourceResult).map((result) => result.caseId))
1346
+ const reviewExecuted = sortedUnique(results.filter((result) => result.sourceResult).map((result) => result.caseId))
1347
+ const validationExecuted = steps.filter((step) => step.kind === 'validation' && step.status !== 'skipped').map((step) => `yarn ${step.id.slice('validation:'.length)}`)
1348
+ const targetValidationExecuted = []
1349
+ const targetValidationPassed = []
1350
+ const targetValidationFailed = []
1351
+ for (const caseId of plan.coverage.targetValidation.expectedCaseIds) {
1352
+ const caseSteps = steps.filter((step) => step.kind === 'target-validation' && step.caseId === caseId)
1353
+ if (caseSteps.length !== plan.coverage.targetValidation.commands.length || caseSteps.some((step) => step.status === 'skipped')) continue
1354
+ targetValidationExecuted.push(caseId)
1355
+ if (caseSteps.every((step) => step.status === 'pass')) targetValidationPassed.push(caseId)
1356
+ else targetValidationFailed.push(caseId)
1357
+ }
1358
+ const generatedTestExecuted = sortedUnique(steps.filter((step) => step.kind === 'generated-test' && step.status !== 'skipped').map((step) => step.caseId))
1359
+ const generatedTestPassed = sortedUnique(steps.filter((step) => step.kind === 'generated-test' && step.status === 'pass').map((step) => step.caseId))
1360
+ const generatedTestFailed = sortedUnique(steps.filter((step) => step.kind === 'generated-test' && step.status === 'fail').map((step) => step.caseId))
1361
+ return {
1362
+ deterministic: { ...plan.coverage.deterministic, executedCaseIds: deterministic, missingCaseIds: difference(plan.coverage.deterministic.expectedCaseIds, deterministic) },
1363
+ routing,
1364
+ writable: { ...plan.coverage.writable, executedCaseIds: writableExecuted, missingCaseIds: difference(plan.coverage.writable.expectedCaseIds, writableExecuted) },
1365
+ review: { ...plan.coverage.review, executedCaseIds: reviewExecuted, missingCaseIds: difference(plan.coverage.review.expectedCaseIds, reviewExecuted) },
1366
+ registry: plan.coverage.registry,
1367
+ validation: { ...plan.coverage.validation, executedCommands: validationExecuted, missingExecutedCommands: difference(plan.coverage.validation.expectedCommands, validationExecuted) },
1368
+ targetValidation: {
1369
+ ...plan.coverage.targetValidation,
1370
+ executedCaseIds: targetValidationExecuted,
1371
+ passedCaseIds: targetValidationPassed,
1372
+ failedCaseIds: targetValidationFailed,
1373
+ missingCaseIds: difference(plan.coverage.targetValidation.expectedCaseIds, targetValidationExecuted),
1374
+ },
1375
+ generatedTests: {
1376
+ ...plan.coverage.generatedTests,
1377
+ executedCaseIds: generatedTestExecuted,
1378
+ passedCaseIds: generatedTestPassed,
1379
+ failedCaseIds: generatedTestFailed,
1380
+ missingCaseIds: difference(plan.coverage.generatedTests.expectedCaseIds, generatedTestExecuted),
1381
+ },
1382
+ }
1383
+ }
1384
+
1385
+ function writeReport(root, report, roots, schema) {
1386
+ const directory = path.join(root, '.ai', 'harness', 'results')
1387
+ fs.mkdirSync(directory, { recursive: true })
1388
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
1389
+ const file = path.join(directory, `${stamp}-release-suite.json`)
1390
+ const sanitized = sanitizeObject(report, roots)
1391
+ const schemaErrors = validateJsonSchema(sanitized, schema)
1392
+ if (schemaErrors.length) throw new Error(`release report schema validation failed: ${schemaErrors.slice(0, 8).join('; ')}`)
1393
+ fs.writeFileSync(file, `${JSON.stringify(sanitized, null, 2)}\n`, { mode: 0o600 })
1394
+ return path.relative(root, file).replaceAll(path.sep, '/')
1395
+ }
1396
+
1397
+ function writeTargetValidationResult(root, target, caseId, sourceArtifact, commandSteps, generatedTestStep, schema) {
1398
+ const sourcePath = path.join(root, sourceArtifact.path)
1399
+ const targetFingerprint = targetContentFingerprint(target)
1400
+ if (targetFingerprint !== sourceArtifact.value.writable.targetFingerprint) {
1401
+ throw new Error('original writable target changed after its trusted oracle; target validation must run only in the isolated copy')
1402
+ }
1403
+ const record = {
1404
+ schemaVersion: 1,
1405
+ caseId,
1406
+ sourceResult: { path: sourceArtifact.path, sha256: sha256(fs.readFileSync(sourcePath)) },
1407
+ beforeValidationFingerprint: sourceArtifact.value.writable.targetFingerprint,
1408
+ targetFingerprint,
1409
+ commands: commandSteps.map((step) => ({
1410
+ command: step.command,
1411
+ status: step.status,
1412
+ exitStatus: step.exitStatus,
1413
+ durationMs: step.durationMs,
1414
+ })),
1415
+ generatedTests: generatedTestStep ? [{
1416
+ runner: generatedTestStep.testRunner,
1417
+ artifact: generatedTestStep.artifact,
1418
+ artifactSha256: sha256(fs.readFileSync(path.join(target, generatedTestStep.artifact))),
1419
+ executor: generatedTestStep.executor,
1420
+ cliPackage: generatedTestStep.cliPackage,
1421
+ cliSha256: generatedTestStep.cliSha256,
1422
+ argv: generatedTestStep.argv,
1423
+ command: generatedTestStep.command,
1424
+ network: generatedTestStep.network,
1425
+ testCounts: generatedTestStep.testCounts,
1426
+ status: generatedTestStep.status,
1427
+ exitStatus: generatedTestStep.exitStatus,
1428
+ durationMs: generatedTestStep.durationMs,
1429
+ }] : [],
1430
+ status: commandSteps.every((step) => step.status === 'pass') && (!generatedTestStep || generatedTestStep.status === 'pass') ? 'pass' : 'fail',
1431
+ }
1432
+ const schemaErrors = validateJsonSchema(record, schema)
1433
+ if (schemaErrors.length) throw new Error(`target validation result schema failed: ${schemaErrors.slice(0, 8).join('; ')}`)
1434
+ const directory = path.join(root, '.ai', 'harness', 'results')
1435
+ fs.mkdirSync(directory, { recursive: true })
1436
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
1437
+ const absolute = path.join(directory, `${stamp}-target-validation-${caseId}.json`)
1438
+ fs.writeFileSync(absolute, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 })
1439
+ return { absolute, relative: path.relative(root, absolute).replaceAll(path.sep, '/'), value: record }
1440
+ }
1441
+
1442
+ function initialReport(plan, startedAt) {
1443
+ return {
1444
+ schemaVersion: 1,
1445
+ status: 'fail',
1446
+ startedAt,
1447
+ finishedAt: new Date().toISOString(),
1448
+ durationMs: 0,
1449
+ runnerPolicy: plan.runnerPolicy,
1450
+ catalog: plan.catalog,
1451
+ coverage: executedCoverage(plan, [], []),
1452
+ steps: [],
1453
+ metrics: aggregateQualityMetrics([]),
1454
+ violations: plan.violations.map((entry) => entry.slice(0, VIOLATION_LIMIT)),
1455
+ }
1456
+ }
1457
+
1458
+ export function main(argv = process.argv.slice(2)) {
1459
+ const wallStarted = Date.now()
1460
+ const startedAt = new Date().toISOString()
1461
+ let options
1462
+ try { options = parseArgs(argv) } catch (error) { console.error(error.message); console.error(usage()); return 2 }
1463
+ if (options.help) { console.log(usage()); return 0 }
1464
+ let root
1465
+ try { root = fs.realpathSync(options.root) } catch { console.error('release root is unavailable'); return 2 }
1466
+ const harnessDir = path.join(root, '.ai', 'harness')
1467
+ if (!fs.existsSync(harnessDir)) { console.error(`harness directory not found under release root`); return 2 }
1468
+ let cases
1469
+ let registry
1470
+ let releaseMatrix
1471
+ let fixtures
1472
+ let seeds
1473
+ let releaseResultSchema
1474
+ let targetValidationResultSchema
1475
+ try {
1476
+ cases = readJson(path.join(harnessDir, 'cases.json'))
1477
+ registry = readJson(path.join(harnessDir, 'validators.json'))
1478
+ releaseMatrix = readJson(path.join(harnessDir, 'release-matrix.json'))
1479
+ fixtures = readJson(path.join(harnessDir, 'fixtures', 'index.json'))
1480
+ seeds = readJson(path.join(harnessDir, 'fixtures', 'seeds.json'))
1481
+ releaseResultSchema = readJson(path.join(harnessDir, 'release-result.schema.json'))
1482
+ targetValidationResultSchema = readJson(path.join(harnessDir, 'target-validation-result.schema.json'))
1483
+ } catch {
1484
+ console.error('release harness inputs are missing or invalid')
1485
+ return 2
1486
+ }
1487
+ const hostPrerequisiteViolations = releaseHostPrerequisiteViolations(releaseMatrix)
1488
+ if (hostPrerequisiteViolations.length) {
1489
+ console.error('release host prerequisites are not satisfied:')
1490
+ for (const violation of hostPrerequisiteViolations) console.error(`- ${violation}`)
1491
+ return 2
1492
+ }
1493
+ let targetsManifest
1494
+ let controllerDependencyFingerprint
1495
+ try { controllerDependencyFingerprint = dependencyContentFingerprint(root) } catch (error) {
1496
+ console.error(`controller dependency verification failed: ${error.message}`)
1497
+ return 2
1498
+ }
1499
+ if (options.writableTargets) {
1500
+ try {
1501
+ const stat = fs.lstatSync(options.writableTargets)
1502
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > RESULT_LIMIT) throw new Error('manifest must be a bounded regular file')
1503
+ targetsManifest = readJson(options.writableTargets)
1504
+ } catch (error) {
1505
+ console.error(`cannot read writable target manifest: ${error.message}`)
1506
+ return 2
1507
+ }
1508
+ } else {
1509
+ let prepareRoot
1510
+ try { prepareRoot = resolvePreparationRoot(options.prepareTargets, root) } catch (error) { console.error(error.message); return 2 }
1511
+ const writableIds = cases.filter((item) => WRITABLE_KINDS.has(item.evaluationKind)).map((item) => item.id)
1512
+ const proposedManifest = { schemaVersion: 1, targets: Object.fromEntries(writableIds.map((id) => [id, path.join(prepareRoot, id)])) }
1513
+ const preliminary = buildReleasePlan({ cases, registry, releaseMatrix, fixtures, seeds, targetsManifest: proposedManifest, root, primaryRunner: options.runner, portabilityRunner: options.portabilityRunner, targetsMayNotExist: true })
1514
+ const proposedRoots = Object.values(proposedManifest.targets)
1515
+ if (preliminary.violations.length) {
1516
+ const report = initialReport(preliminary, startedAt)
1517
+ report.durationMs = Date.now() - wallStarted
1518
+ report.finishedAt = new Date().toISOString()
1519
+ const reportPath = writeReport(root, report, [root, ...proposedRoots], releaseResultSchema)
1520
+ console.error(`Release preflight failed before target preparation; report: ${reportPath}`)
1521
+ return 1
1522
+ }
1523
+ try {
1524
+ targetsManifest = prepareWritableTargets({ root, prepareRoot, caseIds: writableIds })
1525
+ } catch (error) {
1526
+ preliminary.violations = [`automatic writable target preparation failed: ${error.message}`]
1527
+ const report = initialReport(preliminary, startedAt)
1528
+ report.durationMs = Date.now() - wallStarted
1529
+ report.finishedAt = new Date().toISOString()
1530
+ const reportPath = writeReport(root, report, [root, ...proposedRoots], releaseResultSchema)
1531
+ console.error(`Automatic target preparation failed; report: ${reportPath}`)
1532
+ return 1
1533
+ }
1534
+ }
1535
+ const plan = buildReleasePlan({ cases, registry, releaseMatrix, fixtures, seeds, targetsManifest, root, primaryRunner: options.runner, portabilityRunner: options.portabilityRunner })
1536
+ const targetRoots = Object.values(plan.targets).filter((entry) => typeof entry === 'string' && path.isAbsolute(entry)).map((entry) => path.resolve(entry))
1537
+ const roots = [root, ...targetRoots]
1538
+ if (plan.violations.length) {
1539
+ const report = initialReport(plan, startedAt)
1540
+ report.durationMs = Date.now() - wallStarted
1541
+ report.finishedAt = new Date().toISOString()
1542
+ const reportPath = writeReport(root, report, roots, releaseResultSchema)
1543
+ console.error(`Release preflight failed; report: ${reportPath}`)
1544
+ for (const violation of plan.violations) console.error(`- ${violation}`)
1545
+ return 1
1546
+ }
1547
+ console.log(`Runner policy: primary=${plan.runnerPolicy.primaryRunner}; portability=${plan.runnerPolicy.portabilityRunner ?? 'not requested'}`)
1548
+
1549
+ const evaluator = path.join(root, 'scripts', 'evaluate-agent-harness.mjs')
1550
+ const preparer = path.join(root, 'scripts', 'prepare-agent-harness-fixture.mjs')
1551
+ const sharedDependencyBefore = controllerDependencyFingerprint
1552
+ const steps = []
1553
+ const resultArtifacts = []
1554
+ const deterministicStep = plan.steps.find((step) => step.kind === 'deterministic')
1555
+ const validationSteps = plan.steps.filter((step) => step.kind === 'validation')
1556
+ const foundationTempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'om-harness-foundation-'))
1557
+ const { env: foundationEnv } = createMinimalValidationEnvironment(foundationTempRoot)
1558
+ let deterministicResult
1559
+ try {
1560
+ const deterministicExecution = execute(
1561
+ process.execPath,
1562
+ [evaluator, '--root', root, '--all'],
1563
+ root,
1564
+ options.caseTimeout * Math.max(1, plan.catalog.caseCount) + 60_000,
1565
+ foundationEnv,
1566
+ )
1567
+ const deterministicObserved = sortedUnique((deterministicExecution.stdout ?? '').match(/^PASS (OMH-[0-9]{3})/gm)?.map((entry) => entry.slice('PASS '.length)) ?? [])
1568
+ deterministicResult = stepResult(deterministicStep, deterministicExecution, [], roots)
1569
+ deterministicResult.observedCaseIds = deterministicObserved
1570
+ if (deterministicObserved.length !== plan.catalog.caseCount) {
1571
+ deterministicResult.status = 'fail'
1572
+ deterministicResult.sanitizedError = `expected ${plan.catalog.caseCount} deterministic cases, observed ${deterministicObserved.length}`
1573
+ }
1574
+ steps.push(deterministicResult)
1575
+
1576
+ if (deterministicResult.status === 'pass') {
1577
+ steps.push(...runTargetValidationSteps({
1578
+ steps: validationSteps,
1579
+ target: root,
1580
+ timeout: options.validationTimeout,
1581
+ roots,
1582
+ allowContainedDependencies: true,
1583
+ }))
1584
+ } else {
1585
+ for (const step of validationSteps) steps.push(skippedStep(step, 'deterministic gate failed'))
1586
+ }
1587
+ } finally {
1588
+ fs.rmSync(foundationTempRoot, { recursive: true, force: true })
1589
+ }
1590
+
1591
+ const foundationsPassed = deterministicResult.status === 'pass'
1592
+ && steps.filter((step) => step.kind === 'validation').every((step) => step.status === 'pass')
1593
+ const modelSteps = plan.steps.filter((step) => ['routing', 'fixture', 'writable', 'target-validation', 'generated-test', 'review'].includes(step.kind))
1594
+ if (!foundationsPassed) {
1595
+ for (const step of modelSteps) steps.push(skippedStep(step, 'deterministic or validation foundation failed'))
1596
+ } else {
1597
+ for (const step of plan.steps.filter((entry) => entry.kind === 'routing')) {
1598
+ const before = resultFiles(root)
1599
+ const routingArgs = [evaluator, '--root', root, '--runner', step.runner]
1600
+ if (step.lane === 'primary') routingArgs.push('--all')
1601
+ routingArgs.push('--model', step.modelSelector, '--timeout', String(options.caseTimeout))
1602
+ const execution = execute(process.execPath, routingArgs, root, options.caseTimeout * Math.max(1, step.expectedCaseIds.length) + 60_000)
1603
+ const artifacts = readNewResults(root, before)
1604
+ resultArtifacts.push(...artifacts)
1605
+ steps.push(stepResult(step, execution, artifacts, roots, step.expectedCaseIds.length))
1606
+ }
1607
+
1608
+ for (const caseId of plan.coverage.writable.expectedCaseIds) {
1609
+ const fixtureStep = plan.steps.find((step) => step.id === `fixture:${caseId}`)
1610
+ const writableStep = plan.steps.find((step) => step.id === `writable:${caseId}`)
1611
+ const targetValidationSteps = plan.steps.filter((step) => step.kind === 'target-validation' && step.caseId === caseId)
1612
+ const generatedTestStep = plan.steps.find((step) => step.kind === 'generated-test' && step.caseId === caseId)
1613
+ const reviewStep = plan.steps.find((step) => step.id === `review:${caseId}`)
1614
+ const target = plan.targets[caseId]
1615
+ const fixtureExecution = execute(process.execPath, [preparer, '--case', caseId, '--target', target, '--acknowledge-writes'], root, 120_000)
1616
+ const fixtureResult = stepResult(fixtureStep, fixtureExecution, [], roots)
1617
+ steps.push(fixtureResult)
1618
+ if (fixtureResult.status !== 'pass') {
1619
+ steps.push(skippedStep(writableStep, 'fixture preparation failed'))
1620
+ for (const step of targetValidationSteps) steps.push(skippedStep(step, 'writable gate did not pass'))
1621
+ if (generatedTestStep) steps.push(skippedStep(generatedTestStep, 'writable gate did not pass'))
1622
+ if (reviewStep) steps.push(skippedStep(reviewStep, 'writable gate did not pass'))
1623
+ continue
1624
+ }
1625
+ const beforeWritable = resultFiles(root)
1626
+ const writableExecution = execute(process.execPath, [
1627
+ evaluator, '--root', root, '--runner', writableStep.runner, '--case', caseId,
1628
+ '--model', writableStep.modelSelector, '--timeout', String(options.caseTimeout),
1629
+ '--writable-root', target, '--acknowledge-writes',
1630
+ ], root, options.caseTimeout + 120_000)
1631
+ const writableArtifacts = readNewResults(root, beforeWritable)
1632
+ resultArtifacts.push(...writableArtifacts)
1633
+ const writableResult = stepResult(writableStep, writableExecution, writableArtifacts, roots, 1)
1634
+ steps.push(writableResult)
1635
+ const sourceArtifact = writableArtifacts.find((entry) => entry.value.caseId === caseId && WRITABLE_KINDS.has(entry.value.evaluationKind))
1636
+ const targetValidationResults = runTargetValidationSteps({
1637
+ steps: targetValidationSteps,
1638
+ target,
1639
+ timeout: options.validationTimeout,
1640
+ roots,
1641
+ })
1642
+ steps.push(...targetValidationResults)
1643
+ const failedTargetCommands = targetValidationResults.filter((step) => step.status !== 'pass')
1644
+ let generatedTestResult
1645
+ if (generatedTestStep) {
1646
+ if (writableResult.status !== 'pass' || !sourceArtifact || sourceArtifact.value.status !== 'pass') {
1647
+ generatedTestResult = skippedStep(generatedTestStep, 'trusted writable oracle did not pass')
1648
+ } else if (failedTargetCommands.length) {
1649
+ generatedTestResult = skippedStep(generatedTestStep, 'target validation did not pass')
1650
+ } else {
1651
+ generatedTestResult = runGeneratedTestStep({
1652
+ step: generatedTestStep,
1653
+ target,
1654
+ timeout: options.validationTimeout,
1655
+ roots,
1656
+ })
1657
+ }
1658
+ steps.push(generatedTestResult)
1659
+ }
1660
+ if (!reviewStep) continue
1661
+ if (writableResult.status !== 'pass' || !sourceArtifact || sourceArtifact.value.status !== 'pass') {
1662
+ steps.push(skippedStep(reviewStep, 'writable gate did not pass'))
1663
+ continue
1664
+ }
1665
+ if (failedTargetCommands.length) {
1666
+ steps.push(skippedStep(reviewStep, `target validation failed: ${failedTargetCommands.map((step) => step.command).join(', ')}`))
1667
+ continue
1668
+ }
1669
+ if (generatedTestResult && generatedTestResult.status !== 'pass') {
1670
+ steps.push(skippedStep(reviewStep, 'generated test execution did not pass'))
1671
+ continue
1672
+ }
1673
+ let targetValidationArtifact
1674
+ try {
1675
+ targetValidationArtifact = writeTargetValidationResult(
1676
+ root, target, caseId, sourceArtifact, targetValidationResults, generatedTestResult, targetValidationResultSchema,
1677
+ )
1678
+ } catch (error) {
1679
+ const finalValidation = targetValidationResults.at(-1)
1680
+ finalValidation.status = 'fail'
1681
+ finalValidation.sanitizedError = sanitizeReportText(`validation attestation failed: ${error.message}`, roots)
1682
+ steps.push(skippedStep(reviewStep, 'target validation attestation failed'))
1683
+ continue
1684
+ }
1685
+ const beforeReview = resultFiles(root)
1686
+ const reviewExecution = execute(process.execPath, [
1687
+ evaluator, '--root', root, '--runner', reviewStep.runner,
1688
+ '--model', reviewStep.modelSelector, '--timeout', String(options.caseTimeout),
1689
+ '--review-writable-result', path.join(root, sourceArtifact.path), '--writable-root', target,
1690
+ '--review-validation-result', targetValidationArtifact.absolute,
1691
+ ], root, options.caseTimeout + 60_000)
1692
+ const reviewArtifacts = readNewResults(root, beforeReview)
1693
+ resultArtifacts.push(...reviewArtifacts)
1694
+ steps.push(stepResult(reviewStep, reviewExecution, reviewArtifacts, roots, 1))
1695
+ }
1696
+ }
1697
+
1698
+ if (sharedDependencyBefore) {
1699
+ let sharedDependencyAfter
1700
+ let dependencyError
1701
+ try { sharedDependencyAfter = dependencyContentFingerprint(root) } catch (error) { dependencyError = error }
1702
+ steps.push({
1703
+ id: 'shared-dependencies:unchanged',
1704
+ kind: 'dependency-guard',
1705
+ status: !dependencyError && sharedDependencyAfter === sharedDependencyBefore ? 'pass' : 'fail',
1706
+ exitStatus: null,
1707
+ durationMs: 0,
1708
+ resultPaths: [],
1709
+ ...(!dependencyError && sharedDependencyAfter === sharedDependencyBefore ? {} : {
1710
+ sanitizedError: dependencyError
1711
+ ? sanitizeReportText(`shared dependency verification failed: ${dependencyError.message}`, roots)
1712
+ : 'shared dependency tree changed during release execution; restore dependencies and rerun with fresh targets',
1713
+ }),
1714
+ })
1715
+ }
1716
+
1717
+ const values = resultArtifacts.map((entry) => entry.value)
1718
+ const coverage = executedCoverage(plan, steps, values)
1719
+ const executionViolations = steps
1720
+ .filter((step) => step.status !== 'pass')
1721
+ .map((step) => `${step.id} ${step.status}${step.sanitizedError ? `: ${step.sanitizedError}` : ''}`)
1722
+ .slice(0, 256)
1723
+ const coverageIncomplete = coverage.deterministic.missingCaseIds.length
1724
+ || coverage.routing.some((entry) => entry.missingCaseIds.length)
1725
+ || coverage.writable.missingCaseIds.length
1726
+ || coverage.review.missingCaseIds.length
1727
+ || coverage.validation.missingExecutedCommands.length
1728
+ || coverage.targetValidation.missingCaseIds.length
1729
+ || coverage.targetValidation.failedCaseIds.length
1730
+ || coverage.generatedTests.missingCaseIds.length
1731
+ || coverage.generatedTests.failedCaseIds.length
1732
+ const status = executionViolations.length === 0 && !coverageIncomplete ? 'pass' : 'fail'
1733
+ const report = {
1734
+ schemaVersion: 1,
1735
+ status,
1736
+ startedAt,
1737
+ finishedAt: new Date().toISOString(),
1738
+ durationMs: Date.now() - wallStarted,
1739
+ runnerPolicy: plan.runnerPolicy,
1740
+ catalog: plan.catalog,
1741
+ coverage,
1742
+ steps,
1743
+ metrics: aggregateQualityMetrics(values),
1744
+ violations: executionViolations.map((entry) => entry.slice(0, VIOLATION_LIMIT)),
1745
+ }
1746
+ const reportPath = writeReport(root, report, roots, releaseResultSchema)
1747
+ console.log(`${status === 'pass' ? 'PASS' : 'FAIL'} release suite — ${reportPath}`)
1748
+ return status === 'pass' ? 0 : 1
1749
+ }
1750
+
1751
+ if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url) process.exitCode = main()