oxe-cc 1.16.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (590) hide show
  1. package/.cursor/commands/oxe-alm.md +47 -0
  2. package/.cursor/commands/oxe-ask.md +1 -1
  3. package/.cursor/commands/oxe-capabilities.md +1 -1
  4. package/.cursor/commands/oxe-checkpoint.md +1 -1
  5. package/.cursor/commands/oxe-compact.md +1 -1
  6. package/.cursor/commands/oxe-dashboard.md +1 -1
  7. package/.cursor/commands/oxe-debug.md +1 -1
  8. package/.cursor/commands/oxe-discuss.md +45 -45
  9. package/.cursor/commands/oxe-execute.md +52 -50
  10. package/.cursor/commands/oxe-forensics.md +1 -1
  11. package/.cursor/commands/oxe-help.md +44 -44
  12. package/.cursor/commands/oxe-loop.md +1 -1
  13. package/.cursor/commands/oxe-milestone.md +1 -1
  14. package/.cursor/commands/oxe-next.md +44 -44
  15. package/.cursor/commands/oxe-obs.md +1 -1
  16. package/.cursor/commands/oxe-plan-agent.md +1 -1
  17. package/.cursor/commands/oxe-plan.md +49 -47
  18. package/.cursor/commands/oxe-project.md +1 -1
  19. package/.cursor/commands/oxe-quick.md +49 -47
  20. package/.cursor/commands/oxe-research.md +1 -1
  21. package/.cursor/commands/oxe-retro.md +1 -1
  22. package/.cursor/commands/oxe-review-pr.md +47 -47
  23. package/.cursor/commands/oxe-route.md +1 -1
  24. package/.cursor/commands/oxe-scan.md +47 -47
  25. package/.cursor/commands/oxe-security.md +1 -1
  26. package/.cursor/commands/oxe-session.md +1 -1
  27. package/.cursor/commands/oxe-ship.md +47 -47
  28. package/.cursor/commands/oxe-skill.md +1 -1
  29. package/.cursor/commands/oxe-spec.md +49 -47
  30. package/.cursor/commands/oxe-ui-review.md +1 -1
  31. package/.cursor/commands/oxe-ui-spec.md +1 -1
  32. package/.cursor/commands/oxe-update.md +1 -1
  33. package/.cursor/commands/oxe-validate-gaps.md +1 -1
  34. package/.cursor/commands/oxe-verify-audit.md +1 -1
  35. package/.cursor/commands/oxe-verify.md +50 -50
  36. package/.cursor/commands/oxe-workflow-authoring.md +1 -1
  37. package/.cursor/commands/oxe-workstream.md +1 -1
  38. package/.cursor/commands/oxe.md +51 -49
  39. package/.github/copilot-instructions.md +3 -3
  40. package/.github/prompts/oxe-alm.prompt.md +47 -0
  41. package/.github/prompts/oxe-ask.prompt.md +47 -47
  42. package/.github/prompts/oxe-capabilities.prompt.md +47 -47
  43. package/.github/prompts/oxe-checkpoint.prompt.md +47 -47
  44. package/.github/prompts/oxe-compact.prompt.md +46 -46
  45. package/.github/prompts/oxe-dashboard.prompt.md +47 -47
  46. package/.github/prompts/oxe-debug.prompt.md +47 -47
  47. package/.github/prompts/oxe-discuss.prompt.md +47 -47
  48. package/.github/prompts/oxe-execute.prompt.md +52 -50
  49. package/.github/prompts/oxe-forensics.prompt.md +47 -47
  50. package/.github/prompts/oxe-help.prompt.md +46 -46
  51. package/.github/prompts/oxe-loop.prompt.md +47 -47
  52. package/.github/prompts/oxe-milestone.prompt.md +47 -47
  53. package/.github/prompts/oxe-next.prompt.md +46 -46
  54. package/.github/prompts/oxe-obs.prompt.md +47 -47
  55. package/.github/prompts/oxe-plan-agent.prompt.md +46 -46
  56. package/.github/prompts/oxe-plan.prompt.md +49 -47
  57. package/.github/prompts/oxe-project.prompt.md +47 -47
  58. package/.github/prompts/oxe-quick.prompt.md +49 -47
  59. package/.github/prompts/oxe-research.prompt.md +47 -47
  60. package/.github/prompts/oxe-retro.prompt.md +47 -47
  61. package/.github/prompts/oxe-review-pr.prompt.md +47 -47
  62. package/.github/prompts/oxe-route.prompt.md +47 -47
  63. package/.github/prompts/oxe-scan.prompt.md +47 -47
  64. package/.github/prompts/oxe-security.prompt.md +47 -47
  65. package/.github/prompts/oxe-session.prompt.md +47 -47
  66. package/.github/prompts/oxe-ship.prompt.md +47 -47
  67. package/.github/prompts/oxe-skill.prompt.md +47 -47
  68. package/.github/prompts/oxe-spec.prompt.md +49 -47
  69. package/.github/prompts/oxe-ui-review.prompt.md +47 -47
  70. package/.github/prompts/oxe-ui-spec.prompt.md +47 -47
  71. package/.github/prompts/oxe-update.prompt.md +46 -46
  72. package/.github/prompts/oxe-validate-gaps.prompt.md +47 -47
  73. package/.github/prompts/oxe-verify-audit.prompt.md +1 -1
  74. package/.github/prompts/oxe-verify.prompt.md +50 -50
  75. package/.github/prompts/oxe-workflow-authoring.prompt.md +1 -1
  76. package/.github/prompts/oxe-workstream.prompt.md +47 -47
  77. package/.github/prompts/oxe.prompt.md +51 -49
  78. package/.github/workflows/ci.yml +26 -5
  79. package/.github/workflows/release.yml +15 -14
  80. package/AGENTS.md +15 -9
  81. package/CHANGELOG.md +1027 -10
  82. package/LICENSE +21 -21
  83. package/QUICKSTART.md +99 -99
  84. package/README.md +120 -17
  85. package/assets/readme-banner.svg +19 -19
  86. package/bin/banner.txt +5 -5
  87. package/bin/lib/oxe-acceptance-audit.cjs +195 -0
  88. package/bin/lib/oxe-adr.cjs +145 -0
  89. package/bin/lib/oxe-agent-install.cjs +31 -29
  90. package/bin/lib/oxe-alm-admin.cjs +215 -0
  91. package/bin/lib/oxe-alm-metrics.cjs +143 -0
  92. package/bin/lib/oxe-alm-prs.cjs +274 -0
  93. package/bin/lib/oxe-alm-refine.cjs +1003 -0
  94. package/bin/lib/oxe-alm.cjs +1289 -0
  95. package/bin/lib/oxe-anchor-copy.cjs +218 -0
  96. package/bin/lib/oxe-api-surface.cjs +96 -0
  97. package/bin/lib/oxe-artifact-refs.cjs +72 -0
  98. package/bin/lib/oxe-attention.cjs +97 -0
  99. package/bin/lib/oxe-autoresume.cjs +448 -0
  100. package/bin/lib/oxe-azure.cjs +1445 -1445
  101. package/bin/lib/oxe-budget.cjs +154 -0
  102. package/bin/lib/oxe-change-folder.cjs +130 -0
  103. package/bin/lib/oxe-change.cjs +389 -0
  104. package/bin/lib/oxe-channels.cjs +82 -0
  105. package/bin/lib/oxe-cited-paths.cjs +180 -0
  106. package/bin/lib/oxe-cli-errors.cjs +76 -0
  107. package/bin/lib/oxe-cli-output.cjs +111 -0
  108. package/bin/lib/oxe-commit-convention.cjs +104 -0
  109. package/bin/lib/oxe-complexity.cjs +106 -0
  110. package/bin/lib/oxe-console-decode.cjs +23 -0
  111. package/bin/lib/oxe-coordinator-queue.cjs +67 -0
  112. package/bin/lib/oxe-core-command-handlers.cjs +10 -8
  113. package/bin/lib/oxe-criteria-ids.cjs +87 -0
  114. package/bin/lib/oxe-criterion-coverage.cjs +93 -0
  115. package/bin/lib/oxe-cross-card-conflicts.cjs +639 -0
  116. package/bin/lib/oxe-customize.cjs +146 -0
  117. package/bin/lib/oxe-dashboard.cjs +1 -1
  118. package/bin/lib/oxe-decisions.cjs +211 -0
  119. package/bin/lib/oxe-deferred.cjs +80 -0
  120. package/bin/lib/oxe-deps-audit.cjs +136 -0
  121. package/bin/lib/oxe-diff-reviewer.cjs +105 -0
  122. package/bin/lib/oxe-dir-info.cjs +138 -0
  123. package/bin/lib/oxe-docs-check.cjs +124 -0
  124. package/bin/lib/oxe-docs-publish.cjs +81 -0
  125. package/bin/lib/oxe-dom-hooks.cjs +902 -0
  126. package/bin/lib/oxe-dossier.cjs +355 -0
  127. package/bin/lib/oxe-e2e-ready.cjs +360 -0
  128. package/bin/lib/oxe-env-sanitize.cjs +155 -0
  129. package/bin/lib/oxe-event-bus.cjs +118 -118
  130. package/bin/lib/oxe-failure-cost.cjs +144 -0
  131. package/bin/lib/oxe-file-size-guard.cjs +849 -0
  132. package/bin/lib/oxe-findings.cjs +86 -0
  133. package/bin/lib/oxe-grill-cases.cjs +148 -0
  134. package/bin/lib/oxe-grill.cjs +444 -0
  135. package/bin/lib/oxe-grooming.cjs +115 -0
  136. package/bin/lib/oxe-guard.cjs +180 -0
  137. package/bin/lib/oxe-handoff.cjs +97 -0
  138. package/bin/lib/oxe-install-resolve.cjs +28 -0
  139. package/bin/lib/oxe-integration-checks.cjs +285 -0
  140. package/bin/lib/oxe-intent-context.cjs +101 -0
  141. package/bin/lib/oxe-journey.cjs +403 -0
  142. package/bin/lib/oxe-known-failures.cjs +138 -0
  143. package/bin/lib/oxe-local-config.cjs +77 -0
  144. package/bin/lib/oxe-memory-kernel.cjs +190 -188
  145. package/bin/lib/oxe-merge-train.cjs +277 -0
  146. package/bin/lib/oxe-model-resolve.cjs +74 -0
  147. package/bin/lib/oxe-model-tiers.cjs +65 -0
  148. package/bin/lib/oxe-nfr.cjs +125 -0
  149. package/bin/lib/oxe-npm-version.cjs +1 -1
  150. package/bin/lib/oxe-open-defects.cjs +121 -0
  151. package/bin/lib/oxe-operational.cjs +14339 -1066
  152. package/bin/lib/oxe-origin-guard.cjs +102 -0
  153. package/bin/lib/oxe-origin.cjs +377 -0
  154. package/bin/lib/oxe-pack-removed.cjs +208 -0
  155. package/bin/lib/oxe-parallel-run.cjs +81 -0
  156. package/bin/lib/oxe-parallel.cjs +234 -0
  157. package/bin/lib/oxe-phase-extras.cjs +185 -0
  158. package/bin/lib/oxe-phase-gates.cjs +551 -0
  159. package/bin/lib/oxe-plan-build.cjs +1520 -0
  160. package/bin/lib/oxe-plan-json.cjs +1107 -0
  161. package/bin/lib/oxe-plan-merge.cjs +253 -0
  162. package/bin/lib/oxe-plan-mutate.cjs +214 -0
  163. package/bin/lib/oxe-plan-repair.cjs +479 -0
  164. package/bin/lib/oxe-plan-review.cjs +256 -0
  165. package/bin/lib/oxe-plan-skeleton.cjs +494 -0
  166. package/bin/lib/oxe-plan-staleness.cjs +125 -0
  167. package/bin/lib/oxe-plugin-cli.cjs +3 -1
  168. package/bin/lib/oxe-policy-rules.cjs +144 -0
  169. package/bin/lib/oxe-prd.cjs +129 -0
  170. package/bin/lib/oxe-preflight.cjs +378 -0
  171. package/bin/lib/oxe-process.cjs +11 -11
  172. package/bin/lib/oxe-program-members.cjs +97 -0
  173. package/bin/lib/oxe-program.cjs +245 -0
  174. package/bin/lib/oxe-progress-run.cjs +80 -0
  175. package/bin/lib/oxe-project-env.cjs +273 -0
  176. package/bin/lib/oxe-project-health.cjs +619 -41
  177. package/bin/lib/oxe-promote-helpers.cjs +1561 -0
  178. package/bin/lib/oxe-provider-antigravity.cjs +114 -0
  179. package/bin/lib/oxe-provider-grok.cjs +48 -0
  180. package/bin/lib/oxe-questions.cjs +115 -0
  181. package/bin/lib/oxe-quick.cjs +537 -0
  182. package/bin/lib/oxe-ratchets.cjs +132 -0
  183. package/bin/lib/oxe-rationality.cjs +587 -532
  184. package/bin/lib/oxe-real-regression.cjs +97 -0
  185. package/bin/lib/oxe-recovery.cjs +160 -0
  186. package/bin/lib/oxe-release-ops.cjs +325 -0
  187. package/bin/lib/oxe-release.cjs +622 -551
  188. package/bin/lib/oxe-repair.cjs +153 -0
  189. package/bin/lib/oxe-repo-map.cjs +136 -0
  190. package/bin/lib/oxe-repo-rules.cjs +121 -0
  191. package/bin/lib/oxe-research-provenance.cjs +96 -0
  192. package/bin/lib/oxe-resume.cjs +406 -0
  193. package/bin/lib/oxe-review.cjs +403 -0
  194. package/bin/lib/oxe-rfc.cjs +192 -0
  195. package/bin/lib/oxe-risk-decision.cjs +141 -0
  196. package/bin/lib/oxe-runtime-semantics.cjs +8 -1
  197. package/bin/lib/oxe-scorecard.cjs +234 -0
  198. package/bin/lib/oxe-scratch.cjs +81 -0
  199. package/bin/lib/oxe-seams.cjs +159 -0
  200. package/bin/lib/oxe-security.cjs +289 -289
  201. package/bin/lib/oxe-semver.cjs +83 -0
  202. package/bin/lib/oxe-ship-pr.cjs +204 -0
  203. package/bin/lib/oxe-signal.cjs +173 -0
  204. package/bin/lib/oxe-skill-loader.cjs +131 -131
  205. package/bin/lib/oxe-spec-check.cjs +217 -0
  206. package/bin/lib/oxe-spec-ears.cjs +98 -0
  207. package/bin/lib/oxe-spec-edit.cjs +411 -0
  208. package/bin/lib/oxe-spec-freeze.cjs +378 -0
  209. package/bin/lib/oxe-spec-probe.cjs +146 -0
  210. package/bin/lib/oxe-spec-stress.cjs +146 -0
  211. package/bin/lib/oxe-spike.cjs +98 -0
  212. package/bin/lib/oxe-state.cjs +87 -0
  213. package/bin/lib/oxe-stub-check.cjs +355 -0
  214. package/bin/lib/oxe-suite-impact.cjs +1145 -0
  215. package/bin/lib/oxe-sync.cjs +250 -0
  216. package/bin/lib/oxe-system-design.cjs +138 -0
  217. package/bin/lib/oxe-task-gates.cjs +139 -0
  218. package/bin/lib/oxe-telemetry.cjs +201 -0
  219. package/bin/lib/oxe-test-precheck.cjs +508 -0
  220. package/bin/lib/oxe-test-rigor.cjs +663 -0
  221. package/bin/lib/oxe-test-scope.cjs +883 -0
  222. package/bin/lib/oxe-trace.cjs +168 -0
  223. package/bin/lib/oxe-turns.cjs +64 -0
  224. package/bin/lib/oxe-ui-evidence.cjs +187 -0
  225. package/bin/lib/oxe-ui-verify.cjs +55 -0
  226. package/bin/lib/oxe-unsafe-commands.cjs +94 -0
  227. package/bin/lib/oxe-verdicts.cjs +131 -0
  228. package/bin/lib/oxe-verify-dryrun.cjs +541 -0
  229. package/bin/lib/oxe-verify-remote.cjs +208 -0
  230. package/bin/lib/oxe-vitest-batch.cjs +142 -0
  231. package/bin/lib/oxe-workflow-budget.cjs +99 -0
  232. package/bin/lib/oxe-workflow-eval.cjs +118 -0
  233. package/bin/lib/oxe-workflows.cjs +3 -1
  234. package/bin/lib/oxe-worktree-deps.cjs +241 -0
  235. package/bin/lib/oxe-worktree-gc.cjs +170 -0
  236. package/bin/oxe-cc.js +4934 -94
  237. package/commands/oxe/alm.md +54 -0
  238. package/commands/oxe/ask.md +55 -55
  239. package/commands/oxe/capabilities.md +50 -50
  240. package/commands/oxe/checkpoint.md +53 -53
  241. package/commands/oxe/compact.md +47 -47
  242. package/commands/oxe/dashboard.md +51 -51
  243. package/commands/oxe/debug.md +58 -58
  244. package/commands/oxe/discuss.md +58 -58
  245. package/commands/oxe/execute.md +63 -61
  246. package/commands/oxe/forensics.md +53 -53
  247. package/commands/oxe/help.md +48 -48
  248. package/commands/oxe/loop.md +54 -54
  249. package/commands/oxe/milestone.md +53 -53
  250. package/commands/oxe/next.md +49 -49
  251. package/commands/oxe/obs.md +53 -53
  252. package/commands/oxe/oxe.md +55 -53
  253. package/commands/oxe/plan-agent.md +57 -57
  254. package/commands/oxe/plan.md +59 -57
  255. package/commands/oxe/project.md +53 -53
  256. package/commands/oxe/quick.md +53 -53
  257. package/commands/oxe/research.md +53 -53
  258. package/commands/oxe/retro.md +53 -53
  259. package/commands/oxe/review-pr.md +53 -53
  260. package/commands/oxe/route.md +48 -48
  261. package/commands/oxe/scan.md +58 -58
  262. package/commands/oxe/security.md +53 -53
  263. package/commands/oxe/session.md +53 -53
  264. package/commands/oxe/ship.md +53 -53
  265. package/commands/oxe/skill.md +53 -53
  266. package/commands/oxe/spec.md +59 -56
  267. package/commands/oxe/ui-review.md +53 -53
  268. package/commands/oxe/ui-spec.md +53 -53
  269. package/commands/oxe/update.md +53 -53
  270. package/commands/oxe/validate-gaps.md +53 -53
  271. package/commands/oxe/verify-audit.md +50 -50
  272. package/commands/oxe/verify.md +60 -60
  273. package/commands/oxe/workflow-authoring.md +50 -50
  274. package/commands/oxe/workstream.md +53 -53
  275. package/docs/ADLC-COVERAGE.md +55 -0
  276. package/docs/CONTENT-MIGRATION-AUDIT.md +49 -49
  277. package/docs/HAPPY-PATH.md +106 -0
  278. package/docs/INCIDENT-PLAYBOOK.md +181 -181
  279. package/docs/RELEASE-READINESS.md +1 -0
  280. package/docs/ROLES.md +129 -129
  281. package/docs/TEAM-ADOPTION.md +153 -153
  282. package/docs/WALKTHROUGH.md +241 -241
  283. package/docs/adr/D-1-isolamento-read-only-e-sanitizacao-centralizada-de-env-vars.md +29 -0
  284. package/docs/adr/D-2-junction-segura-de-node-modules-condicionada-a-sha-256-de-pa.md +29 -0
  285. package/docs/adr/D-3-preflight-local-5s-impacto-estatico-e2e-e-leitura-explicita.md +29 -0
  286. package/docs/adr/D-4-governanca-de-release-unificada-retomada-idempotente-pos-rei.md +29 -0
  287. package/docs/adr/README.md +15 -0
  288. package/docs/cli-errors.md +20 -0
  289. package/docs/oxespace-1.5/BACKLOG.md +2056 -0
  290. package/docs/oxespace-1.5/HANDOFF-1.21.2.md +140 -0
  291. package/docs/oxevoice/BACKLOG.md +244 -0
  292. package/lib/runtime/compiler/graph-compiler.d.ts +15 -0
  293. package/lib/runtime/compiler/graph-compiler.js +49 -3
  294. package/lib/runtime/delivery/promotion-pipeline.d.ts +1 -0
  295. package/lib/runtime/delivery/promotion-pipeline.js +59 -2
  296. package/lib/runtime/events/catalog.d.ts +1 -1
  297. package/lib/runtime/events/catalog.js +29 -0
  298. package/lib/runtime/executor/action-tool-map.d.ts +3 -1
  299. package/lib/runtime/executor/action-tool-map.js +4 -1
  300. package/lib/runtime/executor/adapters/antigravity-cli.d.ts +103 -0
  301. package/lib/runtime/executor/adapters/antigravity-cli.js +530 -0
  302. package/lib/runtime/executor/adapters/claude-cli.d.ts +92 -0
  303. package/lib/runtime/executor/adapters/claude-cli.js +328 -0
  304. package/lib/runtime/executor/adapters/grok-cli.d.ts +89 -0
  305. package/lib/runtime/executor/adapters/grok-cli.js +351 -0
  306. package/lib/runtime/executor/adapters/http-openai.d.ts +9 -0
  307. package/lib/runtime/executor/adapters/http-openai.js +18 -0
  308. package/lib/runtime/executor/adapters/registry.d.ts +18 -0
  309. package/lib/runtime/executor/adapters/registry.js +49 -0
  310. package/lib/runtime/executor/adapters/types.d.ts +21 -0
  311. package/lib/runtime/executor/adapters/types.js +2 -0
  312. package/lib/runtime/executor/built-in-tools.d.ts +64 -0
  313. package/lib/runtime/executor/built-in-tools.js +257 -24
  314. package/lib/runtime/executor/index.d.ts +19 -2
  315. package/lib/runtime/executor/index.js +50 -1
  316. package/lib/runtime/executor/llm-task-executor.d.ts +108 -2
  317. package/lib/runtime/executor/llm-task-executor.js +598 -39
  318. package/lib/runtime/executor/node-context.d.ts +94 -0
  319. package/lib/runtime/executor/node-context.js +126 -0
  320. package/lib/runtime/executor/node-prompt-builder.d.ts +2 -0
  321. package/lib/runtime/executor/node-prompt-builder.js +4 -0
  322. package/lib/runtime/executor/quota-patterns.d.ts +7 -0
  323. package/lib/runtime/executor/quota-patterns.js +39 -0
  324. package/lib/runtime/executor/shell-argv.d.ts +41 -0
  325. package/lib/runtime/executor/shell-argv.js +144 -0
  326. package/lib/runtime/executor/stream-completion.d.ts +27 -0
  327. package/lib/runtime/executor/stream-completion.js +82 -5
  328. package/lib/runtime/index.d.ts +5 -2
  329. package/lib/runtime/index.js +10 -1
  330. package/lib/runtime/models/failure.d.ts +1 -1
  331. package/lib/runtime/models/run.d.ts +1 -1
  332. package/lib/runtime/program/index.d.ts +1 -0
  333. package/lib/runtime/program/index.js +17 -0
  334. package/lib/runtime/program/program-model.d.ts +92 -0
  335. package/lib/runtime/program/program-model.js +262 -0
  336. package/lib/runtime/projection/projection-engine.d.ts +16 -1
  337. package/lib/runtime/projection/projection-engine.js +55 -3
  338. package/lib/runtime/reducers/run-state-reducer.js +48 -5
  339. package/lib/runtime/scheduler/run-journal.d.ts +27 -1
  340. package/lib/runtime/scheduler/run-journal.js +40 -1
  341. package/lib/runtime/scheduler/scheduler.d.ts +239 -0
  342. package/lib/runtime/scheduler/scheduler.js +1157 -97
  343. package/lib/runtime/verification/contract-exports.d.ts +24 -0
  344. package/lib/runtime/verification/contract-exports.js +201 -0
  345. package/lib/runtime/verification/index.d.ts +1 -0
  346. package/lib/runtime/verification/index.js +1 -0
  347. package/lib/runtime/verification/runner-timeout.d.ts +7 -0
  348. package/lib/runtime/verification/runner-timeout.js +17 -0
  349. package/lib/runtime/verification/test-report-parsers.d.ts +38 -0
  350. package/lib/runtime/verification/test-report-parsers.js +188 -0
  351. package/lib/runtime/verification/verification-compiler.d.ts +101 -2
  352. package/lib/runtime/verification/verification-compiler.js +491 -82
  353. package/lib/runtime/verification/verification-manifest.d.ts +12 -0
  354. package/lib/runtime/verification/verification-manifest.js +33 -4
  355. package/lib/runtime/workspace/index.d.ts +2 -1
  356. package/lib/runtime/workspace/index.js +3 -1
  357. package/lib/runtime/workspace/strategies/ephemeral-container.d.ts +9 -0
  358. package/lib/runtime/workspace/strategies/ephemeral-container.js +37 -10
  359. package/lib/runtime/workspace/strategies/git-worktree.d.ts +24 -1
  360. package/lib/runtime/workspace/strategies/git-worktree.js +134 -1
  361. package/lib/sdk/README.md +21 -21
  362. package/lib/sdk/index.cjs +27 -9
  363. package/oxe/agents/oxe-assumptions-analyzer.md +136 -136
  364. package/oxe/agents/oxe-codebase-mapper.md +142 -142
  365. package/oxe/agents/oxe-debugger.md +145 -145
  366. package/oxe/agents/oxe-executor.md +139 -139
  367. package/oxe/agents/oxe-integration-checker.md +142 -142
  368. package/oxe/agents/oxe-plan-checker.md +143 -143
  369. package/oxe/agents/oxe-planner.md +151 -151
  370. package/oxe/agents/oxe-research-synthesizer.md +146 -146
  371. package/oxe/agents/oxe-researcher.md +163 -163
  372. package/oxe/agents/oxe-ui-auditor.md +151 -151
  373. package/oxe/agents/oxe-ui-checker.md +157 -157
  374. package/oxe/agents/oxe-ui-researcher.md +179 -179
  375. package/oxe/agents/oxe-validation-auditor.md +154 -154
  376. package/oxe/agents/oxe-verifier.md +132 -132
  377. package/oxe/migrations/config-migrations.json +15 -0
  378. package/oxe/personas/README.md +91 -91
  379. package/oxe/personas/architect.md +149 -149
  380. package/oxe/personas/db-specialist.md +149 -149
  381. package/oxe/personas/debugger.md +155 -155
  382. package/oxe/personas/executor.md +164 -164
  383. package/oxe/personas/planner.md +165 -165
  384. package/oxe/personas/researcher.md +148 -148
  385. package/oxe/personas/ui-specialist.md +164 -164
  386. package/oxe/personas/verifier.md +174 -174
  387. package/oxe/schemas/plan-agents.schema.json +122 -122
  388. package/oxe/schemas/plan.schema.json +101 -0
  389. package/oxe/schemas/role-plan.schema.json +50 -0
  390. package/oxe/schemas/swarm-run.schema.json +130 -130
  391. package/oxe/templates/ACTIVE-RUN.template.json +32 -32
  392. package/oxe/templates/CAPABILITIES.template.md +7 -7
  393. package/oxe/templates/CAPABILITY.template.md +45 -45
  394. package/oxe/templates/CHECKPOINT.template.md +37 -37
  395. package/oxe/templates/CHECKPOINTS.template.md +7 -7
  396. package/oxe/templates/CODEBASE-DELTA.template.md +33 -33
  397. package/oxe/templates/CONFIG.md +172 -0
  398. package/oxe/templates/DISCUSS.template.md +1 -0
  399. package/oxe/templates/DOCS_BROWNFIELD_LAYOUT.md +55 -55
  400. package/oxe/templates/FIXTURE-PACK.template.json +18 -18
  401. package/oxe/templates/FIXTURE-PACK.template.md +19 -19
  402. package/oxe/templates/GIT_HOOKS_OXE.md +52 -52
  403. package/oxe/templates/GLOSSARY.template.md +9 -0
  404. package/oxe/templates/HYPOTHESES.template.md +33 -33
  405. package/oxe/templates/IMPLEMENTATION-PACK.template.json +26 -26
  406. package/oxe/templates/IMPLEMENTATION-PACK.template.md +32 -32
  407. package/oxe/templates/INVESTIGATION.template.md +38 -38
  408. package/oxe/templates/LESSONS-METRICS.template.json +13 -13
  409. package/oxe/templates/LESSONS.template.md +43 -43
  410. package/oxe/templates/MEMORY.template.md +49 -49
  411. package/oxe/templates/MILESTONES.template.md +17 -17
  412. package/oxe/templates/NOTES.template.md +16 -16
  413. package/oxe/templates/OBSERVATIONS.template.md +18 -18
  414. package/oxe/templates/PLAN-REVIEW.template.md +31 -31
  415. package/oxe/templates/PLAN.template.md +87 -87
  416. package/oxe/templates/PRD.template.md +53 -0
  417. package/oxe/templates/REFERENCE-ANCHORS.template.md +30 -26
  418. package/oxe/templates/RESEARCH.template.md +8 -0
  419. package/oxe/templates/RESUME.template.md +49 -49
  420. package/oxe/templates/RFC.template.md +43 -0
  421. package/oxe/templates/ROADMAP.template.md +44 -44
  422. package/oxe/templates/SECURITY.template.md +72 -72
  423. package/oxe/templates/SESSION.template.md +34 -34
  424. package/oxe/templates/SKILL.template.md +26 -26
  425. package/oxe/templates/SPEC.template.md +65 -65
  426. package/oxe/templates/SUMMARY.template.md +50 -50
  427. package/oxe/templates/VISUAL-INPUTS.template.json +27 -27
  428. package/oxe/templates/VISUAL-INPUTS.template.md +36 -36
  429. package/oxe/templates/WORKFLOW_AUTHORING.md +93 -93
  430. package/oxe/templates/finding-rules.json +22 -0
  431. package/oxe/templates/plan-agent-messages-README.template.md +9 -9
  432. package/oxe/templates/plan-agents.template.json +30 -30
  433. package/oxe/templates/quick-agents.template.json +24 -24
  434. package/oxe/templates/stress-methods.md +33 -0
  435. package/oxe/workflows/agent-mode.md +150 -150
  436. package/oxe/workflows/alm.md +50 -0
  437. package/oxe/workflows/ask.md +96 -96
  438. package/oxe/workflows/capabilities.md +25 -25
  439. package/oxe/workflows/checkpoint.md +37 -37
  440. package/oxe/workflows/compact/plan.md +149 -0
  441. package/oxe/workflows/compact/spec.md +114 -0
  442. package/oxe/workflows/compact.md +1 -0
  443. package/oxe/workflows/conduct.md +149 -149
  444. package/oxe/workflows/dashboard.md +33 -33
  445. package/oxe/workflows/debug.md +9 -9
  446. package/oxe/workflows/discuss.md +15 -3
  447. package/oxe/workflows/distill.md +164 -164
  448. package/oxe/workflows/execute.md +30 -26
  449. package/oxe/workflows/forensics.md +5 -5
  450. package/oxe/workflows/help.md +10 -4
  451. package/oxe/workflows/lean/execute.md +42 -0
  452. package/oxe/workflows/lean/plan.md +60 -0
  453. package/oxe/workflows/lean/spec.md +61 -0
  454. package/oxe/workflows/loop.md +67 -67
  455. package/oxe/workflows/memory.md +163 -163
  456. package/oxe/workflows/milestone.md +95 -95
  457. package/oxe/workflows/next.md +10 -8
  458. package/oxe/workflows/obs.md +167 -167
  459. package/oxe/workflows/oxe.md +33 -14
  460. package/oxe/workflows/plan-agent.md +143 -143
  461. package/oxe/workflows/plan.md +49 -40
  462. package/oxe/workflows/project.md +55 -55
  463. package/oxe/workflows/quick.md +19 -5
  464. package/oxe/workflows/references/adaptive-discovery.md +27 -27
  465. package/oxe/workflows/references/alm-refine.md +55 -0
  466. package/oxe/workflows/references/azure-in-plan.md +5 -0
  467. package/oxe/workflows/references/change-management.md +48 -0
  468. package/oxe/workflows/references/grill.md +74 -0
  469. package/oxe/workflows/references/legacy-brownfield.md +136 -136
  470. package/oxe/workflows/references/next-step-footer.md +33 -0
  471. package/oxe/workflows/references/plan-agent-chat-protocol.md +99 -99
  472. package/oxe/workflows/references/plan-json-acceptance-program.md +174 -0
  473. package/oxe/workflows/references/product-docs-alm.md +51 -0
  474. package/oxe/workflows/references/reasoning-discovery.md +28 -28
  475. package/oxe/workflows/references/reasoning-execution.md +29 -29
  476. package/oxe/workflows/references/reasoning-planning.md +32 -32
  477. package/oxe/workflows/references/reasoning-review.md +29 -29
  478. package/oxe/workflows/references/reasoning-status.md +24 -24
  479. package/oxe/workflows/references/robustness-elevation.md +295 -295
  480. package/oxe/workflows/references/session-path-resolution.md +71 -71
  481. package/oxe/workflows/references/workflow-runtime-contracts.json +1167 -1151
  482. package/oxe/workflows/research.md +1 -0
  483. package/oxe/workflows/retro.md +117 -117
  484. package/oxe/workflows/review-pr.md +53 -53
  485. package/oxe/workflows/route.md +1 -1
  486. package/oxe/workflows/scan.md +356 -355
  487. package/oxe/workflows/security.md +67 -67
  488. package/oxe/workflows/session.md +213 -213
  489. package/oxe/workflows/ship.md +74 -125
  490. package/oxe/workflows/size-budget.json +62 -0
  491. package/oxe/workflows/skill.md +44 -44
  492. package/oxe/workflows/spec.md +92 -93
  493. package/oxe/workflows/swarm/board.md +119 -119
  494. package/oxe/workflows/swarm/scout.md +170 -170
  495. package/oxe/workflows/swarm-mode.md +280 -280
  496. package/oxe/workflows/ui-review.md +5 -5
  497. package/oxe/workflows/ui-spec.md +7 -7
  498. package/oxe/workflows/update.md +35 -35
  499. package/oxe/workflows/validate-gaps.md +45 -45
  500. package/oxe/workflows/verify-audit.md +73 -73
  501. package/oxe/workflows/verify.md +35 -14
  502. package/oxe/workflows/workflow-authoring.md +34 -34
  503. package/oxe/workflows/workstream.md +97 -97
  504. package/package.json +8 -3
  505. package/packages/runtime/package.json +1 -1
  506. package/packages/runtime/src/audit/audit-trail.ts +243 -243
  507. package/packages/runtime/src/audit/index.ts +2 -2
  508. package/packages/runtime/src/audit/policy-pack.ts +62 -62
  509. package/packages/runtime/src/compiler/graph-compiler.ts +67 -3
  510. package/packages/runtime/src/compiler/index.ts +1 -1
  511. package/packages/runtime/src/context/context-pack-store.ts +197 -197
  512. package/packages/runtime/src/context/context-profiles.ts +60 -60
  513. package/packages/runtime/src/context/index.ts +3 -3
  514. package/packages/runtime/src/decision/decision-engine.ts +174 -174
  515. package/packages/runtime/src/decision/decision-memo.ts +211 -211
  516. package/packages/runtime/src/decision/index.ts +2 -2
  517. package/packages/runtime/src/delivery/branch-manager.ts +91 -91
  518. package/packages/runtime/src/delivery/ci-checks.ts +285 -285
  519. package/packages/runtime/src/delivery/delivery-records.ts +75 -75
  520. package/packages/runtime/src/delivery/index.ts +5 -5
  521. package/packages/runtime/src/delivery/pr-manager.ts +112 -112
  522. package/packages/runtime/src/delivery/promotion-pipeline.ts +65 -2
  523. package/packages/runtime/src/events/bus.ts +92 -92
  524. package/packages/runtime/src/events/catalog.ts +29 -0
  525. package/packages/runtime/src/events/envelope.ts +14 -14
  526. package/packages/runtime/src/events/index.ts +3 -3
  527. package/packages/runtime/src/evidence/evidence-store.ts +130 -130
  528. package/packages/runtime/src/evidence/index.ts +1 -1
  529. package/packages/runtime/src/executor/action-tool-map.ts +52 -50
  530. package/packages/runtime/src/executor/adapters/antigravity-cli.ts +619 -0
  531. package/packages/runtime/src/executor/adapters/claude-cli.ts +367 -0
  532. package/packages/runtime/src/executor/adapters/grok-cli.ts +392 -0
  533. package/packages/runtime/src/executor/adapters/http-openai.ts +16 -0
  534. package/packages/runtime/src/executor/adapters/registry.ts +53 -0
  535. package/packages/runtime/src/executor/adapters/types.ts +24 -0
  536. package/packages/runtime/src/executor/built-in-tools.ts +525 -305
  537. package/packages/runtime/src/executor/index.ts +23 -6
  538. package/packages/runtime/src/executor/llm-task-executor.ts +854 -236
  539. package/packages/runtime/src/executor/node-context.ts +226 -0
  540. package/packages/runtime/src/executor/node-prompt-builder.ts +69 -62
  541. package/packages/runtime/src/executor/quota-patterns.ts +41 -0
  542. package/packages/runtime/src/executor/shell-argv.ts +144 -0
  543. package/packages/runtime/src/executor/stream-completion.ts +230 -145
  544. package/packages/runtime/src/gate/gate-manager.ts +289 -289
  545. package/packages/runtime/src/gate/index.ts +1 -1
  546. package/packages/runtime/src/index.ts +12 -0
  547. package/packages/runtime/src/models/attempt.ts +19 -19
  548. package/packages/runtime/src/models/evidence.ts +21 -21
  549. package/packages/runtime/src/models/failure.ts +22 -13
  550. package/packages/runtime/src/models/gate-decision.ts +25 -25
  551. package/packages/runtime/src/models/index.ts +8 -8
  552. package/packages/runtime/src/models/run.ts +1 -0
  553. package/packages/runtime/src/models/session.ts +11 -11
  554. package/packages/runtime/src/models/verification-result.ts +10 -10
  555. package/packages/runtime/src/models/work-item.ts +25 -25
  556. package/packages/runtime/src/models/workspace.ts +31 -31
  557. package/packages/runtime/src/plugins/capability-matrix.ts +126 -126
  558. package/packages/runtime/src/plugins/index.ts +5 -5
  559. package/packages/runtime/src/plugins/plugin-manifest.ts +118 -118
  560. package/packages/runtime/src/policy/index.ts +1 -1
  561. package/packages/runtime/src/policy/policy-engine.ts +330 -330
  562. package/packages/runtime/src/program/index.ts +1 -0
  563. package/packages/runtime/src/program/program-model.ts +293 -0
  564. package/packages/runtime/src/projection/index.ts +1 -1
  565. package/packages/runtime/src/projection/projection-engine.ts +61 -3
  566. package/packages/runtime/src/reducers/debug-reducer.ts +36 -36
  567. package/packages/runtime/src/reducers/index.ts +2 -2
  568. package/packages/runtime/src/reducers/run-state-reducer.ts +44 -5
  569. package/packages/runtime/src/scheduler/agent-registry.ts +132 -132
  570. package/packages/runtime/src/scheduler/agent-roles.ts +109 -109
  571. package/packages/runtime/src/scheduler/index.ts +4 -4
  572. package/packages/runtime/src/scheduler/run-journal.ts +47 -2
  573. package/packages/runtime/src/scheduler/scheduler.ts +1242 -99
  574. package/packages/runtime/src/verification/contract-exports.ts +203 -0
  575. package/packages/runtime/src/verification/index.ts +1 -0
  576. package/packages/runtime/src/verification/runner-timeout.ts +17 -0
  577. package/packages/runtime/src/verification/test-report-parsers.ts +204 -0
  578. package/packages/runtime/src/verification/verification-compiler.ts +508 -40
  579. package/packages/runtime/src/verification/verification-manifest.ts +44 -4
  580. package/packages/runtime/src/workspace/index.ts +2 -1
  581. package/packages/runtime/src/workspace/strategies/ephemeral-container.ts +44 -11
  582. package/packages/runtime/src/workspace/strategies/git-worktree.ts +104 -1
  583. package/packages/runtime/src/workspace/strategies/inplace.ts +38 -38
  584. package/packages/runtime/src/workspace/workspace-manager.ts +16 -16
  585. package/vscode-extension/LICENSE +21 -21
  586. package/vscode-extension/package.json +1 -1
  587. package/vscode-extension/src/shared/contextLoader.js +137 -137
  588. package/vscode-extension/src/shared/contractBuilder.js +159 -159
  589. package/vscode-extension/src/shared/stateReader.js +101 -101
  590. package/docs/oxe-artifact-map.html +0 -1172
@@ -0,0 +1,1561 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * OXB-C1 (P1 #1–#4): single-task / multi-task `runtime promote` hardening:
5
+ * 1. `selectPromoteQuickCommits` — includes `OXE-Quick` commits of the task's card (or naming the task) made since the
6
+ * previous checkpoint on that card (or preceding checkpoint), in history order; warns & skips if a quick touches
7
+ * another task's files.
8
+ * 2. `reconcilePromotedRatchets` & `checkPromotedEnforcedTargets` — recalculates `lint.ratchets` caps in the promote
9
+ * worktree against `base + task` so program-wide caps lower than `base + task`'s real count never break `main` CI;
10
+ * warns when `enforced.lock.json` promotes a target to `enforced` whose selector is absent from `main`'s
11
+ * conformance scene, proposing `pending` with reason.
12
+ * 3. `analyzeUnpromotedDependencies` — finds unpromoted tasks in `base..HEAD` whose commits share modified files or
13
+ * define/modify modules/symbols imported by the promoted task, suggesting the topological promotion order (and
14
+ * blocking when `--strict` is set).
15
+ * 4. `discoverMainCiRiskSuites` & `buildPreviewCiCommands` — identifies `axe`/`a11y-surfaces`/`conformance` and `e2e`
16
+ * suites on `main` covering the touched components (for the PR body risk section and `promote --preview-ci`).
17
+ */
18
+
19
+ const fs = require('fs');
20
+ const path = require('path');
21
+ const { spawnSync } = require('child_process');
22
+
23
+ const norm = (p) => String(typeof p === 'string' ? p : (p && p.path) || '').replace(/\\/g, '/').replace(/^\.\//, '');
24
+
25
+ const QUICK_RE = /^OXE-Quick:\s*(Q-\d{8}-[a-z0-9]{4})\s*$/im;
26
+ const CARD_RE = /^OXE-Card:\s*([A-Za-z][A-Za-z0-9]*-\d+|\d+)\s*$/im;
27
+ const TASK_TRAILER_RE = /^OXE-Task:\s*(?:([A-Za-z][\w.-]*)\/)?(T(?:\d[\w.-]*|-[A-Za-z0-9][\w.-]*))\s*$/gm;
28
+
29
+ function gitOut(cwd, args) {
30
+ const r = spawnSync('git', ['-c', 'core.quotepath=false', ...args], {
31
+ cwd,
32
+ encoding: 'utf8',
33
+ windowsHide: true,
34
+ maxBuffer: 64 * 1024 * 1024,
35
+ });
36
+ return { ok: r.status === 0, status: r.status, stdout: String(r.stdout || ''), stderr: String(r.stderr || '') };
37
+ }
38
+
39
+ function gitLines(cwd, args) {
40
+ const r = gitOut(cwd, args);
41
+ return r.ok ? r.stdout.split(/\r?\n/).filter(Boolean) : [];
42
+ }
43
+
44
+ function parseTaskTrailers(body, currentPhase) {
45
+ const out = [];
46
+ for (const m of String(body || '').matchAll(TASK_TRAILER_RE)) {
47
+ const ph = m[1] || null;
48
+ const id = String(m[2] || '').toUpperCase();
49
+ if (currentPhase && ph && ph.toUpperCase() !== String(currentPhase).toUpperCase()) continue;
50
+ out.push({ phase: ph, id });
51
+ }
52
+ return out;
53
+ }
54
+
55
+ /**
56
+ * Resolves the ALM card key(s) associated with a plan task (from task fields or `.oxe/program` ALM mapping).
57
+ */
58
+ function resolveTaskCards(projectRoot, programDir, config, phaseId, task) {
59
+ const keys = new Set();
60
+ for (const raw of [task && task.card, task && task.alm_key, task && task.key, ...(Array.isArray(task && task.cards) ? task.cards : [])]) {
61
+ if (typeof raw === 'string' && raw.trim()) keys.add(raw.trim().toUpperCase());
62
+ }
63
+ try {
64
+ const almLib = require('./oxe-alm.cjs');
65
+ const almCfg = almLib.almConfig(config || {});
66
+ if (almCfg && task && task.id) {
67
+ const k = almLib.keyFor(programDir || path.join(projectRoot, '.oxe', 'program'), almCfg, phaseId || null, task.id);
68
+ if (k) keys.add(String(k).trim().toUpperCase());
69
+ }
70
+ } catch { /* no ALM */ }
71
+ return keys;
72
+ }
73
+
74
+ /**
75
+ * P1.1: Selects `OXE-Quick` commits in `range` (`baseSha..HEAD`) that belong to the promoted `planTasks`.
76
+ *
77
+ * A quick belongs to `planTasks` when:
78
+ * - it carries an `OXE-Task` trailer naming one of `taskIds`, OR its commit message / `.oxe/quick/<id>.json` objective
79
+ * explicitly mentions `\bT<n>\b` (not qualified by another phase), OR
80
+ * - its `OXE-Card` (from trailer or `.oxe/quick/<id>.json`) matches one of `planTasks`' cards AND the commit sits
81
+ * after any earlier done task's checkpoint on that same card (and not in a window before a prior checkpoint that
82
+ * already closed another task of the same card).
83
+ *
84
+ * Safety rule: if a matching quick modifies a file outside `planTasks`' scope that belongs to another active task in
85
+ * `PLAN.json` (or that another task already modified in `range`), it is NOT cherry-picked and emits a warning instead.
86
+ */
87
+ function selectPromoteQuickCommits(projectRoot, {
88
+ range,
89
+ orderedTaskShas,
90
+ planTasks,
91
+ allTasks = [],
92
+ phase = null,
93
+ programDir = null,
94
+ config = {},
95
+ }) {
96
+ const idSet = new Set((planTasks || []).map((t) => String(t.id).toUpperCase()));
97
+ const existingSet = new Set(orderedTaskShas || []);
98
+ const allRangeShas = gitLines(projectRoot, ['rev-list', '--reverse', '--topo-order', range]);
99
+ if (!allRangeShas.length) return { quicks: [], skipped: [], warnings: [] };
100
+
101
+ const quickLib = (() => { try { return require('./oxe-quick.cjs'); } catch { return null; } })();
102
+ const testScope = require('./oxe-test-scope.cjs');
103
+
104
+ // Card keys of promoted tasks vs other tasks on the same card
105
+ const ourCards = new Set();
106
+ for (const t of planTasks || []) {
107
+ for (const k of resolveTaskCards(projectRoot, programDir, config, phase, t)) ourCards.add(k);
108
+ }
109
+ const otherTasks = (allTasks || []).filter((t) => t && !idSet.has(String(t.id).toUpperCase()) && !t.superseded && !t.merged_into);
110
+ const otherByCard = new Map();
111
+ for (const o of otherTasks) {
112
+ for (const k of resolveTaskCards(projectRoot, programDir, config, phase, o)) {
113
+ if (!otherByCard.has(k)) otherByCard.set(k, []);
114
+ otherByCard.get(k).push(o);
115
+ }
116
+ }
117
+
118
+ const ownScope = (planTasks || []).flatMap((t) => (t.files || []).map(norm)).filter(Boolean);
119
+ const inOwnScope = (f) => ownScope.some((s) => testScope.covers(s, f));
120
+ const otherTaskScopes = otherTasks.map((o) => ({
121
+ id: String(o.id).toUpperCase(),
122
+ wave: Number.isFinite(Number(o.wave)) ? Number(o.wave) : null,
123
+ files: (o.files || []).map(norm).filter(Boolean),
124
+ }));
125
+
126
+ // Metadata of every commit in range
127
+ const shaIndex = new Map();
128
+ const commitMeta = new Map();
129
+ const otherCommitsByFile = new Map(); // file -> Set<otherTaskId>
130
+ const lastCheckpointIdxByTask = new Map();
131
+
132
+ allRangeShas.forEach((sha, idx) => {
133
+ shaIndex.set(sha, idx);
134
+ const body = gitOut(projectRoot, ['log', '-1', '--format=%B', sha]).stdout;
135
+ const files = gitLines(projectRoot, ['show', '--name-only', '--format=', '--no-renames', sha]).map(norm).filter((f) => f && !f.startsWith('.oxe/'));
136
+ const taskTrailers = parseTaskTrailers(body, phase);
137
+ for (const tr of taskTrailers) {
138
+ lastCheckpointIdxByTask.set(tr.id, idx);
139
+ if (!idSet.has(tr.id)) {
140
+ for (const f of files) {
141
+ if (!otherCommitsByFile.has(f)) otherCommitsByFile.set(f, new Set());
142
+ otherCommitsByFile.get(f).add(tr.id);
143
+ }
144
+ }
145
+ }
146
+ commitMeta.set(sha, { idx, body, files, taskTrailers });
147
+ });
148
+ for (const o of otherTasks) {
149
+ if (o.done_commit) {
150
+ const full = gitLines(projectRoot, ['rev-parse', '--verify', `${o.done_commit}^{commit}`])[0];
151
+ if (full && shaIndex.has(full)) lastCheckpointIdxByTask.set(String(o.id).toUpperCase(), shaIndex.get(full));
152
+ }
153
+ }
154
+
155
+ // Earliest commit index of our promoted tasks (if any)
156
+ const ourIndices = (orderedTaskShas || []).map((s) => shaIndex.get(s)).filter((x) => x !== undefined);
157
+ const firstOurIdx = ourIndices.length ? Math.min(...ourIndices) : 0;
158
+ // Immediate previous task checkpoint index before our first commit (general lower bound for task-less card quicks when earlier tasks share card)
159
+ const minWave = Math.min(...(planTasks || []).map((t) => (Number.isFinite(Number(t.wave)) ? Number(t.wave) : Infinity)));
160
+
161
+ const quicks = [];
162
+ const skipped = [];
163
+ const warnings = [];
164
+
165
+ const mentionsOurTask = (text) => {
166
+ for (const id of idSet) {
167
+ // Match `T34` or `F6/T34`, but NOT `F5/T34` when phase is `F6`
168
+ const re = new RegExp(`(?:([A-Za-z][\\w.-]*)/)?\\b${id}\\b`, 'gi');
169
+ for (const m of String(text || '').matchAll(re)) {
170
+ if (m[1] && phase && m[1].toUpperCase() !== String(phase).toUpperCase()) continue;
171
+ return true;
172
+ }
173
+ }
174
+ return false;
175
+ };
176
+
177
+ for (const sha of allRangeShas) {
178
+ if (existingSet.has(sha)) continue;
179
+ const meta = commitMeta.get(sha);
180
+ if (!meta) continue;
181
+ // Skip commits that belong to another task's OXE-Task trailer
182
+ if (meta.taskTrailers.some((tr) => !idSet.has(tr.id))) continue;
183
+
184
+ const qm = QUICK_RE.exec(meta.body);
185
+ if (!qm) continue;
186
+ const quickId = qm[1];
187
+ const rec = quickLib ? quickLib.read(projectRoot, quickId) : null;
188
+ const cardMatch = CARD_RE.exec(meta.body);
189
+ const quickCard = String((cardMatch && cardMatch[1]) || (rec && rec.key) || '').trim().toUpperCase() || null;
190
+ const combinedText = `${meta.body}\n${(rec && rec.objective) || ''}`;
191
+
192
+ const directTaskMatch = meta.taskTrailers.some((tr) => idSet.has(tr.id)) || mentionsOurTask(combinedText);
193
+ let cardWindowMatch = false;
194
+ if (!directTaskMatch && quickCard && ourCards.has(quickCard)) {
195
+ const siblings = otherByCard.get(quickCard) || [];
196
+ // Previous checkpoint on the same card: max checkpoint index of done sibling tasks that preceded our task
197
+ let lowerBound = -1;
198
+ let upperBound = Infinity;
199
+ for (const sib of siblings) {
200
+ const sibId = String(sib.id).toUpperCase();
201
+ const sibIdx = lastCheckpointIdxByTask.get(sibId);
202
+ if (sibIdx === undefined) continue;
203
+ const sibWave = Number.isFinite(Number(sib.wave)) ? Number(sib.wave) : Infinity;
204
+ if (sibIdx < firstOurIdx || sibWave < minWave) {
205
+ if (sibIdx > lowerBound) lowerBound = sibIdx;
206
+ } else if (sibIdx > firstOurIdx && sib.done === true) {
207
+ if (sibIdx < upperBound) upperBound = sibIdx;
208
+ }
209
+ }
210
+ cardWindowMatch = meta.idx > lowerBound && meta.idx < upperBound;
211
+ }
212
+
213
+ if (!directTaskMatch && !cardWindowMatch) {
214
+ // OXB-C23-1 (152chat T9, b14246ae3): a quick outside the card window that still changes the task's own files
215
+ // is never dropped in silence — the PR would lack the feature.
216
+ const own = meta.files.filter((f) => inOwnScope(f));
217
+ if (own.length) {
218
+ warnings.push(`quick ${sha.slice(0, 8)} (${quickId}${quickCard ? `, ${quickCard}` : ''}) mexe nos arquivos de ${[...idSet].join(',')} (${own.slice(0, 4).join(', ')}) e não vai no PR: fora da janela do cartão/sem citar a tarefa — confira; se for da tarefa, cite ${[...idSet].join(',')} no quick (OXE-Task) ou leve o commit à mão [OXB-C23-1]`);
219
+ skipped.push({ sha, quick: quickId, card: quickCard, reason: 'outside_card_window', own_files: own });
220
+ }
221
+ continue;
222
+ }
223
+
224
+ // Check if this quick touches files belonging to ANOTHER task
225
+ const foreignTouches = [];
226
+ for (const f of meta.files) {
227
+ const committedByOther = [...(otherCommitsByFile.get(f) || [])];
228
+ const scopedToOther = !inOwnScope(f)
229
+ ? otherTaskScopes.filter((o) => o.files.some((sf) => testScope.covers(sf, f))).map((o) => o.id)
230
+ : [];
231
+ const owners = [...new Set([...committedByOther, ...scopedToOther])];
232
+ if (owners.length) foreignTouches.push({ file: f, tasks: owners });
233
+ }
234
+
235
+ if (foreignTouches.length) {
236
+ const ownerIds = [...new Set(foreignTouches.flatMap((x) => x.tasks))];
237
+ const touchedList = foreignTouches.map((x) => `${x.file} (${x.tasks.join(', ')})`).slice(0, 4).join(', ');
238
+ skipped.push({ sha, quick: quickId, card: quickCard, foreign: foreignTouches });
239
+ warnings.push(
240
+ `quick ${sha.slice(0, 8)} (${quickId}${quickCard ? `, ${quickCard}` : ''}) não foi incluído no promote: toca arquivo(s) de outra tarefa — ${touchedList}. Leve à mão se seguro ou promova junto (--tasks ${[...idSet, ...ownerIds].join(',')})`
241
+ );
242
+ continue;
243
+ }
244
+
245
+ quicks.push({ sha, quick: quickId, card: quickCard, files: meta.files });
246
+ }
247
+
248
+ return { quicks, skipped, warnings };
249
+ }
250
+
251
+ /**
252
+ * OXB-C2 Adendo (16/11, PRs #882/#883/#886/#894 kicked from merge train):
253
+ * Auto-resolves `git cherry-pick` conflicts when ALL conflicted files are `lint.ratchets` files whose commit diff on
254
+ * `projectRoot` ONLY moved the cap number — keeping `ours` (`base`'s cap line) so sequential task promotes never conflict.
255
+ */
256
+ function tryResolveRatchetCherryPickConflict(projectRoot, work, sha, config, conflictedFiles) {
257
+ const ratchetsLib = require('./oxe-ratchets.cjs');
258
+ const list = ratchetsLib.ratchetsOf(config || {});
259
+ if (!list.length || !Array.isArray(conflictedFiles) || !conflictedFiles.length) return { resolved: false };
260
+ const ratchetFiles = new Set(list.map((r) => norm(r.file)));
261
+ if (!conflictedFiles.every((f) => ratchetFiles.has(norm(f)))) return { resolved: false };
262
+
263
+ for (const f of conflictedFiles) {
264
+ const parentRes = gitOut(projectRoot, ['show', `${sha}^:${norm(f)}`]);
265
+ const commitRes = gitOut(projectRoot, ['show', `${sha}:${norm(f)}`]);
266
+ if (parentRes.status !== 0 || commitRes.status !== 0) return { resolved: false };
267
+ if (!ratchetsLib.onlyCapChanged(parentRes.stdout, commitRes.stdout, config, f)) {
268
+ return { resolved: false };
269
+ }
270
+ }
271
+
272
+ const co = gitOut(work, ['checkout', '--ours', '--', ...conflictedFiles]);
273
+ if (co.status !== 0) return { resolved: false };
274
+ const add = gitOut(work, ['add', '--', ...conflictedFiles]);
275
+ if (add.status !== 0) return { resolved: false };
276
+
277
+ const stagedDiff = gitOut(work, ['diff', '--cached', '--quiet']);
278
+ if (stagedDiff.status === 0) {
279
+ const skip = gitOut(work, ['cherry-pick', '--skip']);
280
+ return { resolved: skip.status === 0, skipped: true, files: conflictedFiles.map(norm) };
281
+ }
282
+ const cont = spawnSync('git', ['-c', 'core.editor=true', 'cherry-pick', '--continue'], {
283
+ cwd: work,
284
+ encoding: 'utf8',
285
+ windowsHide: true,
286
+ env: { ...process.env, GIT_EDITOR: 'true' },
287
+ });
288
+ return { resolved: cont.status === 0, skipped: false, files: conflictedFiles.map(norm) };
289
+ }
290
+
291
+ /**
292
+ * P1.2 (a) + OXB-C2 Adendo revisto (16/11 06:10Z):
293
+ * Reconciles `lint.ratchets` in the promote worktree `work` against `buildSha` (`base` + promoted task).
294
+ * Frozen design-lint tests (e.g. `brd-01`/`brd-03`) require `cap === realCount` ("a trava acompanha o código para baixo"),
295
+ * so whenever the promoted task touched the ratchet file (including auto-resolved cap-only cherry-pick conflicts),
296
+ * violated `base`'s cap, or changed files counted by a tight ratchet on `base`, promote writes `nextCap = realCount`.
297
+ */
298
+ function reconcilePromotedRatchets(work, buildSha, config, options = {}) {
299
+ const ratchetsLib = require('./oxe-ratchets.cjs');
300
+ const testScope = require('./oxe-test-scope.cjs');
301
+ const list = ratchetsLib.ratchetsOf(config || {});
302
+ if (!list.length) return { adjusted: [], files: [] };
303
+
304
+ const changedList = gitLines(work, ['diff', '--name-only', buildSha, 'HEAD']).map(norm);
305
+ const changedInWork = new Set(changedList);
306
+ const resolvedCapSet = new Set((options.resolvedCapFiles || []).map(norm));
307
+ const adjusted = [];
308
+ const files = new Set();
309
+
310
+ for (const r of list) {
311
+ const abs = path.join(work, r.file);
312
+ if (!fs.existsSync(abs)) continue;
313
+ let text = '';
314
+ try { text = fs.readFileSync(abs, 'utf8'); } catch { continue; }
315
+ const cap = ratchetsLib.capOf(text, r);
316
+ if (!cap) continue;
317
+ const baseRes = buildSha ? gitOut(work, ['show', `${buildSha}:${r.file}`]) : { status: 1, stdout: '' };
318
+ const baseText = baseRes.status === 0 ? baseRes.stdout : null;
319
+ const baseCapObj = baseText != null ? ratchetsLib.capOf(baseText, r) : null;
320
+ const baseCap = baseCapObj ? baseCapObj.value : null;
321
+
322
+ const realCount = ratchetsLib.countOf(work, r);
323
+ const touchedHere = changedInWork.has(norm(r.file)) || resolvedCapSet.has(norm(r.file));
324
+ const violated = r.direction === 'down' ? cap.value < realCount : cap.value > realCount;
325
+ const matchesPat = (pat, f) => (pat instanceof RegExp ? pat.test(f) : testScope.covers(pat, f));
326
+ const excludes = Array.isArray(r.exclude) ? r.exclude : [];
327
+ const touchedCountedPath = Array.isArray(r.paths) && r.paths.length
328
+ ? changedList.some((f) => r.paths.some((pat) => matchesPat(pat, f)) && !excludes.some((pat) => matchesPat(pat, f)))
329
+ : false;
330
+
331
+ // Reconcile against the final promoted tree whenever the ratchet file was touched/resolved, cap is violated,
332
+ // or counted source files changed in promote and the real count differs from the current cap (#907 / OXB-C6 #5).
333
+ if (!touchedHere && !violated && !(touchedCountedPath && realCount !== cap.value)) continue;
334
+
335
+ const nextCap = realCount;
336
+ if (nextCap === cap.value) continue;
337
+
338
+ let nextText = text.slice(0, cap.index) + String(nextCap) + text.slice(cap.index + cap.length);
339
+ if (baseText != null && nextText.replace(/\r\n/g, '\n') === baseText.replace(/\r\n/g, '\n')) {
340
+ nextText = baseText;
341
+ }
342
+ fs.writeFileSync(abs, nextText, 'utf8');
343
+ files.add(r.file);
344
+ adjusted.push({
345
+ file: r.file,
346
+ line: cap.line,
347
+ program_cap: cap.value,
348
+ base_cap: baseCap,
349
+ promoted_cap: nextCap,
350
+ real_count: realCount,
351
+ reason: violated ? 'increased_above_cap' : 'matched_real_count',
352
+ });
353
+ }
354
+
355
+ return { adjusted, files: [...files] };
356
+ }
357
+
358
+ function extractEnforcedEntries(doc) {
359
+ const out = new Map(); // id -> { status, selector }
360
+ if (!doc || typeof doc !== 'object') return out;
361
+ if (Array.isArray(doc)) {
362
+ for (const item of doc) {
363
+ if (item && typeof item === 'object' && item.id) {
364
+ out.set(String(item.id), { status: String(item.status || item.state || ''), selector: item.selector || item.query || null });
365
+ }
366
+ }
367
+ return out;
368
+ }
369
+ if (Array.isArray(doc.enforced)) {
370
+ for (const id of doc.enforced) out.set(String(id), { status: 'enforced', selector: null });
371
+ }
372
+ const container = (doc.targets && typeof doc.targets === 'object' && !Array.isArray(doc.targets))
373
+ ? doc.targets
374
+ : (doc.entries && typeof doc.entries === 'object' && !Array.isArray(doc.entries))
375
+ ? doc.entries
376
+ : doc;
377
+ for (const [k, v] of Object.entries(container)) {
378
+ if (['schema', 'schema_version', 'version', 'updated_at', 'generated_at', 'enforced'].includes(k)) continue;
379
+ if (typeof v === 'string') out.set(k, { status: v, selector: null });
380
+ else if (v && typeof v === 'object') {
381
+ out.set(k, { status: String(v.status || v.state || (v.enforced === true ? 'enforced' : '')), selector: v.selector || v.query || null });
382
+ }
383
+ }
384
+ return out;
385
+ }
386
+
387
+ function extractSelectorTokens(selector, targetId) {
388
+ const tokens = [];
389
+ const s = String(selector || '').trim();
390
+ if (s) {
391
+ for (const m of s.matchAll(/\[([a-zA-Z0-9_-]+)(?:[~|^$*]?=["']?([^\]"']+)["']?)?\]/g)) {
392
+ if (m[2]) tokens.push(m[2]);
393
+ else tokens.push(m[1]);
394
+ }
395
+ for (const m of s.matchAll(/([.#][A-Za-z_-][\w-]*)/g)) tokens.push(m[1].slice(1));
396
+ }
397
+ if (!tokens.length && targetId) {
398
+ // e.g. `BRD-13.branch.font-family` -> surface segment `branch`
399
+ const parts = String(targetId).split('.');
400
+ if (parts.length >= 2 && !/^BRD-\d+$/i.test(parts[1])) tokens.push(parts[1]);
401
+ }
402
+ return [...new Set(tokens.filter((t) => t && t.length >= 3))];
403
+ }
404
+
405
+ /**
406
+ * P1.2 (b): Checks `*enforced*.json` files changed in `work` (`buildSha..HEAD`). For entries newly promoted to
407
+ * `enforced`, verifies that `work`'s conformance scene files contain the target's selector/hook; otherwise warns and
408
+ * proposes `"pending"` with the reason.
409
+ */
410
+ function checkPromotedEnforcedTargets(work, buildSha, { base = 'main', config = {} } = {}) {
411
+ const changed = gitLines(work, ['diff', '--name-only', buildSha, 'HEAD']).map(norm);
412
+ const lockFiles = changed.filter((f) => /(^|\/)[^/]*enforced[^/]*\.json$/i.test(f));
413
+ if (!lockFiles.length) return { gaps: [], warnings: [] };
414
+
415
+ const allFiles = gitLines(work, ['ls-files']).map(norm);
416
+ const configuredScenes = (config && config.promote && Array.isArray(config.promote.conformance_scenes))
417
+ ? config.promote.conformance_scenes.map(norm)
418
+ : [];
419
+ const sceneFiles = configuredScenes.length
420
+ ? allFiles.filter((f) => configuredScenes.some((s) => f === s || f.startsWith(s)))
421
+ : allFiles.filter((f) => /(conformance|brand-scene|brand-targets|brand.*fixture|conformance.*scene)/i.test(f) && !/enforced[^/]*\.json$/i.test(f));
422
+ if (!sceneFiles.length) return { gaps: [], warnings: [] };
423
+
424
+ // Optional target definitions (selectors by target id) in brand target files
425
+ const selectorByTarget = new Map();
426
+ for (const tf of allFiles.filter((f) => /(brand[-_]?targets|conformance[-_]?targets)\.[cm]?[jt]sx?$|\.json$/i.test(f) && /brand|conformance/i.test(f)).slice(0, 20)) {
427
+ let txt = '';
428
+ try { txt = fs.readFileSync(path.join(work, tf), 'utf8'); } catch { continue; }
429
+ for (const m of txt.matchAll(/['"`](BRD-\d+(?:\.[\w-]+)+)['"`][\s\S]{0,240}?selector\s*:\s*['"`]([^'"`]+)['"`]/g)) {
430
+ selectorByTarget.set(m[1], m[2]);
431
+ }
432
+ }
433
+
434
+ const sceneCorpus = sceneFiles.map((f) => {
435
+ try { return fs.readFileSync(path.join(work, f), 'utf8'); } catch { return ''; }
436
+ }).join('\n');
437
+
438
+ const gaps = [];
439
+ const warnings = [];
440
+
441
+ for (const lf of lockFiles) {
442
+ let afterDoc = null;
443
+ let beforeDoc = null;
444
+ try { afterDoc = JSON.parse(fs.readFileSync(path.join(work, lf), 'utf8')); } catch { continue; }
445
+ const baseShow = gitOut(work, ['show', `${buildSha}:${lf}`]);
446
+ if (baseShow.ok) {
447
+ try { beforeDoc = JSON.parse(baseShow.stdout); } catch { beforeDoc = null; }
448
+ }
449
+ const afterMap = extractEnforcedEntries(afterDoc);
450
+ const beforeMap = extractEnforcedEntries(beforeDoc);
451
+
452
+ for (const [id, info] of afterMap) {
453
+ if (info.status !== 'enforced') continue;
454
+ const prev = beforeMap.get(id);
455
+ if (prev && prev.status === 'enforced') continue;
456
+
457
+ const selector = info.selector || selectorByTarget.get(id) || null;
458
+ const tokens = extractSelectorTokens(selector, id);
459
+ if (!tokens.length) continue;
460
+
461
+ const present = tokens.some((tok) => sceneCorpus.includes(tok));
462
+ if (!present) {
463
+ const proposal = {
464
+ file: lf,
465
+ id,
466
+ selector: selector || tokens.join(', '),
467
+ proposed_status: 'pending',
468
+ proposed_reason: `cena de conformidade em ${base} ainda não monta ${selector || tokens[0]} (evita "measured no element")`,
469
+ };
470
+ gaps.push(proposal);
471
+ warnings.push(
472
+ `${lf} promove ${id} como "enforced", mas a cena de conformidade em ${base} não tem o seletor \`${proposal.selector}\` ("measured no element") — mantenha como "pending" com motivo: "${proposal.proposed_reason}"`
473
+ );
474
+ }
475
+ }
476
+ }
477
+
478
+ return { gaps, warnings };
479
+ }
480
+
481
+ /**
482
+ * P1.3: Finds unpromoted tasks in `range` (`baseSha..HEAD`) that the promoted `planTasks` touch or import from
483
+ * (shared modified files or imported files/symbols created or changed by another unpromoted task), returning a
484
+ * suggested topological promotion order.
485
+ */
486
+ function analyzeUnpromotedDependencies(projectRoot, {
487
+ range,
488
+ baseSha,
489
+ orderedTaskShas,
490
+ planTasks,
491
+ phase = null,
492
+ stackedTaskIds = [],
493
+ }) {
494
+ const idSet = new Set((planTasks || []).map((t) => String(t.id).toUpperCase()));
495
+ const stackedSet = new Set((stackedTaskIds || []).map((id) => String(id).toUpperCase()));
496
+ const allRangeShas = gitLines(projectRoot, ['rev-list', '--reverse', '--topo-order', range]);
497
+ if (!allRangeShas.length) return { dependencies: [], suggested_order: [], warnings: [] };
498
+
499
+ const CODE_RE = /\.(c|m)?[jt]sx?$/i;
500
+ const pb = require('./oxe-plan-build.cjs');
501
+
502
+ // Map other tasks' commits & touched files in range
503
+ const otherTaskInfo = new Map(); // taskId -> { task, shas: [], files: Set, firstIdx: number }
504
+ const fileOwners = new Map(); // file -> Set<taskId>
505
+ const ourFiles = new Set();
506
+
507
+ const ourShaSet = new Set(orderedTaskShas || []);
508
+ allRangeShas.forEach((sha, idx) => {
509
+ const files = gitLines(projectRoot, ['show', '--name-only', '--format=', '--no-renames', sha]).map(norm).filter((f) => f && !f.startsWith('.oxe/'));
510
+ if (ourShaSet.has(sha)) {
511
+ for (const f of files) ourFiles.add(f);
512
+ return;
513
+ }
514
+ const body = gitOut(projectRoot, ['log', '-1', '--format=%B', sha]).stdout;
515
+ const trailers = parseTaskTrailers(body, phase);
516
+ for (const tr of trailers) {
517
+ if (idSet.has(tr.id) || stackedSet.has(tr.id)) continue;
518
+ if (!otherTaskInfo.has(tr.id)) otherTaskInfo.set(tr.id, { task: tr.id, shas: [], files: new Set(), firstIdx: idx });
519
+ const entry = otherTaskInfo.get(tr.id);
520
+ entry.shas.push(sha);
521
+ for (const f of files) {
522
+ entry.files.add(f);
523
+ if (!fileOwners.has(f)) fileOwners.set(f, new Set());
524
+ fileOwners.get(f).add(tr.id);
525
+ }
526
+ }
527
+ });
528
+
529
+ if (!otherTaskInfo.size) return { dependencies: [], suggested_order: [], warnings: [] };
530
+
531
+ const ourFirstIdx = (() => {
532
+ const idxs = allRangeShas.map((s, i) => (ourShaSet.has(s) ? i : -1)).filter((i) => i >= 0);
533
+ return idxs.length ? Math.min(...idxs) : Infinity;
534
+ })();
535
+
536
+ // Check imports from our modified code files at HEAD into files created/modified by other unpromoted tasks
537
+ const tracked = new Set(gitLines(projectRoot, ['ls-files']).map(norm));
538
+ const aliases = pb.loadPathAliases(projectRoot);
539
+ const importedByUs = new Map(); // targetFile -> Set<symbolName | '*'>
540
+ for (const f of ourFiles) {
541
+ if (!CODE_RE.test(f)) continue;
542
+ let src = '';
543
+ try { src = fs.readFileSync(path.join(projectRoot, f), 'utf8'); } catch { continue; }
544
+ for (const imp of pb.extractModuleImports(src)) {
545
+ const resolved = pb.resolveModuleSpecifier(f, imp.specifier, tracked, aliases);
546
+ if (!resolved || ourFiles.has(resolved)) continue;
547
+ if (!importedByUs.has(resolved)) importedByUs.set(resolved, new Set());
548
+ const bucket = importedByUs.get(resolved);
549
+ if (imp.wildcard || !(imp.names && imp.names.length)) bucket.add('*');
550
+ else for (const n of imp.names) bucket.add(n);
551
+ }
552
+ }
553
+
554
+ // Symbols newly added on HEAD vs baseSha in a file
555
+ const baseTextCache = new Map();
556
+ const textAtBase = (f) => {
557
+ if (!baseTextCache.has(f)) {
558
+ const r = gitOut(projectRoot, ['show', `${baseSha}:${f}`]);
559
+ baseTextCache.set(f, r.ok ? r.stdout : null);
560
+ }
561
+ return baseTextCache.get(f);
562
+ };
563
+
564
+ const depMap = new Map(); // otherTaskId -> { task, firstIdx, shared_files: Set, imported_files: Map<file, string[]>, before_us: boolean }
565
+ const ensureDep = (tid) => {
566
+ if (!depMap.has(tid)) {
567
+ const info = otherTaskInfo.get(tid);
568
+ depMap.set(tid, {
569
+ task: tid,
570
+ firstIdx: info ? info.firstIdx : 0,
571
+ shas: info ? info.shas : [],
572
+ shared_files: new Set(),
573
+ imported_files: new Map(),
574
+ before_us: info ? info.firstIdx < ourFirstIdx : false,
575
+ });
576
+ }
577
+ return depMap.get(tid);
578
+ };
579
+
580
+ // (a) Shared modified files
581
+ for (const f of ourFiles) {
582
+ for (const owner of fileOwners.get(f) || []) {
583
+ ensureDep(owner).shared_files.add(f);
584
+ }
585
+ }
586
+
587
+ // (b) Imported files / symbols modified or created by another unpromoted task
588
+ for (const [targetFile, syms] of importedByUs) {
589
+ const owners = fileOwners.get(targetFile);
590
+ if (!owners || !owners.size) continue;
591
+ const before = textAtBase(targetFile);
592
+ const isNewFile = before === null;
593
+ const requestedSyms = [...syms].filter((s) => s !== '*');
594
+ // Either the file is brand-new after baseSha, or it changed in range and we import symbols from it
595
+ const newOrChangedSyms = isNewFile
596
+ ? (requestedSyms.length ? requestedSyms : ['(arquivo novo)'])
597
+ : requestedSyms.filter((sym) => !new RegExp(`\\b${sym.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`).test(before));
598
+ // Even if an existing symbol's signature/props changed (like PaneHeader), importing a component modified by To is a dependency!
599
+ const relevantSyms = newOrChangedSyms.length ? newOrChangedSyms : (requestedSyms.length ? requestedSyms : [path.posix.basename(targetFile)]);
600
+ for (const owner of owners) {
601
+ const d = ensureDep(owner);
602
+ d.imported_files.set(targetFile, relevantSyms);
603
+ }
604
+ }
605
+
606
+ const dependencies = [...depMap.values()]
607
+ .sort((a, b) => a.firstIdx - b.firstIdx)
608
+ .map((d) => ({
609
+ task: d.task,
610
+ shas: d.shas,
611
+ before_us: d.before_us,
612
+ shared_files: [...d.shared_files],
613
+ imports: [...d.imported_files.entries()].map(([file, symbols]) => ({ file, symbols })),
614
+ }));
615
+
616
+ if (!dependencies.length) return { dependencies: [], suggested_order: [], warnings: [] };
617
+
618
+ // Topological / commit-order suggestion: dependencies whose commits precede us (or provide imports to us) go BEFORE us;
619
+ // tasks that only share a file AFTER us go after us (or together via --tasks)
620
+ const mustPrecede = dependencies.filter((d) => d.imports.length > 0 || d.before_us).map((d) => d.task);
621
+ const afterUs = dependencies.filter((d) => !mustPrecede.includes(d.task)).map((d) => d.task);
622
+ const ourLabel = [...idSet].join(',');
623
+ const suggestedOrder = [...mustPrecede, ourLabel, ...afterUs];
624
+
625
+ const parts = dependencies.map((d) => {
626
+ const reasons = [];
627
+ if (d.imports.length) {
628
+ reasons.push(`importa ${d.imports.map((x) => `${x.symbols.join('/')} de ${x.file}`).slice(0, 3).join(', ')}`);
629
+ }
630
+ if (d.shared_files.length) {
631
+ reasons.push(`compartilha ${d.shared_files.slice(0, 3).join(', ')}`);
632
+ }
633
+ return `${d.task} (${reasons.join('; ')})`;
634
+ });
635
+
636
+ const warnings = [
637
+ `dependência(s) não promovida(s) fora da base: ${parts.join(' · ')} — ordem sugerida: ${suggestedOrder.join(' → ')}${mustPrecede.length ? ` (ou promova junto: oxe-cc runtime promote --tasks ${[...mustPrecede, ...idSet].join(',')})` : ''}`,
638
+ ];
639
+
640
+ return { dependencies, must_precede: mustPrecede, suggested_order: suggestedOrder, warnings };
641
+ }
642
+
643
+ function componentSearchTerms(filePath) {
644
+ const base = path.posix.basename(filePath).replace(/\.[cm]?[jt]sx?$/i, '').replace(/\.(vue|svelte)$/i, '');
645
+ if (!base || ['index', 'types', 'utils', 'constants', 'helpers'].includes(base.toLowerCase())) return [];
646
+ const terms = new Set([base]);
647
+ // PascalCase / camelCase -> kebab-case & spaced words (`ChangesPanel` -> `changes-panel`, `changes panel`)
648
+ if (/[a-z][A-Z]/.test(base)) {
649
+ const kebab = base.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
650
+ const spaced = kebab.replace(/-/g, ' ');
651
+ if (kebab.length >= 5) terms.add(kebab);
652
+ if (spaced.length >= 5) terms.add(spaced);
653
+ }
654
+ return [...terms].filter((t) => t.length >= 4);
655
+ }
656
+
657
+ /**
658
+ * P1.4: Discovers `axe`/`a11y-surfaces`/`conformance` and `e2e` suites in `work` (`main + task`) that cover the touched
659
+ * components/files and are not already in the task's verify or frozen acceptance tests.
660
+ */
661
+ function discoverMainCiRiskSuites(work, changedFiles, { excludeSuites = [] } = {}) {
662
+ const touched = (changedFiles || []).map(norm).filter((f) => f && !f.startsWith('.oxe/') && !/\.(test|spec)\.[cm]?[jt]sx?$/i.test(f));
663
+ if (!touched.length) return [];
664
+
665
+ const allFiles = gitLines(work, ['ls-files']).map(norm);
666
+ const excluded = new Set((excludeSuites || []).map(norm));
667
+ const CI_SUITE_RE = /(^|\/)(e2e|playwright)\/.*\.(spec|test)\.[cm]?[jt]sx?$|\.(e2e|a11y)\.(spec|test)\.[cm]?[jt]sx?$|\/(axe|a11y[-_]?surfaces|brand[-_]?conformance|session[-_]?location)[^/]*\.(spec|test)\.[cm]?[jt]sx?$/i;
668
+
669
+ const candidateSuites = allFiles.filter((f) => !excluded.has(f) && !/(^|\/)parked[^/]*\//i.test(f) && CI_SUITE_RE.test(`/${f}`));
670
+ if (!candidateSuites.length) return [];
671
+
672
+ const termsByFile = new Map();
673
+ for (const f of touched) {
674
+ const terms = componentSearchTerms(f);
675
+ const stem = path.posix.basename(f).replace(/\.[^.]+$/, '');
676
+ if (stem.length >= 4) terms.push(stem);
677
+ if (terms.length) termsByFile.set(f, [...new Set(terms)]);
678
+ }
679
+
680
+ const hits = [];
681
+ for (const suite of candidateSuites) {
682
+ let text = '';
683
+ try { text = fs.readFileSync(path.join(work, suite), 'utf8'); } catch { continue; }
684
+ const lower = text.toLowerCase();
685
+ const matchedFiles = [];
686
+ for (const [srcFile, terms] of termsByFile) {
687
+ if (terms.some((term) => lower.includes(term.toLowerCase()))) {
688
+ matchedFiles.push(srcFile);
689
+ }
690
+ }
691
+ if (matchedFiles.length) {
692
+ const kind = /(axe|a11y)/i.test(suite) ? 'a11y' : /conformance/i.test(suite) ? 'conformance' : 'e2e';
693
+ hits.push({ suite, kind, covers: matchedFiles.slice(0, 4) });
694
+ }
695
+ }
696
+
697
+ return hits;
698
+ }
699
+
700
+ function collectVerifyStringsFromOptions(options = {}) {
701
+ const out = [];
702
+ const push = (v) => {
703
+ if (typeof v === 'string' && v.trim()) out.push(v.trim());
704
+ };
705
+ for (const c of Array.isArray(options.verifyCommands) ? options.verifyCommands : []) push(c);
706
+ const readTaskCmds = (tasks) => {
707
+ for (const t of Array.isArray(tasks) ? tasks : []) {
708
+ if (!t || typeof t !== 'object') continue;
709
+ for (const c of (t.verify && Array.isArray(t.verify.commands)) ? t.verify.commands : []) push(c);
710
+ if (t.verify && t.verify.command) push(t.verify.command);
711
+ if (t.verifyCommand) push(t.verifyCommand);
712
+ }
713
+ };
714
+ readTaskCmds(options.planTasks);
715
+ if (options.planDoc && typeof options.planDoc === 'object') {
716
+ readTaskCmds(options.planDoc.tasks);
717
+ for (const a of Array.isArray(options.planDoc.acceptance_tests) ? options.planDoc.acceptance_tests : []) {
718
+ if (a && a.command) push(a.command);
719
+ }
720
+ }
721
+ return [...new Set(out)];
722
+ }
723
+
724
+ function splitShellSegments(cmd) {
725
+ const out = [];
726
+ let cur = '';
727
+ let q = null;
728
+ const s = String(cmd || '');
729
+ for (let i = 0; i < s.length; i += 1) {
730
+ const ch = s[i];
731
+ if (q) {
732
+ if (ch === q && s[i - 1] !== '\\') q = null;
733
+ cur += ch;
734
+ continue;
735
+ }
736
+ if (ch === '"' || ch === "'") {
737
+ q = ch;
738
+ cur += ch;
739
+ continue;
740
+ }
741
+ if ((ch === '&' && s[i + 1] === '&') || (ch === '|' && s[i + 1] === '|')) {
742
+ if (cur.trim()) out.push(cur.trim());
743
+ cur = '';
744
+ i += 1;
745
+ continue;
746
+ }
747
+ if (ch === ';') {
748
+ if (cur.trim()) out.push(cur.trim());
749
+ cur = '';
750
+ continue;
751
+ }
752
+ cur += ch;
753
+ }
754
+ if (cur.trim()) out.push(cur.trim());
755
+ return out.length ? out : (s.trim() ? [s.trim()] : []);
756
+ }
757
+
758
+ function normalizeRemoteWrapperPrefix(rawPrefix, work, projectRoot) {
759
+ let prefix = String(rawPrefix || '').trim();
760
+ if (!prefix) return '';
761
+ // If wrapper references a relative script outside `work` (e.g. `../deps/scripts/remote-verify.mjs`), resolve
762
+ // relative to `projectRoot` so running inside `.oxe/promote-ws/<task>/` keeps working.
763
+ prefix = prefix.replace(/(["']?)([^\s"']*remote-verify(?:\.[cm]?js)?)\1/i, (full, q, rel) => {
764
+ const clean = rel.replace(/\\/g, '/');
765
+ if (path.isAbsolute(rel) || /^[A-Za-z]:[\\/]/.test(rel)) return full;
766
+ if (projectRoot && clean.startsWith('..')) {
767
+ const fromRoot = path.resolve(projectRoot, clean);
768
+ if (fs.existsSync(fromRoot)) {
769
+ const fwd = fromRoot.replace(/\\/g, '/');
770
+ return /\s/.test(fwd) ? `"${fwd}"` : fwd;
771
+ }
772
+ }
773
+ if (fs.existsSync(path.resolve(work, clean))) return full;
774
+ if (projectRoot) {
775
+ const fromRoot = path.resolve(projectRoot, clean);
776
+ if (fs.existsSync(fromRoot)) {
777
+ const fwd = fromRoot.replace(/\\/g, '/');
778
+ return /\s/.test(fwd) ? `"${fwd}"` : fwd;
779
+ }
780
+ }
781
+ return full;
782
+ });
783
+ return `${prefix} `;
784
+ }
785
+
786
+ function resolvePreviewCiWrapper(work, config = {}, options = {}) {
787
+ const customRunner = config && config.promote && typeof config.promote.preview_ci_runner === 'string'
788
+ ? config.promote.preview_ci_runner.trim()
789
+ : '';
790
+ if (customRunner) {
791
+ const expanded = customRunner
792
+ .replace(/\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, n) => process.env[n] || '')
793
+ .split('{command}')[0]
794
+ .trim();
795
+ if (expanded) return normalizeRemoteWrapperPrefix(expanded, work, options.projectRoot);
796
+ }
797
+
798
+ const isRemoteSeg = (s) => /(?:^|[\s/\\"'])remote-verify(?:\.[cm]?js|\b)/i.test(String(s || ''));
799
+ for (const fullCmd of collectVerifyStringsFromOptions(options)) {
800
+ for (const seg of splitShellSegments(fullCmd)) {
801
+ if (!isRemoteSeg(seg)) continue;
802
+ const idx = seg.indexOf(' -- ');
803
+ if (idx > 0) {
804
+ return normalizeRemoteWrapperPrefix(seg.slice(0, idx + 4), work, options.projectRoot);
805
+ }
806
+ const trailIdx = seg.search(/\s+--$/);
807
+ if (trailIdx > 0) {
808
+ return normalizeRemoteWrapperPrefix(`${seg.slice(0, trailIdx)} --`, work, options.projectRoot);
809
+ }
810
+ }
811
+ }
812
+
813
+ const gatesRunner = config && typeof config.phase_gates_runner === 'string' ? config.phase_gates_runner.trim() : '';
814
+ if (gatesRunner && isRemoteSeg(gatesRunner)) {
815
+ const expanded = gatesRunner
816
+ .replace(/\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, n) => process.env[n] || '')
817
+ .split('{command}')[0]
818
+ .trim();
819
+ if (expanded) return normalizeRemoteWrapperPrefix(expanded, work, options.projectRoot);
820
+ }
821
+
822
+ const candidates = ['scripts/remote-verify.mjs', 'scripts/remote-verify.cjs', 'scripts/remote-verify.js'];
823
+ const inWork = candidates.find((rel) => fs.existsSync(path.join(work, rel)));
824
+ if (inWork) return `node ${inWork} -- `;
825
+ if (options.projectRoot) {
826
+ const inRoot = candidates.find((rel) => fs.existsSync(path.join(options.projectRoot, rel)));
827
+ if (inRoot) {
828
+ const abs = path.resolve(options.projectRoot, inRoot).replace(/\\/g, '/');
829
+ return `node ${/\s/.test(abs) ? `"${abs}"` : abs} -- `;
830
+ }
831
+ }
832
+ return '';
833
+ }
834
+
835
+ function extractPlaywrightTestDirs(cfgRel, cfgText) {
836
+ const cfgDir = path.posix.dirname(norm(cfgRel));
837
+ const resolveRel = (raw) => {
838
+ const clean = String(raw || '').trim().replace(/\\/g, '/');
839
+ if (!clean) return null;
840
+ const joined = cfgDir && cfgDir !== '.' ? path.posix.normalize(path.posix.join(cfgDir, clean)) : path.posix.normalize(clean);
841
+ const out = joined.replace(/^\.\//, '').replace(/\/+$/, '');
842
+ return out === '.' ? '' : out;
843
+ };
844
+ const dirs = [];
845
+ for (const m of String(cfgText || '').matchAll(/\btestDir\s*:\s*(['"`])([^'"`]+)\1/g)) {
846
+ const d = resolveRel(m[2]);
847
+ if (d !== null) dirs.push(d);
848
+ }
849
+ for (const m of String(cfgText || '').matchAll(/\btestDir\s*:\s*path\.(?:join|resolve)\(\s*__dirname\s*,\s*([^)]+)\)/g)) {
850
+ const parts = [...m[1].matchAll(/(['"`])([^'"`]+)\1/g)].map((x) => x[2]);
851
+ if (parts.length) {
852
+ const d = resolveRel(parts.join('/'));
853
+ if (d !== null) dirs.push(d);
854
+ }
855
+ }
856
+ return [...new Set(dirs)];
857
+ }
858
+
859
+ function discoverPlaywrightConfigs(work) {
860
+ const PW_CFG_RE = /(^|\/)playwright(?:\.([^/]+))?\.config\.[cm]?[jt]s$/i;
861
+ const found = new Set();
862
+ for (const f of gitLines(work, ['ls-files']).map(norm)) {
863
+ if (PW_CFG_RE.test(f) && !/(^|\/)(?:node_modules|\.oxe|parked[^/]*)\//i.test(f)) found.add(f);
864
+ }
865
+ const scanDir = (relDir, depth) => {
866
+ if (depth > 2) return;
867
+ const abs = relDir ? path.join(work, relDir) : work;
868
+ let entries = [];
869
+ try { entries = fs.readdirSync(abs, { withFileTypes: true }); } catch { return; }
870
+ for (const e of entries) {
871
+ if (e.name.startsWith('.') || e.name === 'node_modules' || /^parked/i.test(e.name)) continue;
872
+ const rel = relDir ? `${relDir}/${e.name}` : e.name;
873
+ if (e.isFile() && PW_CFG_RE.test(rel)) found.add(rel);
874
+ else if (e.isDirectory() && depth < 2) scanDir(rel, depth + 1);
875
+ }
876
+ };
877
+ scanDir('', 0);
878
+
879
+ return [...found]
880
+ .sort((a, b) => {
881
+ const aDef = /(?:^|\/)playwright\.config\.[cm]?[jt]s$/i.test(a) ? 0 : 1;
882
+ const bDef = /(?:^|\/)playwright\.config\.[cm]?[jt]s$/i.test(b) ? 0 : 1;
883
+ return aDef - bDef || a.localeCompare(b);
884
+ })
885
+ .map((file) => {
886
+ let text = '';
887
+ try { text = fs.readFileSync(path.join(work, file), 'utf8'); } catch { text = ''; }
888
+ const base = path.posix.basename(file);
889
+ const tagMatch = /^playwright\.(.+)\.config\.[cm]?[jt]s$/i.exec(base);
890
+ const tag = tagMatch ? tagMatch[1].toLowerCase() : null;
891
+ return {
892
+ file,
893
+ dir: path.posix.dirname(file) === '.' ? '' : path.posix.dirname(file),
894
+ tag,
895
+ isDefault: !tag,
896
+ testDirs: extractPlaywrightTestDirs(file, text),
897
+ };
898
+ });
899
+ }
900
+
901
+ function collectPlaywrightCommandHints(work, options = {}) {
902
+ const hints = [];
903
+ const texts = [...collectVerifyStringsFromOptions(options)];
904
+ try {
905
+ const pkg = JSON.parse(fs.readFileSync(path.join(work, 'package.json'), 'utf8'));
906
+ if (pkg && pkg.scripts && typeof pkg.scripts === 'object') {
907
+ for (const cmd of Object.values(pkg.scripts)) {
908
+ if (typeof cmd === 'string' && /playwright/.test(cmd)) texts.push(cmd);
909
+ }
910
+ }
911
+ } catch { /* ignore */ }
912
+ for (const cmd of texts) {
913
+ if (!/playwright\s+test/i.test(cmd)) continue;
914
+ const cfgM = /(?:^|\s)(?:-c|--config(?:=|\s+))["']?([^\s"']+)["']?/.exec(cmd);
915
+ if (!cfgM) continue;
916
+ const cfg = norm(cfgM[1]);
917
+ const afterPw = cmd.split(/playwright\s+test/i)[1] || '';
918
+ const tokens = (afterPw.replace(/(?:-c|--config(?:=|\s+))["']?[^\s"']+["']?/g, '').match(/[^\s"'`]+/g) || [])
919
+ .map(norm)
920
+ .filter((t) => t && !t.startsWith('-') && (t.includes('/') || /\.(?:spec|test)\.[cm]?[jt]sx?$/i.test(t)));
921
+ if (cfg && tokens.length) hints.push({ cfg, targets: tokens });
922
+ }
923
+ return hints;
924
+ }
925
+
926
+ function assignPlaywrightConfigForSuite(suiteRel, pwConfigs, commandHints = []) {
927
+ if (!pwConfigs || !pwConfigs.length) return null;
928
+ const s = norm(suiteRel);
929
+ // 1. Most specific (longest) `testDir` prefix declared in Playwright config files
930
+ let bestDirCfg = null;
931
+ let bestLen = -1;
932
+ for (const cfg of pwConfigs) {
933
+ for (const td of cfg.testDirs) {
934
+ if (!td) continue;
935
+ if (s === td || s.startsWith(`${td}/`)) {
936
+ if (td.length > bestLen || (td.length === bestLen && bestDirCfg && bestDirCfg.isDefault && !cfg.isDefault)) {
937
+ bestLen = td.length;
938
+ bestDirCfg = cfg.file;
939
+ }
940
+ }
941
+ }
942
+ }
943
+ if (bestDirCfg) return bestDirCfg;
944
+
945
+ // 2. Explicit `--config <file>` hint matching exact suite or directory prefix
946
+ for (const h of commandHints) {
947
+ if (!pwConfigs.some((c) => c.file === h.cfg)) continue;
948
+ if (h.targets.some((t) => s === t || s.startsWith(`${t.replace(/\/+$/, '')}/`))) return h.cfg;
949
+ }
950
+
951
+ // 3. Named config `playwright.<tag>.config.*` matching a path segment of the suite
952
+ const segs = s.toLowerCase().split('/');
953
+ const named = pwConfigs.find((cfg) => cfg.tag && segs.includes(cfg.tag));
954
+ if (named) return named.file;
955
+
956
+ // 4. Explicit `testDir: '.'` or default `playwright.config.*`
957
+ const rootMatch = pwConfigs.find((cfg) => cfg.testDirs.includes('') && cfg.isDefault)
958
+ || pwConfigs.find((cfg) => cfg.isDefault && (!cfg.dir || s.startsWith(`${cfg.dir}/`)))
959
+ || pwConfigs.find((cfg) => cfg.isDefault);
960
+ return rootMatch ? rootMatch.file : null;
961
+ }
962
+
963
+ /**
964
+ * Builds the shell command(s) for `promote --preview-ci` over discovered risk suites, grouping Playwright suites by
965
+ * their Playwright config (`--config <file>`) and preferring the project's `remote-verify` verify wrapper (from
966
+ * `config.promote.preview_ci_command` / `PLAN.json` verify lines / `phase_gates_runner` / `scripts/remote-verify.*`).
967
+ */
968
+ function buildPreviewCiCommands(work, riskSuites, config = {}, options = {}) {
969
+ if (!riskSuites || !riskSuites.length) return [];
970
+ const custom = config && config.promote && typeof config.promote.preview_ci_command === 'string'
971
+ ? config.promote.preview_ci_command.trim()
972
+ : '';
973
+ const files = riskSuites.map((r) => r.suite);
974
+ if (custom) {
975
+ return [custom.includes('{suites}') ? custom.replace('{suites}', files.join(' ')) : `${custom} ${files.join(' ')}`];
976
+ }
977
+
978
+ const prefix = resolvePreviewCiWrapper(work, config, options);
979
+
980
+ const isPlaywrightSuite = (r) => {
981
+ let txt = '';
982
+ try { txt = fs.readFileSync(path.join(work, r.suite), 'utf8'); } catch { txt = ''; }
983
+ const usesPlaywright = /@playwright\/test|\bfrom\s+['"][^'"]*playwright|playwright\.expect/i.test(txt);
984
+ const usesVitestOrNodeTest = /\bfrom\s+['"](?:vitest|node:test)['"]|require\(\s*['"](?:vitest|node:test)['"]\s*\)/i.test(txt);
985
+ if (usesVitestOrNodeTest && !usesPlaywright) return false;
986
+ if (usesPlaywright || r.kind === 'e2e' || r.kind === 'conformance' || /(^|\/)(e2e|playwright)\//i.test(r.suite)) return true;
987
+ return false;
988
+ };
989
+ const playwrightSuites = riskSuites.filter(isPlaywrightSuite).map((r) => r.suite);
990
+ const vitestSuites = files.filter((f) => !playwrightSuites.includes(f));
991
+ const cmds = [];
992
+ if (vitestSuites.length) cmds.push(`${prefix}npx vitest run ${vitestSuites.join(' ')}`);
993
+ if (playwrightSuites.length) {
994
+ const pwConfigs = discoverPlaywrightConfigs(work);
995
+ const commandHints = collectPlaywrightCommandHints(work, options);
996
+ const grouped = new Map();
997
+ for (const suite of playwrightSuites) {
998
+ const cfg = assignPlaywrightConfigForSuite(suite, pwConfigs, commandHints);
999
+ if (!grouped.has(cfg)) grouped.set(cfg, []);
1000
+ grouped.get(cfg).push(suite);
1001
+ }
1002
+ for (const [cfgFile, groupSuites] of grouped) {
1003
+ const cfgFlag = cfgFile ? `--config ${cfgFile} ` : '';
1004
+ cmds.push(`${prefix}npx playwright test ${cfgFlag}${groupSuites.join(' ')}`);
1005
+ }
1006
+ }
1007
+ return cmds;
1008
+ }
1009
+
1010
+ const PREVIEW_NOISE_LINE_RES = [
1011
+ /^(?:\(node:\d+\)\s*)?(?:Warning:\s*)?The\s+['"]?NO_COLOR['"]?\s+env\s+is\s+ignored\b/i,
1012
+ /^(?:\(node:\d+\)\s*)?(?:DeprecationWarning|ExperimentalWarning|MaxListenersExceededWarning):/i,
1013
+ /^\(Use\s+`node\s+--trace-(?:deprecation|warnings)\b[^)]*\)\s*$/i,
1014
+ /^\s*npm\s+(?:warn|notice)\b/i,
1015
+ ];
1016
+
1017
+ function stripAnsiAndTimestamps(text) {
1018
+ return String(text || '')
1019
+ .replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '')
1020
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '')
1021
+ .replace(/^[^\t\r\n]+\t[^\t\r\n]+\t\d{4}-\d{2}-\d{2}T[\d:.]+Z\s?/gm, '')
1022
+ .replace(/^\d{4}-\d{2}-\d{2}T[\d:.]+Z\s+/gm, '');
1023
+ }
1024
+
1025
+ /**
1026
+ * Extracts failing spec paths and real failure diagnostics from `--preview-ci` output, stripping Node/npm warning
1027
+ * noise (`NO_COLOR`/`FORCE_COLOR`, `DeprecationWarning`) so failures are never hidden behind a tail of warnings.
1028
+ */
1029
+ function extractPreviewCiFailure(rawOutput, maxLines = 12) {
1030
+ const cleaned = stripAnsiAndTimestamps(rawOutput);
1031
+ const rawLines = cleaned.split(/\r?\n/).map((l) => l.trimEnd());
1032
+ const nonNoise = rawLines.filter((l) => {
1033
+ const t = l.trim();
1034
+ if (!t) return false;
1035
+ return !PREVIEW_NOISE_LINE_RES.some((re) => re.test(t));
1036
+ });
1037
+
1038
+ const specs = new Set();
1039
+ const PW_SPEC_RE = /^\s*(?:\d+\)|✘|✗|×|FAIL|❌)?\s*(?:\d+\s+)?(?:\[[^\]]+\]\s*›\s*|│[^│]+│\s*)?([\w./\\@+$()[\]-]+\.(?:spec|test)\.[cm]?[jt]sx?)(?::\d+(?::\d+)?)?(?:\s*(?:›|>)\s*.+)?$/i;
1040
+ for (const l of nonNoise) {
1041
+ const t = l.trim();
1042
+ if (!/(^\s*\d+\)|^\s*(?:FAIL|✘|✗|×|❯|❌)\b)/.test(l) && !/\[[^\]]+\]\s*›\s*[\w./\\-]+/.test(t)) continue;
1043
+ const m = PW_SPEC_RE.exec(t);
1044
+ if (m && m[1]) specs.add(norm(m[1]));
1045
+ }
1046
+
1047
+ const FAILURE_SIGNAL_RES = [
1048
+ /^\s*\d+\)\s+/,
1049
+ /^\s*(?:FAIL|✘|✗|×|❯|❌|not ok\s+\d+)\b/,
1050
+ /^\s*(?:Error|TimeoutError|AssertionError|TypeError|ReferenceError)\b[:\s]/i,
1051
+ /^\s*(?:Expected|Received|Locator|Strict mode violation|waiting for locator)\b[:\s]/i,
1052
+ /\berror TS\d{4}\b/,
1053
+ /^npm ERR!/,
1054
+ /^\s*(?:\d+\s+failed|Tests?\s+\d+\s+failed|\d+\s+failing)\b/i,
1055
+ ];
1056
+ const picked = [];
1057
+ const seen = new Set();
1058
+ const pushUnique = (line) => {
1059
+ const trimmed = String(line || '').trim();
1060
+ if (!trimmed || seen.has(trimmed)) return;
1061
+ seen.add(trimmed);
1062
+ picked.push(trimmed);
1063
+ };
1064
+ for (let i = 0; i < nonNoise.length; i += 1) {
1065
+ const line = nonNoise[i];
1066
+ if (FAILURE_SIGNAL_RES.some((re) => re.test(line))) {
1067
+ pushUnique(line);
1068
+ // Include immediate detail line after a failure header if non-empty and not stack noise
1069
+ const next = nonNoise[i + 1];
1070
+ if (next && !/^\s*at\s/.test(next) && !FAILURE_SIGNAL_RES.some((re) => re.test(next))) {
1071
+ pushUnique(next);
1072
+ }
1073
+ }
1074
+ }
1075
+
1076
+ const lines = picked.length
1077
+ ? picked.slice(0, maxLines)
1078
+ : nonNoise.length
1079
+ ? nonNoise.slice(-maxLines)
1080
+ : ['(saída continha apenas avisos de ambiente; consulte o log completo)'];
1081
+ return {
1082
+ failing_specs: [...specs],
1083
+ lines,
1084
+ summary: lines.join('\n'),
1085
+ };
1086
+ }
1087
+
1088
+ /**
1089
+ * Valid conflict resolution strategies for `--resolve <path>=ours|theirs|union-json-array`.
1090
+ */
1091
+ const VALID_RESOLVE_STRATEGIES = new Set(['ours', 'theirs', 'union-json-array']);
1092
+
1093
+ /**
1094
+ * Parses `--resolve` arguments (`<path>=<strategy>` strings or `{ path, strategy }` objects).
1095
+ * Throws immediately if syntax or strategy is invalid.
1096
+ */
1097
+ function parseResolveRules(rawList) {
1098
+ const rules = [];
1099
+ const items = Array.isArray(rawList) ? rawList : rawList ? [rawList] : [];
1100
+ for (const raw of items) {
1101
+ if (!raw) continue;
1102
+ let filePath = '';
1103
+ let strategy = '';
1104
+ if (typeof raw === 'string') {
1105
+ const idx = raw.lastIndexOf('=');
1106
+ if (idx <= 0 || idx === raw.length - 1) {
1107
+ throw new Error(`--resolve inválido ("${raw}"): use --resolve <caminho>=ours|theirs|union-json-array`);
1108
+ }
1109
+ filePath = norm(raw.slice(0, idx).trim());
1110
+ strategy = raw.slice(idx + 1).trim().toLowerCase();
1111
+ } else if (typeof raw === 'object') {
1112
+ filePath = norm(String(raw.path || '').trim());
1113
+ strategy = String(raw.strategy || '').trim().toLowerCase();
1114
+ }
1115
+ if (!filePath || !VALID_RESOLVE_STRATEGIES.has(strategy)) {
1116
+ throw new Error(`--resolve inválido ("${typeof raw === 'string' ? raw : JSON.stringify(raw)}"): estratégia deve ser ours, theirs ou union-json-array`);
1117
+ }
1118
+ rules.push({ path: filePath, strategy });
1119
+ }
1120
+ return rules;
1121
+ }
1122
+
1123
+ function unionJsonArrayItems(oursArr, theirsArr) {
1124
+ const itemKey = (v) => {
1125
+ if (v === null || typeof v !== 'object') return `${typeof v}:${String(v)}`;
1126
+ if (!Array.isArray(v) && v.id != null) return `id:${String(v.id)}`;
1127
+ return `json:${JSON.stringify(v)}`;
1128
+ };
1129
+ const seen = new Set();
1130
+ const merged = [];
1131
+ for (const item of [...(Array.isArray(oursArr) ? oursArr : []), ...(Array.isArray(theirsArr) ? theirsArr : [])]) {
1132
+ const k = itemKey(item);
1133
+ if (seen.has(k)) continue;
1134
+ seen.add(k);
1135
+ merged.push(item);
1136
+ }
1137
+ return merged;
1138
+ }
1139
+
1140
+ function mergeJsonLockObjects(oursObj, theirsObj) {
1141
+ const isPlain = (x) => x && typeof x === 'object' && !Array.isArray(x);
1142
+ const out = { ...oursObj };
1143
+ for (const [k, tv] of Object.entries(theirsObj || {})) {
1144
+ const ov = out[k];
1145
+ if (Array.isArray(ov) && Array.isArray(tv)) {
1146
+ out[k] = unionJsonArrayItems(ov, tv);
1147
+ } else if (isPlain(ov) && isPlain(tv)) {
1148
+ const sub = { ...ov };
1149
+ for (const [sk, stv] of Object.entries(tv)) {
1150
+ const sov = sub[sk];
1151
+ if (isPlain(sov) && isPlain(stv)) {
1152
+ // Append-only lock entry upgrade (`pending` -> `enforced`) never regresses if either side enforced it
1153
+ const preferred = String(sov.status || sov.state || '').toLowerCase() === 'enforced' ? sov : stv;
1154
+ sub[sk] = { ...sov, ...stv, ...(preferred === sov ? { status: sov.status, ...(sov.state ? { state: sov.state } : {}) } : {}) };
1155
+ } else if (Array.isArray(sov) && Array.isArray(stv)) {
1156
+ sub[sk] = unionJsonArrayItems(sov, stv);
1157
+ } else if (!(sk in sub)) {
1158
+ sub[sk] = stv;
1159
+ }
1160
+ }
1161
+ out[k] = sub;
1162
+ } else if (!(k in out)) {
1163
+ out[k] = tv;
1164
+ }
1165
+ }
1166
+ return out;
1167
+ }
1168
+
1169
+ /**
1170
+ * Combines two JSON documents (`ours` vs `theirs`) via union of JSON arrays (plus map-entry union for
1171
+ * object-shaped lock files like `{ enforced: [...], targets: {...} }`), returning formatted JSON text or null.
1172
+ */
1173
+ function unionJsonDocuments(oursText, theirsText) {
1174
+ let ours;
1175
+ let theirs;
1176
+ try {
1177
+ ours = JSON.parse(String(oursText || ''));
1178
+ theirs = JSON.parse(String(theirsText || ''));
1179
+ } catch {
1180
+ return null;
1181
+ }
1182
+ if (Array.isArray(ours) && Array.isArray(theirs)) {
1183
+ return `${JSON.stringify(unionJsonArrayItems(ours, theirs), null, 2)}\n`;
1184
+ }
1185
+ if (ours && theirs && typeof ours === 'object' && typeof theirs === 'object' && !Array.isArray(ours) && !Array.isArray(theirs)) {
1186
+ return `${JSON.stringify(mergeJsonLockObjects(ours, theirs), null, 2)}\n`;
1187
+ }
1188
+ return null;
1189
+ }
1190
+
1191
+ const LOCK_META_KEYS = new Set(['schema', 'schema_version', 'version', 'updated_at', 'generated_at', 'enforced', 'targets', 'entries']);
1192
+ const lockItemKey = (v) => {
1193
+ if (v === null || typeof v !== 'object') return `${typeof v}:${String(v)}`;
1194
+ if (!Array.isArray(v) && v.id != null) return `id:${String(v.id)}`;
1195
+ return `json:${JSON.stringify(v)}`;
1196
+ };
1197
+ const isEntryEnforced = (v) => {
1198
+ if (!v || typeof v !== 'object') return false;
1199
+ return String(v.status || v.state || (v.enforced === true ? 'enforced' : '')).toLowerCase() === 'enforced';
1200
+ };
1201
+
1202
+ function mergeLockArrayThreeWay(oursArr, theirsArr, baseArr) {
1203
+ const baseByKey = new Map();
1204
+ for (const item of Array.isArray(baseArr) ? baseArr : []) baseByKey.set(lockItemKey(item), item);
1205
+ const delta = [];
1206
+ for (const item of Array.isArray(theirsArr) ? theirsArr : []) {
1207
+ const k = lockItemKey(item);
1208
+ if (!baseByKey.has(k)) {
1209
+ delta.push(item);
1210
+ } else if (isEntryEnforced(item) && !isEntryEnforced(baseByKey.get(k))) {
1211
+ delta.push(item);
1212
+ }
1213
+ }
1214
+ return unionJsonArrayItems(oursArr, delta);
1215
+ }
1216
+
1217
+ function mergeLockMapThreeWay(oursMap, theirsMap, baseMap) {
1218
+ const isPlain = (x) => x && typeof x === 'object' && !Array.isArray(x);
1219
+ const out = { ...(oursMap || {}) };
1220
+ const base = baseMap && typeof baseMap === 'object' ? baseMap : {};
1221
+ for (const [k, tv] of Object.entries(theirsMap || {})) {
1222
+ const ov = out[k];
1223
+ const inBase = Object.prototype.hasOwnProperty.call(base, k);
1224
+ const bv = base[k];
1225
+ if (!inBase) {
1226
+ // Newly added entry by this commit
1227
+ if (isPlain(ov) && isPlain(tv)) {
1228
+ const preferred = isEntryEnforced(ov) ? ov : tv;
1229
+ out[k] = { ...ov, ...tv, ...(preferred === ov ? { status: ov.status, ...(ov.state ? { state: ov.state } : {}) } : {}) };
1230
+ } else if (!(k in out)) {
1231
+ out[k] = tv;
1232
+ }
1233
+ continue;
1234
+ }
1235
+ // Entry already existed in parent: carry update only if `ours` kept it OR `theirs` newly promoted it to `enforced`
1236
+ const promotedHere = isPlain(tv) && isEntryEnforced(tv) && !(isPlain(bv) && isEntryEnforced(bv));
1237
+ if (Object.prototype.hasOwnProperty.call(out, k)) {
1238
+ if (isPlain(ov) && isPlain(tv) && promotedHere) {
1239
+ out[k] = { ...ov, ...tv };
1240
+ }
1241
+ } else if (promotedHere) {
1242
+ out[k] = tv;
1243
+ }
1244
+ }
1245
+ return out;
1246
+ }
1247
+
1248
+ /**
1249
+ * 3-way JSON lock merge (`base`, `ours`, `theirs`): applies ONLY entries added or promoted to `enforced` by
1250
+ * `theirs` relative to `base`, never reintroducing entries that `base` already had and `ours` removed (#914 / T56).
1251
+ */
1252
+ function mergeJsonLockThreeWay(oursText, theirsText, baseText) {
1253
+ let ours;
1254
+ let theirs;
1255
+ let base;
1256
+ try {
1257
+ ours = JSON.parse(String(oursText || ''));
1258
+ theirs = JSON.parse(String(theirsText || ''));
1259
+ base = JSON.parse(String(baseText || ''));
1260
+ } catch {
1261
+ return null;
1262
+ }
1263
+ const isPlain = (x) => x && typeof x === 'object' && !Array.isArray(x);
1264
+ if (Array.isArray(ours) && Array.isArray(theirs) && Array.isArray(base)) {
1265
+ return `${JSON.stringify(mergeLockArrayThreeWay(ours, theirs, base), null, 2)}\n`;
1266
+ }
1267
+ if (!isPlain(ours) || !isPlain(theirs) || !isPlain(base)) return null;
1268
+
1269
+ const out = { ...ours };
1270
+ for (const [k, tv] of Object.entries(theirs)) {
1271
+ const ov = out[k];
1272
+ const bv = base[k];
1273
+ if (k === 'enforced' && Array.isArray(ov) && Array.isArray(tv)) {
1274
+ out[k] = mergeLockArrayThreeWay(ov, tv, Array.isArray(bv) ? bv : []);
1275
+ } else if ((k === 'targets' || k === 'entries') && isPlain(ov) && isPlain(tv)) {
1276
+ out[k] = mergeLockMapThreeWay(ov, tv, isPlain(bv) ? bv : {});
1277
+ } else if (!LOCK_META_KEYS.has(k)) {
1278
+ const mergedFlat = mergeLockMapThreeWay(
1279
+ Object.prototype.hasOwnProperty.call(ours, k) ? { [k]: ov } : {},
1280
+ { [k]: tv },
1281
+ Object.prototype.hasOwnProperty.call(base, k) ? { [k]: bv } : {},
1282
+ );
1283
+ if (Object.prototype.hasOwnProperty.call(mergedFlat, k)) out[k] = mergedFlat[k];
1284
+ } else if (!Object.prototype.hasOwnProperty.call(out, k) && !Object.prototype.hasOwnProperty.call(base, k)) {
1285
+ out[k] = tv;
1286
+ }
1287
+ }
1288
+ return `${JSON.stringify(out, null, 2)}\n`;
1289
+ }
1290
+
1291
+ function reconcileSingleLockDoc(baseDoc, workDoc, taskAddedOrEnforced, taskRemoved) {
1292
+ const isPlain = (x) => x && typeof x === 'object' && !Array.isArray(x);
1293
+ const removedIds = [];
1294
+ if (Array.isArray(workDoc)) {
1295
+ const baseArr = Array.isArray(baseDoc) ? baseDoc : [];
1296
+ const baseKeys = new Set(baseArr.map((x) => (x && typeof x === 'object' && x.id != null ? String(x.id) : String(x))));
1297
+ const next = [];
1298
+ for (const item of workDoc) {
1299
+ const id = item && typeof item === 'object' && item.id != null ? String(item.id) : String(item);
1300
+ if (taskRemoved.has(id) && !taskAddedOrEnforced.has(id)) {
1301
+ removedIds.push(id);
1302
+ continue;
1303
+ }
1304
+ if (baseKeys.has(id) || taskAddedOrEnforced.has(id)) next.push(item);
1305
+ else removedIds.push(id);
1306
+ }
1307
+ return { nextDoc: next, removedIds };
1308
+ }
1309
+ if (!isPlain(workDoc)) return { nextDoc: workDoc, removedIds };
1310
+
1311
+ const base = isPlain(baseDoc) ? baseDoc : {};
1312
+ const next = { ...workDoc };
1313
+
1314
+ if (Array.isArray(workDoc.enforced)) {
1315
+ const baseArr = Array.isArray(base.enforced) ? base.enforced.map(String) : [];
1316
+ const baseEnforced = new Set(baseArr);
1317
+ const workArr = workDoc.enforced.map(String);
1318
+ const seen = new Set();
1319
+ const nextEnforced = [];
1320
+ for (const bid of baseArr) {
1321
+ if (taskRemoved.has(bid) && !taskAddedOrEnforced.has(bid)) continue;
1322
+ if (seen.has(bid)) continue;
1323
+ seen.add(bid);
1324
+ nextEnforced.push(bid);
1325
+ }
1326
+ for (const wid of workArr) {
1327
+ if (seen.has(wid)) continue;
1328
+ if (baseEnforced.has(wid) || taskAddedOrEnforced.has(wid)) {
1329
+ seen.add(wid);
1330
+ nextEnforced.push(wid);
1331
+ } else {
1332
+ removedIds.push(wid);
1333
+ }
1334
+ }
1335
+ next.enforced = nextEnforced;
1336
+ }
1337
+
1338
+ const reconcileMapContainer = (baseMap, workMap) => {
1339
+ const out = {};
1340
+ const b = isPlain(baseMap) ? baseMap : {};
1341
+ const w = isPlain(workMap) ? workMap : {};
1342
+ for (const [id, bVal] of Object.entries(b)) {
1343
+ if (taskRemoved.has(id) && !taskAddedOrEnforced.has(id)) continue;
1344
+ if (taskAddedOrEnforced.has(id) && Object.prototype.hasOwnProperty.call(w, id)) {
1345
+ out[id] = w[id];
1346
+ } else {
1347
+ out[id] = bVal;
1348
+ }
1349
+ }
1350
+ for (const [id, wVal] of Object.entries(w)) {
1351
+ if (Object.prototype.hasOwnProperty.call(out, id)) continue;
1352
+ if (taskAddedOrEnforced.has(id)) {
1353
+ out[id] = wVal;
1354
+ } else {
1355
+ removedIds.push(id);
1356
+ }
1357
+ }
1358
+ return out;
1359
+ };
1360
+
1361
+ if (isPlain(workDoc.targets)) {
1362
+ next.targets = reconcileMapContainer(base.targets, workDoc.targets);
1363
+ } else if (isPlain(workDoc.entries)) {
1364
+ next.entries = reconcileMapContainer(base.entries, workDoc.entries);
1365
+ } else if (!Array.isArray(workDoc.enforced) && !isPlain(workDoc.targets) && !isPlain(workDoc.entries)) {
1366
+ // Flat ID-keyed lock map (preserving schema/meta keys)
1367
+ const meta = {};
1368
+ const baseEntriesOnly = {};
1369
+ const workEntriesOnly = {};
1370
+ for (const [k, v] of Object.entries(base)) {
1371
+ if (!LOCK_META_KEYS.has(k)) baseEntriesOnly[k] = v;
1372
+ }
1373
+ for (const [k, v] of Object.entries(workDoc)) {
1374
+ if (LOCK_META_KEYS.has(k)) meta[k] = v;
1375
+ else workEntriesOnly[k] = v;
1376
+ }
1377
+ return { nextDoc: { ...meta, ...reconcileMapContainer(baseEntriesOnly, workEntriesOnly) }, removedIds: [...new Set(removedIds)] };
1378
+ }
1379
+
1380
+ return { nextDoc: next, removedIds: [...new Set(removedIds)] };
1381
+ }
1382
+
1383
+ /**
1384
+ * OXB-C8 (T56 / #914): Reconciles `*enforced*.json` lock files in `work` (`buildSha..HEAD`) so the promoted lock
1385
+ * holds strictly `base's entries + only the IDs this task itself adds or promotes to enforced`. Prevents silent
1386
+ * carry-over of older program entries that `base` removed after fork (even when cherry-pick succeeded cleanly).
1387
+ */
1388
+ function reconcilePromotedEnforcedLocks(projectRoot, work, buildSha, ordered, options = {}) {
1389
+ if (!Array.isArray(ordered)) return { adjusted: [], files: [] };
1390
+ const changed = gitLines(work, ['diff', '--name-only', buildSha, 'HEAD']).map(norm);
1391
+ const lockFiles = changed.filter((f) => /(?:^|\/)[^/]*enforced[^/]*\.json$/i.test(f));
1392
+ if (!lockFiles.length) return { adjusted: [], files: [] };
1393
+
1394
+ const explicitRules = parseResolveRules(options.resolve);
1395
+ const explicitOverride = (lf) => explicitRules.some((r) => (r.strategy === 'ours' || r.strategy === 'theirs')
1396
+ && (r.path === lf || (!r.path.includes('/') ? path.posix.basename(lf) === r.path : lf.endsWith(`/${r.path}`))));
1397
+
1398
+ const adjusted = [];
1399
+ const files = [];
1400
+
1401
+ for (const lf of lockFiles) {
1402
+ if (explicitOverride(lf)) continue;
1403
+ const abs = path.join(work, lf);
1404
+ if (!fs.existsSync(abs)) continue;
1405
+ let workText = '';
1406
+ let workDoc = null;
1407
+ try {
1408
+ workText = fs.readFileSync(abs, 'utf8');
1409
+ workDoc = JSON.parse(workText);
1410
+ } catch { continue; }
1411
+
1412
+ let baseDoc = null;
1413
+ const baseShow = gitOut(work, ['show', `${buildSha}:${lf}`]);
1414
+ if (baseShow.ok) {
1415
+ try { baseDoc = JSON.parse(baseShow.stdout); } catch { baseDoc = null; }
1416
+ }
1417
+
1418
+ const workEntries = extractEnforcedEntries(workDoc);
1419
+ const baseEntries = extractEnforcedEntries(baseDoc);
1420
+ if (!workEntries.size && !baseEntries.size) continue;
1421
+
1422
+ const taskAddedOrEnforced = new Set();
1423
+ const taskRemoved = new Set();
1424
+ for (const sha of ordered) {
1425
+ const parentShow = gitOut(projectRoot, ['show', `${sha}^:${lf}`]);
1426
+ const commitShow = gitOut(projectRoot, ['show', `${sha}:${lf}`]);
1427
+ if (!parentShow.ok && !commitShow.ok) continue;
1428
+ if (parentShow.ok && commitShow.ok && parentShow.stdout === commitShow.stdout) continue;
1429
+ let beforeDoc = null;
1430
+ let afterDoc = null;
1431
+ if (parentShow.ok) { try { beforeDoc = JSON.parse(parentShow.stdout); } catch { beforeDoc = null; } }
1432
+ if (commitShow.ok) { try { afterDoc = JSON.parse(commitShow.stdout); } catch { afterDoc = null; } }
1433
+ const beforeMap = extractEnforcedEntries(beforeDoc);
1434
+ const afterMap = extractEnforcedEntries(afterDoc);
1435
+ for (const [id, aInfo] of afterMap) {
1436
+ const bInfo = beforeMap.get(id);
1437
+ if (!bInfo || (aInfo.status === 'enforced' && bInfo.status !== 'enforced')) {
1438
+ taskAddedOrEnforced.add(id);
1439
+ taskRemoved.delete(id);
1440
+ }
1441
+ }
1442
+ for (const id of beforeMap.keys()) {
1443
+ if (!afterMap.has(id) && !taskAddedOrEnforced.has(id)) {
1444
+ taskRemoved.add(id);
1445
+ }
1446
+ }
1447
+ }
1448
+
1449
+ const { nextDoc, removedIds } = reconcileSingleLockDoc(baseDoc, workDoc, taskAddedOrEnforced, taskRemoved);
1450
+ const nextText = `${JSON.stringify(nextDoc, null, 2)}\n`;
1451
+ if (JSON.stringify(nextDoc) === JSON.stringify(workDoc)) continue;
1452
+ const finalText = baseShow.ok && JSON.stringify(nextDoc) === JSON.stringify(baseDoc) ? baseShow.stdout : nextText;
1453
+ fs.writeFileSync(abs, finalText, 'utf8');
1454
+ files.push(lf);
1455
+ adjusted.push({
1456
+ file: lf,
1457
+ removed_ids: removedIds,
1458
+ kept_task_ids: [...taskAddedOrEnforced],
1459
+ });
1460
+ }
1461
+
1462
+ return { adjusted, files };
1463
+ }
1464
+
1465
+ /**
1466
+ * Resolves a conflicted cherry-pick in `work` when all conflicted files can be settled safely:
1467
+ * 1. Ratchet cap-only conflicts (`tryResolveRatchetCherryPickConflict`);
1468
+ * 2. Explicit `--resolve <path>=ours|theirs|union-json-array` rules;
1469
+ * 3. Built-in 3-way JSON lock resolver for `enforced.lock.json` files (never restores entries removed in `ours`/`base`).
1470
+ */
1471
+ function tryResolvePromoteCherryPickConflict(projectRoot, work, sha, config, conflictedFiles, options = {}) {
1472
+ const files = (Array.isArray(conflictedFiles) ? conflictedFiles : []).map(norm).filter(Boolean);
1473
+ if (!files.length) return { resolved: false };
1474
+
1475
+ if (sha && options.skipRatchet !== true) {
1476
+ const ratchetRes = tryResolveRatchetCherryPickConflict(projectRoot, work, sha, config, files);
1477
+ if (ratchetRes.resolved) {
1478
+ return { ...ratchetRes, kind: 'ratchet', resolved_cap_files: ratchetRes.files || [] };
1479
+ }
1480
+ }
1481
+
1482
+ const rules = parseResolveRules(options.resolve);
1483
+ const strategyFor = (file) => {
1484
+ const exact = rules.find((r) => r.path === file);
1485
+ if (exact) return exact.strategy;
1486
+ const suffix = rules.find((r) => !r.path.includes('/') ? path.posix.basename(file) === r.path : file.endsWith(`/${r.path}`));
1487
+ if (suffix) return suffix.strategy;
1488
+ if (/(?:^|\/)enforced\.lock\.json$/i.test(file)) return 'union-json-array';
1489
+ return null;
1490
+ };
1491
+
1492
+ const plan = files.map((f) => ({ file: f, strategy: strategyFor(f) }));
1493
+ if (plan.some((p) => !p.strategy)) return { resolved: false };
1494
+
1495
+ const stagedContents = [];
1496
+ for (const item of plan) {
1497
+ if (item.strategy === 'union-json-array') {
1498
+ const oursStage = gitOut(work, ['show', `:2:${item.file}`]);
1499
+ const theirsStage = gitOut(work, ['show', `:3:${item.file}`]);
1500
+ if (!oursStage.ok || !theirsStage.ok) return { resolved: false };
1501
+ let merged = null;
1502
+ if (/(?:^|\/)[^/]*enforced[^/]*\.json$/i.test(item.file)) {
1503
+ const baseStage = gitOut(work, ['show', `:1:${item.file}`]);
1504
+ if (baseStage.ok) merged = mergeJsonLockThreeWay(oursStage.stdout, theirsStage.stdout, baseStage.stdout);
1505
+ }
1506
+ if (merged == null) merged = unionJsonDocuments(oursStage.stdout, theirsStage.stdout);
1507
+ if (merged == null) return { resolved: false };
1508
+ stagedContents.push({ ...item, merged });
1509
+ } else {
1510
+ stagedContents.push(item);
1511
+ }
1512
+ }
1513
+
1514
+ for (const item of stagedContents) {
1515
+ if (item.strategy === 'ours' || item.strategy === 'theirs') {
1516
+ const co = gitOut(work, ['checkout', `--${item.strategy}`, '--', item.file]);
1517
+ if (!co.ok) return { resolved: false };
1518
+ } else if (item.strategy === 'union-json-array') {
1519
+ fs.mkdirSync(path.dirname(path.join(work, item.file)), { recursive: true });
1520
+ fs.writeFileSync(path.join(work, item.file), item.merged, 'utf8');
1521
+ }
1522
+ const add = gitOut(work, ['add', '--', item.file]);
1523
+ if (!add.ok) return { resolved: false };
1524
+ }
1525
+
1526
+ const resolvedFiles = stagedContents.map((s) => ({ file: s.file, strategy: s.strategy }));
1527
+ if (options.commit === false) {
1528
+ return { resolved: true, kind: 'staged', files, resolved_files: resolvedFiles, resolved_cap_files: [] };
1529
+ }
1530
+
1531
+ const stagedDiff = gitOut(work, ['diff', '--cached', '--quiet']);
1532
+ if (stagedDiff.status === 0) {
1533
+ const skip = gitOut(work, ['cherry-pick', '--skip']);
1534
+ return { resolved: skip.ok, skipped: true, kind: 'resolved', files, resolved_files: resolvedFiles, resolved_cap_files: [] };
1535
+ }
1536
+ const cont = spawnSync('git', ['-c', 'core.editor=true', 'cherry-pick', '--continue'], {
1537
+ cwd: work,
1538
+ encoding: 'utf8',
1539
+ windowsHide: true,
1540
+ env: { ...process.env, GIT_EDITOR: 'true' },
1541
+ });
1542
+ return { resolved: cont.status === 0, skipped: false, kind: 'resolved', files, resolved_files: resolvedFiles, resolved_cap_files: [] };
1543
+ }
1544
+
1545
+ module.exports = {
1546
+ selectPromoteQuickCommits,
1547
+ tryResolveRatchetCherryPickConflict,
1548
+ tryResolvePromoteCherryPickConflict,
1549
+ parseResolveRules,
1550
+ unionJsonDocuments,
1551
+ mergeJsonLockThreeWay,
1552
+ reconcilePromotedRatchets,
1553
+ reconcilePromotedEnforcedLocks,
1554
+ checkPromotedEnforcedTargets,
1555
+ analyzeUnpromotedDependencies,
1556
+ discoverMainCiRiskSuites,
1557
+ discoverPlaywrightConfigs,
1558
+ buildPreviewCiCommands,
1559
+ extractPreviewCiFailure,
1560
+ resolveTaskCards,
1561
+ };