@rpamis/comet 0.4.3 → 0.4.5

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 (464) hide show
  1. package/README.md +372 -332
  2. package/assets/manifest.json +1 -1
  3. package/assets/skills/comet/scripts/comet-archive.mjs +113 -97
  4. package/assets/skills/comet/scripts/comet-check.mjs +117 -104
  5. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +59 -59
  6. package/assets/skills/comet/scripts/comet-guard.mjs +170 -157
  7. package/assets/skills/comet/scripts/comet-handoff.mjs +110 -97
  8. package/assets/skills/comet/scripts/comet-hook-guard.mjs +110 -97
  9. package/assets/skills/comet/scripts/comet-hook-router.mjs +272 -153
  10. package/assets/skills/comet/scripts/comet-intent.mjs +31 -31
  11. package/assets/skills/comet/scripts/comet-resume-probe.mjs +104 -91
  12. package/assets/skills/comet/scripts/comet-runtime.mjs +311 -296
  13. package/assets/skills/comet/scripts/comet-state.mjs +221 -207
  14. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +25 -25
  15. package/assets/skills/comet-archive/SKILL.md +13 -9
  16. package/assets/skills/comet-build/SKILL.md +4 -6
  17. package/assets/skills/comet-classic/SKILL.md +1 -1
  18. package/assets/skills/comet-classic/reference/scripts.md +9 -1
  19. package/assets/skills/comet-design/SKILL.md +0 -2
  20. package/assets/skills/comet-hotfix/SKILL.md +1 -3
  21. package/assets/skills/comet-native/SKILL.md +8 -7
  22. package/assets/skills/comet-native/reference/artifacts.md +51 -7
  23. package/assets/skills/comet-native/reference/clarification.md +5 -5
  24. package/assets/skills/comet-native/reference/commands.md +15 -13
  25. package/assets/skills/comet-native/reference/recovery.md +3 -3
  26. package/assets/skills/comet-native/reference/workspace.md +10 -4
  27. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +257 -169
  28. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +238 -153
  29. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +241 -124
  30. package/assets/skills/comet-native/scripts/comet-native-init.mjs +189 -108
  31. package/assets/skills/comet-native/scripts/comet-native-new.mjs +220 -139
  32. package/assets/skills/comet-native/scripts/comet-native-next.mjs +245 -160
  33. package/assets/skills/comet-native/scripts/comet-native-root.mjs +210 -129
  34. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +284 -196
  35. package/assets/skills/comet-native/scripts/comet-native-select.mjs +212 -128
  36. package/assets/skills/comet-native/scripts/comet-native-show.mjs +207 -126
  37. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +203 -118
  38. package/assets/skills/comet-native/scripts/comet-native-status.mjs +208 -124
  39. package/assets/skills/comet-open/SKILL.md +0 -2
  40. package/assets/skills/comet-tweak/SKILL.md +1 -1
  41. package/assets/skills/comet-verify/SKILL.md +0 -2
  42. package/assets/skills-zh/comet-archive/SKILL.md +13 -9
  43. package/assets/skills-zh/comet-build/SKILL.md +4 -6
  44. package/assets/skills-zh/comet-classic/SKILL.md +1 -1
  45. package/assets/skills-zh/comet-classic/reference/scripts.md +9 -1
  46. package/assets/skills-zh/comet-design/SKILL.md +0 -2
  47. package/assets/skills-zh/comet-hotfix/SKILL.md +1 -3
  48. package/assets/skills-zh/comet-native/SKILL.md +8 -7
  49. package/assets/skills-zh/comet-native/reference/artifacts.md +51 -7
  50. package/assets/skills-zh/comet-native/reference/clarification.md +5 -5
  51. package/assets/skills-zh/comet-native/reference/commands.md +16 -10
  52. package/assets/skills-zh/comet-native/reference/recovery.md +3 -3
  53. package/assets/skills-zh/comet-native/reference/workspace.md +10 -4
  54. package/assets/skills-zh/comet-open/SKILL.md +0 -2
  55. package/assets/skills-zh/comet-tweak/SKILL.md +1 -1
  56. package/assets/skills-zh/comet-verify/SKILL.md +0 -2
  57. package/bin/comet-daemon-router.js +23 -7
  58. package/bin/fast-runtime-router.js +1 -1
  59. package/dist/app/cli/index.js +1 -0
  60. package/dist/app/cli/index.js.map +1 -1
  61. package/dist/app/commands/daemon-server.d.ts.map +1 -1
  62. package/dist/app/commands/daemon-server.js +13 -2
  63. package/dist/app/commands/daemon-server.js.map +1 -1
  64. package/dist/app/commands/doctor.d.ts.map +1 -1
  65. package/dist/app/commands/doctor.js +17 -10
  66. package/dist/app/commands/doctor.js.map +1 -1
  67. package/dist/app/commands/i18n.d.ts +1 -1
  68. package/dist/app/commands/i18n.d.ts.map +1 -1
  69. package/dist/app/commands/i18n.js +4 -0
  70. package/dist/app/commands/i18n.js.map +1 -1
  71. package/dist/app/commands/project-knowledge.d.ts +2 -0
  72. package/dist/app/commands/project-knowledge.d.ts.map +1 -1
  73. package/dist/app/commands/project-knowledge.js +64 -7
  74. package/dist/app/commands/project-knowledge.js.map +1 -1
  75. package/dist/app/commands/uninstall.d.ts +1 -0
  76. package/dist/app/commands/uninstall.d.ts.map +1 -1
  77. package/dist/app/commands/uninstall.js +65 -10
  78. package/dist/app/commands/uninstall.js.map +1 -1
  79. package/dist/domains/agent-learning/coordinator.d.ts +8 -1
  80. package/dist/domains/agent-learning/coordinator.d.ts.map +1 -1
  81. package/dist/domains/agent-learning/coordinator.js +58 -0
  82. package/dist/domains/agent-learning/coordinator.js.map +1 -1
  83. package/dist/domains/agent-learning/experience-journal.d.ts +21 -1
  84. package/dist/domains/agent-learning/experience-journal.d.ts.map +1 -1
  85. package/dist/domains/agent-learning/experience-journal.js +190 -11
  86. package/dist/domains/agent-learning/experience-journal.js.map +1 -1
  87. package/dist/domains/bundle/bundle-platform.d.ts.map +1 -1
  88. package/dist/domains/bundle/bundle-platform.js +6 -1
  89. package/dist/domains/bundle/bundle-platform.js.map +1 -1
  90. package/dist/domains/comet-classic/classic-archive-entry.d.ts +1 -1
  91. package/dist/domains/comet-classic/classic-archive-entry.d.ts.map +1 -1
  92. package/dist/domains/comet-classic/classic-archive-entry.js +5 -2
  93. package/dist/domains/comet-classic/classic-archive-entry.js.map +1 -1
  94. package/dist/domains/comet-classic/classic-archive.d.ts.map +1 -1
  95. package/dist/domains/comet-classic/classic-archive.js +5 -1
  96. package/dist/domains/comet-classic/classic-archive.js.map +1 -1
  97. package/dist/domains/comet-classic/classic-branch-binding.d.ts.map +1 -1
  98. package/dist/domains/comet-classic/classic-branch-binding.js +5 -4
  99. package/dist/domains/comet-classic/classic-branch-binding.js.map +1 -1
  100. package/dist/domains/comet-classic/classic-check-entry.d.ts +1 -1
  101. package/dist/domains/comet-classic/classic-check-entry.d.ts.map +1 -1
  102. package/dist/domains/comet-classic/classic-check-entry.js +5 -2
  103. package/dist/domains/comet-classic/classic-check-entry.js.map +1 -1
  104. package/dist/domains/comet-classic/classic-check-snapshot.d.ts.map +1 -1
  105. package/dist/domains/comet-classic/classic-check-snapshot.js +68 -26
  106. package/dist/domains/comet-classic/classic-check-snapshot.js.map +1 -1
  107. package/dist/domains/comet-classic/classic-design-readiness.d.ts +1 -1
  108. package/dist/domains/comet-classic/classic-guard-entry.d.ts +1 -1
  109. package/dist/domains/comet-classic/classic-guard-entry.d.ts.map +1 -1
  110. package/dist/domains/comet-classic/classic-guard-entry.js +5 -2
  111. package/dist/domains/comet-classic/classic-guard-entry.js.map +1 -1
  112. package/dist/domains/comet-classic/classic-handoff-entry.d.ts +1 -1
  113. package/dist/domains/comet-classic/classic-handoff-entry.d.ts.map +1 -1
  114. package/dist/domains/comet-classic/classic-handoff-entry.js +5 -2
  115. package/dist/domains/comet-classic/classic-handoff-entry.js.map +1 -1
  116. package/dist/domains/comet-classic/classic-progress.d.ts +60 -2
  117. package/dist/domains/comet-classic/classic-progress.d.ts.map +1 -1
  118. package/dist/domains/comet-classic/classic-progress.js +199 -22
  119. package/dist/domains/comet-classic/classic-progress.js.map +1 -1
  120. package/dist/domains/comet-classic/classic-recovery.d.ts +20 -1
  121. package/dist/domains/comet-classic/classic-recovery.d.ts.map +1 -1
  122. package/dist/domains/comet-classic/classic-resume-probe.d.ts.map +1 -1
  123. package/dist/domains/comet-classic/classic-resume-probe.js +3 -2
  124. package/dist/domains/comet-classic/classic-resume-probe.js.map +1 -1
  125. package/dist/domains/comet-classic/classic-script-entry.d.ts +3 -1
  126. package/dist/domains/comet-classic/classic-script-entry.d.ts.map +1 -1
  127. package/dist/domains/comet-classic/classic-script-entry.js +34 -3
  128. package/dist/domains/comet-classic/classic-script-entry.js.map +1 -1
  129. package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
  130. package/dist/domains/comet-classic/classic-state-command.js +3 -2
  131. package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
  132. package/dist/domains/comet-classic/classic-state-entry.d.ts +1 -1
  133. package/dist/domains/comet-classic/classic-state-entry.d.ts.map +1 -1
  134. package/dist/domains/comet-classic/classic-state-entry.js +5 -2
  135. package/dist/domains/comet-classic/classic-state-entry.js.map +1 -1
  136. package/dist/domains/comet-classic/classic-store.d.ts.map +1 -1
  137. package/dist/domains/comet-classic/classic-store.js +67 -1
  138. package/dist/domains/comet-classic/classic-store.js.map +1 -1
  139. package/dist/domains/comet-entry/resume-probe.d.ts.map +1 -1
  140. package/dist/domains/comet-entry/resume-probe.js +3 -2
  141. package/dist/domains/comet-entry/resume-probe.js.map +1 -1
  142. package/dist/domains/comet-native/native-acceptance.d.ts +5 -1
  143. package/dist/domains/comet-native/native-acceptance.d.ts.map +1 -1
  144. package/dist/domains/comet-native/native-acceptance.js +13 -2
  145. package/dist/domains/comet-native/native-acceptance.js.map +1 -1
  146. package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
  147. package/dist/domains/comet-native/native-archive-command.js +167 -37
  148. package/dist/domains/comet-native/native-archive-command.js.map +1 -1
  149. package/dist/domains/comet-native/native-artifact-language.d.ts +10 -1
  150. package/dist/domains/comet-native/native-artifact-language.d.ts.map +1 -1
  151. package/dist/domains/comet-native/native-artifact-language.js +65 -12
  152. package/dist/domains/comet-native/native-artifact-language.js.map +1 -1
  153. package/dist/domains/comet-native/native-artifacts.d.ts +10 -1
  154. package/dist/domains/comet-native/native-artifacts.d.ts.map +1 -1
  155. package/dist/domains/comet-native/native-artifacts.js +130 -21
  156. package/dist/domains/comet-native/native-artifacts.js.map +1 -1
  157. package/dist/domains/comet-native/native-builder-acceptance-review.d.ts +16 -0
  158. package/dist/domains/comet-native/native-builder-acceptance-review.d.ts.map +1 -0
  159. package/dist/domains/comet-native/native-builder-acceptance-review.js +65 -0
  160. package/dist/domains/comet-native/native-builder-acceptance-review.js.map +1 -0
  161. package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
  162. package/dist/domains/comet-native/native-cli-help.js +8 -4
  163. package/dist/domains/comet-native/native-cli-help.js.map +1 -1
  164. package/dist/domains/comet-native/native-cli-shared.d.ts +4 -2
  165. package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
  166. package/dist/domains/comet-native/native-cli-shared.js +37 -9
  167. package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
  168. package/dist/domains/comet-native/native-cli.d.ts +4 -1
  169. package/dist/domains/comet-native/native-cli.d.ts.map +1 -1
  170. package/dist/domains/comet-native/native-cli.js +9 -5
  171. package/dist/domains/comet-native/native-cli.js.map +1 -1
  172. package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
  173. package/dist/domains/comet-native/native-doctor-command.js +144 -3
  174. package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
  175. package/dist/domains/comet-native/native-git-provenance.d.ts.map +1 -1
  176. package/dist/domains/comet-native/native-git-provenance.js +3 -2
  177. package/dist/domains/comet-native/native-git-provenance.js.map +1 -1
  178. package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
  179. package/dist/domains/comet-native/native-hook-guard.js +57 -26
  180. package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
  181. package/dist/domains/comet-native/native-local-execution.d.ts +1 -0
  182. package/dist/domains/comet-native/native-local-execution.d.ts.map +1 -1
  183. package/dist/domains/comet-native/native-local-execution.js +7 -0
  184. package/dist/domains/comet-native/native-local-execution.js.map +1 -1
  185. package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
  186. package/dist/domains/comet-native/native-lock.js +12 -0
  187. package/dist/domains/comet-native/native-lock.js.map +1 -1
  188. package/dist/domains/comet-native/native-loop-runtime.d.ts +2 -0
  189. package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
  190. package/dist/domains/comet-native/native-loop-runtime.js +6 -0
  191. package/dist/domains/comet-native/native-loop-runtime.js.map +1 -1
  192. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  193. package/dist/domains/comet-native/native-next-command.js +57 -28
  194. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  195. package/dist/domains/comet-native/native-output-language.d.ts.map +1 -1
  196. package/dist/domains/comet-native/native-output-language.js +7 -0
  197. package/dist/domains/comet-native/native-output-language.js.map +1 -1
  198. package/dist/domains/comet-native/native-portable-acceptance.d.ts +2 -0
  199. package/dist/domains/comet-native/native-portable-acceptance.d.ts.map +1 -1
  200. package/dist/domains/comet-native/native-portable-acceptance.js +11 -1
  201. package/dist/domains/comet-native/native-portable-acceptance.js.map +1 -1
  202. package/dist/domains/comet-native/native-portable-archive.d.ts +1 -0
  203. package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -1
  204. package/dist/domains/comet-native/native-portable-archive.js +3 -0
  205. package/dist/domains/comet-native/native-portable-archive.js.map +1 -1
  206. package/dist/domains/comet-native/native-portable-checks.d.ts +14 -4
  207. package/dist/domains/comet-native/native-portable-checks.d.ts.map +1 -1
  208. package/dist/domains/comet-native/native-portable-checks.js +159 -60
  209. package/dist/domains/comet-native/native-portable-checks.js.map +1 -1
  210. package/dist/domains/comet-native/native-portable-continuation.d.ts +2 -1
  211. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
  212. package/dist/domains/comet-native/native-portable-continuation.js +121 -39
  213. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
  214. package/dist/domains/comet-native/native-portable-requirements.d.ts +1 -0
  215. package/dist/domains/comet-native/native-portable-requirements.d.ts.map +1 -1
  216. package/dist/domains/comet-native/native-portable-requirements.js +68 -18
  217. package/dist/domains/comet-native/native-portable-requirements.js.map +1 -1
  218. package/dist/domains/comet-native/native-portable-shape-coordination.d.ts.map +1 -1
  219. package/dist/domains/comet-native/native-portable-shape-coordination.js +18 -5
  220. package/dist/domains/comet-native/native-portable-shape-coordination.js.map +1 -1
  221. package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
  222. package/dist/domains/comet-native/native-portable-state.js +12 -3
  223. package/dist/domains/comet-native/native-portable-state.js.map +1 -1
  224. package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -1
  225. package/dist/domains/comet-native/native-portable-status.js +10 -4
  226. package/dist/domains/comet-native/native-portable-status.js.map +1 -1
  227. package/dist/domains/comet-native/native-portable-types.d.ts +2 -1
  228. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
  229. package/dist/domains/comet-native/native-portable-types.js.map +1 -1
  230. package/dist/domains/comet-native/native-portable-verification.d.ts +3 -0
  231. package/dist/domains/comet-native/native-portable-verification.d.ts.map +1 -1
  232. package/dist/domains/comet-native/native-portable-verification.js +28 -35
  233. package/dist/domains/comet-native/native-portable-verification.js.map +1 -1
  234. package/dist/domains/comet-native/native-portable-verifier-coordination.d.ts +2 -0
  235. package/dist/domains/comet-native/native-portable-verifier-coordination.d.ts.map +1 -1
  236. package/dist/domains/comet-native/native-portable-verifier-coordination.js +9 -0
  237. package/dist/domains/comet-native/native-portable-verifier-coordination.js.map +1 -1
  238. package/dist/domains/comet-native/native-runner-input-artifacts.d.ts +9 -0
  239. package/dist/domains/comet-native/native-runner-input-artifacts.d.ts.map +1 -0
  240. package/dist/domains/comet-native/native-runner-input-artifacts.js +102 -0
  241. package/dist/domains/comet-native/native-runner-input-artifacts.js.map +1 -0
  242. package/dist/domains/comet-native/native-runner-input.d.ts +90 -64
  243. package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -1
  244. package/dist/domains/comet-native/native-runner-input.js +107 -22
  245. package/dist/domains/comet-native/native-runner-input.js.map +1 -1
  246. package/dist/domains/comet-native/native-script-entry.d.ts.map +1 -1
  247. package/dist/domains/comet-native/native-script-entry.js +9 -3
  248. package/dist/domains/comet-native/native-script-entry.js.map +1 -1
  249. package/dist/domains/comet-native/native-snapshot.d.ts.map +1 -1
  250. package/dist/domains/comet-native/native-snapshot.js +7 -2
  251. package/dist/domains/comet-native/native-snapshot.js.map +1 -1
  252. package/dist/domains/comet-native/native-verification-receipt-runtime.d.ts.map +1 -1
  253. package/dist/domains/comet-native/native-verification-receipt-runtime.js +5 -4
  254. package/dist/domains/comet-native/native-verification-receipt-runtime.js.map +1 -1
  255. package/dist/domains/comet-native/native-workspace-finish.d.ts +26 -0
  256. package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -1
  257. package/dist/domains/comet-native/native-workspace-finish.js +520 -15
  258. package/dist/domains/comet-native/native-workspace-finish.js.map +1 -1
  259. package/dist/domains/comet-plugin/integration.d.ts +1 -0
  260. package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
  261. package/dist/domains/comet-plugin/integration.js +20 -10
  262. package/dist/domains/comet-plugin/integration.js.map +1 -1
  263. package/dist/domains/comet-plugin/plugin-runtime.d.ts +8 -2
  264. package/dist/domains/comet-plugin/plugin-runtime.d.ts.map +1 -1
  265. package/dist/domains/comet-plugin/plugin-runtime.js +18 -4
  266. package/dist/domains/comet-plugin/plugin-runtime.js.map +1 -1
  267. package/dist/domains/dashboard/project-directory.d.ts +4 -0
  268. package/dist/domains/dashboard/project-directory.d.ts.map +1 -1
  269. package/dist/domains/dashboard/project-directory.js +30 -2
  270. package/dist/domains/dashboard/project-directory.js.map +1 -1
  271. package/dist/domains/dashboard/server.d.ts.map +1 -1
  272. package/dist/domains/dashboard/server.js +28 -3
  273. package/dist/domains/dashboard/server.js.map +1 -1
  274. package/dist/domains/dashboard/web/assets/{abnfDiagram-VCTEODGH-qlcciI25.js → abnfDiagram-VCTEODGH-m9_t3fwH.js} +1 -1
  275. package/dist/domains/dashboard/web/assets/{arc-KVm4k9kp.js → arc-CDiwRrMg.js} +1 -1
  276. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-ypJOsR2Y.js +1 -0
  277. package/dist/domains/dashboard/web/assets/{architectureDiagram-5GKGNRK7-C366RdBK.js → architectureDiagram-5GKGNRK7-Xwj-hlQB.js} +1 -1
  278. package/dist/domains/dashboard/web/assets/{blockDiagram-I7D4REHJ-DAuTc2OO.js → blockDiagram-I7D4REHJ-Cme6qNK_.js} +1 -1
  279. package/dist/domains/dashboard/web/assets/{c4Diagram-7LVT6UL2-CFB0RZmL.js → c4Diagram-7LVT6UL2-Cxs1dU7y.js} +1 -1
  280. package/dist/domains/dashboard/web/assets/channel-BFTjR7Ng.js +1 -0
  281. package/dist/domains/dashboard/web/assets/{chunk-4HAMMTFA-DTV6lyGQ.js → chunk-4HAMMTFA-DBQykIWE.js} +1 -1
  282. package/dist/domains/dashboard/web/assets/{chunk-75Z2AOVW-DgJm4cEX.js → chunk-75Z2AOVW-Dh-E6TAx.js} +1 -1
  283. package/dist/domains/dashboard/web/assets/{chunk-DU6HZSFF-NAtcgGZr.js → chunk-DU6HZSFF-W3lPaoVP.js} +2 -2
  284. package/dist/domains/dashboard/web/assets/{chunk-F27PBJKO-BcFXHZMJ.js → chunk-F27PBJKO-dzf1fpYi.js} +1 -1
  285. package/dist/domains/dashboard/web/assets/{chunk-GMAD6QVW-wNemar9b.js → chunk-GMAD6QVW-CeuSGVHV.js} +1 -1
  286. package/dist/domains/dashboard/web/assets/{chunk-GVQU2GXP-BiVCDO9d.js → chunk-GVQU2GXP-BrGrIBgk.js} +1 -1
  287. package/dist/domains/dashboard/web/assets/{chunk-IMKFNOWR-D9GDj4b6.js → chunk-IMKFNOWR-DXiTC1Xo.js} +1 -1
  288. package/dist/domains/dashboard/web/assets/{chunk-L3NEJ4N5-DkPl5vac.js → chunk-L3NEJ4N5-DnyD3Ocj.js} +1 -1
  289. package/dist/domains/dashboard/web/assets/{chunk-OSK3NFVY-RbbxGqtJ.js → chunk-OSK3NFVY-6vxhPm51.js} +1 -1
  290. package/dist/domains/dashboard/web/assets/{chunk-P2QGCYS3-B9_X57eT.js → chunk-P2QGCYS3-DChNsVqO.js} +1 -1
  291. package/dist/domains/dashboard/web/assets/{chunk-POPQ4Y6H-DE4bOH0D.js → chunk-POPQ4Y6H-RBgha6dE.js} +1 -1
  292. package/dist/domains/dashboard/web/assets/{chunk-PWAF6VOD-Bo-W1iA1.js → chunk-PWAF6VOD-CayoKmnh.js} +1 -1
  293. package/dist/domains/dashboard/web/assets/{chunk-SHT3W25Y-BhLxs4rZ.js → chunk-SHT3W25Y-sOkLJZoB.js} +1 -1
  294. package/dist/domains/dashboard/web/assets/{chunk-SVP7TREG-BCXfn8uF.js → chunk-SVP7TREG-j0QRwmsq.js} +1 -1
  295. package/dist/domains/dashboard/web/assets/{chunk-TICWLB2K-DqSBgE5L.js → chunk-TICWLB2K-D7Re_d_T.js} +1 -1
  296. package/dist/domains/dashboard/web/assets/{chunk-XXDRQBXY-Dbkt1xEZ.js → chunk-XXDRQBXY-BFV70fKF.js} +1 -1
  297. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-gDSLbV2K.js +1 -0
  298. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-gDSLbV2K.js +1 -0
  299. package/dist/domains/dashboard/web/assets/{cose-bilkent-JH36ORCC-DrwNpMyX.js → cose-bilkent-JH36ORCC-k7gqx2Br.js} +1 -1
  300. package/dist/domains/dashboard/web/assets/{cynefin-OW5HDTMX-BbDlivxs.js → cynefin-OW5HDTMX-CWI6FZT8.js} +1 -1
  301. package/dist/domains/dashboard/web/assets/{cynefinDiagram-5FMLGOSQ-DmLmRN42.js → cynefinDiagram-5FMLGOSQ-D-O3RrOu.js} +1 -1
  302. package/dist/domains/dashboard/web/assets/{dagre-GXQ25YYZ-Cgm5DNgI.js → dagre-GXQ25YYZ-BR1jxWfn.js} +1 -1
  303. package/dist/domains/dashboard/web/assets/{diagram-S7CK7UJ4-Bnht1X2m.js → diagram-S7CK7UJ4-B6gXFYBj.js} +1 -1
  304. package/dist/domains/dashboard/web/assets/{diagram-UQ7AKVKN-LELTI4PR.js → diagram-UQ7AKVKN-BBW6aRk8.js} +1 -1
  305. package/dist/domains/dashboard/web/assets/{diagram-VSXAHHWV-Do0fZuNG.js → diagram-VSXAHHWV-BC0CZeyH.js} +1 -1
  306. package/dist/domains/dashboard/web/assets/{diagram-VX7I27RA-B0rZTUwt.js → diagram-VX7I27RA-BmwBIkwS.js} +1 -1
  307. package/dist/domains/dashboard/web/assets/{diagram-Z3DM3KII-wn8xCc_j.js → diagram-Z3DM3KII-DTZgX9SF.js} +1 -1
  308. package/dist/domains/dashboard/web/assets/{dist-CYwDKy2m.js → dist-brXLwleg.js} +1 -1
  309. package/dist/domains/dashboard/web/assets/{ebnfDiagram-PWID7BFC-CMDOpP2T.js → ebnfDiagram-PWID7BFC-CsMXo0C6.js} +1 -1
  310. package/dist/domains/dashboard/web/assets/{erDiagram-RLTQ6QDP-C2d43bdq.js → erDiagram-RLTQ6QDP-DQ9ewX94.js} +1 -1
  311. package/dist/domains/dashboard/web/assets/{es-BzaOcXwu.js → es-CgcAhzLf.js} +1 -1
  312. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-Ll12Q19y.js +1 -0
  313. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-Bf2-9XUn.js +1 -0
  314. package/dist/domains/dashboard/web/assets/{ganttDiagram-EL5Y4UJY-hTH7TzhY.js → ganttDiagram-EL5Y4UJY-DIFkXe6G.js} +1 -1
  315. package/dist/domains/dashboard/web/assets/{gitGraph-4MIJSDKK-C3CCywb-.js → gitGraph-4MIJSDKK-BHY8ZnpE.js} +1 -1
  316. package/dist/domains/dashboard/web/assets/{gitGraphDiagram-WWUBYQGX-DW6jDckj.js → gitGraphDiagram-WWUBYQGX-cBn9dMzs.js} +1 -1
  317. package/dist/domains/dashboard/web/assets/{index-CTZPz_mx.js → index-C_6nf1Fw.js} +3 -3
  318. package/dist/domains/dashboard/web/assets/{index-CWNqBYyI.css → index-Gaxnq6Jd.css} +1 -1
  319. package/dist/domains/dashboard/web/assets/{info-A6RAGUB7-Bg3eKis8.js → info-A6RAGUB7-DtUaS9jN.js} +1 -1
  320. package/dist/domains/dashboard/web/assets/{infoDiagram-27XIBGKW-7zk6ytVJ.js → infoDiagram-27XIBGKW-CIl0e_EN.js} +1 -1
  321. package/dist/domains/dashboard/web/assets/{ishikawaDiagram-5VMMS53U-CGDCTmCQ.js → ishikawaDiagram-5VMMS53U-DAdtPZ_c.js} +1 -1
  322. package/dist/domains/dashboard/web/assets/{journeyDiagram-3NMN7TZE-C8_L_e8a.js → journeyDiagram-3NMN7TZE-CBokRgde.js} +1 -1
  323. package/dist/domains/dashboard/web/assets/{kanban-definition-UXKFOSKX-D5x6qTgM.js → kanban-definition-UXKFOSKX-DrqCYJ-7.js} +1 -1
  324. package/dist/domains/dashboard/web/assets/katex-D29apahB.js +257 -0
  325. package/dist/domains/dashboard/web/assets/{line-DC93oja4.js → line-BDlVqlh4.js} +1 -1
  326. package/dist/domains/dashboard/web/assets/{linear-81TNubkB.js → linear-DTAzui9x.js} +1 -1
  327. package/dist/domains/dashboard/web/assets/{mermaid-parser.core-D60d8uy9.js → mermaid-parser.core-CFw-xbYY.js} +3 -3
  328. package/dist/domains/dashboard/web/assets/{mermaid.core-l4Wgjz2Q.js → mermaid.core-Ck7fB8UD.js} +4 -4
  329. package/dist/domains/dashboard/web/assets/{mindmap-definition-YA3MSWOX-Dfqu1201.js → mindmap-definition-YA3MSWOX-C7kb9KL9.js} +1 -1
  330. package/dist/domains/dashboard/web/assets/{packet-AYTQ26CC-CsFZBhTs.js → packet-AYTQ26CC-P8Mtt0tp.js} +1 -1
  331. package/dist/domains/dashboard/web/assets/{pegDiagram-XKGWAZYB-myFMaA7n.js → pegDiagram-XKGWAZYB-DUDD9qv5.js} +1 -1
  332. package/dist/domains/dashboard/web/assets/{pie-WAS4IAKB-FMuCTNSk.js → pie-WAS4IAKB-dEmLxiDR.js} +1 -1
  333. package/dist/domains/dashboard/web/assets/{pieDiagram-E7YTZNPT-CSR4B4Z1.js → pieDiagram-E7YTZNPT-BUssAcqk.js} +1 -1
  334. package/dist/domains/dashboard/web/assets/purify.es-Bvo9QlJ8.js +3 -0
  335. package/dist/domains/dashboard/web/assets/{quadrantDiagram-AXDQQJYC-BiE4kEeP.js → quadrantDiagram-AXDQQJYC-BzaAWdQL.js} +1 -1
  336. package/dist/domains/dashboard/web/assets/{radar-RG4KPBEZ-BZ-n7JtG.js → radar-RG4KPBEZ-mqtvaz9w.js} +1 -1
  337. package/dist/domains/dashboard/web/assets/{railroad-74A4TZTK-CWVtRfHu.js → railroad-74A4TZTK-7tTnGpoz.js} +1 -1
  338. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CpJvyBJM.js +1 -0
  339. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-BJ5g77l6.js +1 -0
  340. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-BslCK-Gr.js +1 -0
  341. package/dist/domains/dashboard/web/assets/{railroadDiagram-O6MQD6OU-CBj7v1de.js → railroadDiagram-O6MQD6OU-DM1AKXm0.js} +1 -1
  342. package/dist/domains/dashboard/web/assets/{requirementDiagram-BXWQKSXE-DSDgb54n.js → requirementDiagram-BXWQKSXE--H5KiPSc.js} +1 -1
  343. package/dist/domains/dashboard/web/assets/{sankeyDiagram-P5KCCOFB-1-oXLUAP.js → sankeyDiagram-P5KCCOFB-JweUq_u2.js} +1 -1
  344. package/dist/domains/dashboard/web/assets/{sequenceDiagram-WJ2MYXX4-DAF4nGs_.js → sequenceDiagram-WJ2MYXX4-pxb1iTGb.js} +1 -1
  345. package/dist/domains/dashboard/web/assets/{src-CTWLVUqE.js → src-joFOxopw.js} +1 -1
  346. package/dist/domains/dashboard/web/assets/{stateDiagram-D77RDMKH-DzENBaJT.js → stateDiagram-D77RDMKH-CDu5crd8.js} +1 -1
  347. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-wV5AqWaM.js +1 -0
  348. package/dist/domains/dashboard/web/assets/{swimlanes-42K2YHIH-CnxFUZJc.js → swimlanes-42K2YHIH-ioSqowJ4.js} +1 -1
  349. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-DOPLn-V5.js +8 -0
  350. package/dist/domains/dashboard/web/assets/{timeline-definition-24CTP7MA-KtvPzpZM.js → timeline-definition-24CTP7MA-2YXSYkS3.js} +1 -1
  351. package/dist/domains/dashboard/web/assets/{treeView-Q6P3EWNA-Bdu3P9iY.js → treeView-Q6P3EWNA-DEGims38.js} +1 -1
  352. package/dist/domains/dashboard/web/assets/{treemap-WGGIJYW6-DFnn23JR.js → treemap-WGGIJYW6-CJvBhTlR.js} +1 -1
  353. package/dist/domains/dashboard/web/assets/{vennDiagram-4TSXK5OY-BjpviP26.js → vennDiagram-4TSXK5OY-CHdNWhBK.js} +1 -1
  354. package/dist/domains/dashboard/web/assets/{wardley-WFR3VGLG-CEo4a-j4.js → wardley-WFR3VGLG-CVO9PCjo.js} +1 -1
  355. package/dist/domains/dashboard/web/assets/{wardleyDiagram-VM6X3IG4-Bf54n6im.js → wardleyDiagram-VM6X3IG4-RToPmij6.js} +1 -1
  356. package/dist/domains/dashboard/web/assets/{xychartDiagram-S5SC5T6Z-CU-hI0Cm.js → xychartDiagram-S5SC5T6Z-DaWHnpHE.js} +1 -1
  357. package/dist/domains/dashboard/web/index.html +2 -2
  358. package/dist/domains/project-knowledge/host-review.d.ts +15 -2
  359. package/dist/domains/project-knowledge/host-review.d.ts.map +1 -1
  360. package/dist/domains/project-knowledge/host-review.js +65 -25
  361. package/dist/domains/project-knowledge/host-review.js.map +1 -1
  362. package/dist/domains/project-knowledge/index.d.ts +1 -0
  363. package/dist/domains/project-knowledge/index.d.ts.map +1 -1
  364. package/dist/domains/project-knowledge/index.js +1 -0
  365. package/dist/domains/project-knowledge/index.js.map +1 -1
  366. package/dist/domains/project-knowledge/learning.d.ts +2 -1
  367. package/dist/domains/project-knowledge/learning.d.ts.map +1 -1
  368. package/dist/domains/project-knowledge/learning.js +6 -0
  369. package/dist/domains/project-knowledge/learning.js.map +1 -1
  370. package/dist/domains/project-knowledge/plugin.d.ts.map +1 -1
  371. package/dist/domains/project-knowledge/plugin.js +3 -1
  372. package/dist/domains/project-knowledge/plugin.js.map +1 -1
  373. package/dist/domains/skill/dsh-adapter.d.ts +5 -1
  374. package/dist/domains/skill/dsh-adapter.d.ts.map +1 -1
  375. package/dist/domains/skill/dsh-adapter.js +222 -87
  376. package/dist/domains/skill/dsh-adapter.js.map +1 -1
  377. package/dist/domains/skill/platform-inspect.d.ts +1 -0
  378. package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
  379. package/dist/domains/skill/platform-inspect.js +8 -4
  380. package/dist/domains/skill/platform-inspect.js.map +1 -1
  381. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  382. package/dist/domains/skill/platform-install.js +7 -7
  383. package/dist/domains/skill/platform-install.js.map +1 -1
  384. package/dist/domains/workflow-contract/hook-target-scope.d.ts.map +1 -1
  385. package/dist/domains/workflow-contract/hook-target-scope.js +2 -1
  386. package/dist/domains/workflow-contract/hook-target-scope.js.map +1 -1
  387. package/dist/platform/fs/file-system.d.ts +2 -0
  388. package/dist/platform/fs/file-system.d.ts.map +1 -1
  389. package/dist/platform/fs/file-system.js +11 -0
  390. package/dist/platform/fs/file-system.js.map +1 -1
  391. package/dist/platform/install/dsh-profiles.d.ts +3 -0
  392. package/dist/platform/install/dsh-profiles.d.ts.map +1 -0
  393. package/dist/platform/install/dsh-profiles.js +40 -0
  394. package/dist/platform/install/dsh-profiles.js.map +1 -0
  395. package/dist/platform/install/platforms.d.ts.map +1 -1
  396. package/dist/platform/install/platforms.js +1 -0
  397. package/dist/platform/install/platforms.js.map +1 -1
  398. package/dist/platform/install/project-registry.d.ts +7 -1
  399. package/dist/platform/install/project-registry.d.ts.map +1 -1
  400. package/dist/platform/install/project-registry.js +49 -5
  401. package/dist/platform/install/project-registry.js.map +1 -1
  402. package/dist/platform/paths/git-worktree-cache.d.ts +3 -0
  403. package/dist/platform/paths/git-worktree-cache.d.ts.map +1 -0
  404. package/dist/platform/paths/git-worktree-cache.js +109 -0
  405. package/dist/platform/paths/git-worktree-cache.js.map +1 -0
  406. package/dist/platform/paths/git-worktree.d.ts +6 -0
  407. package/dist/platform/paths/git-worktree.d.ts.map +1 -1
  408. package/dist/platform/paths/git-worktree.js +191 -30
  409. package/dist/platform/paths/git-worktree.js.map +1 -1
  410. package/dist/platform/paths/project-worktree-root.d.ts +3 -0
  411. package/dist/platform/paths/project-worktree-root.d.ts.map +1 -0
  412. package/dist/platform/paths/project-worktree-root.js +14 -0
  413. package/dist/platform/paths/project-worktree-root.js.map +1 -0
  414. package/dist/platform/process/comet-daemon.d.ts +3 -0
  415. package/dist/platform/process/comet-daemon.d.ts.map +1 -1
  416. package/dist/platform/process/comet-daemon.js +8 -6
  417. package/dist/platform/process/comet-daemon.js.map +1 -1
  418. package/dist/platform/process/external-command.d.ts +3 -0
  419. package/dist/platform/process/external-command.d.ts.map +1 -1
  420. package/dist/platform/process/external-command.js +69 -2
  421. package/dist/platform/process/external-command.js.map +1 -1
  422. package/dist/platform/process/git.d.ts.map +1 -1
  423. package/dist/platform/process/git.js +3 -4
  424. package/dist/platform/process/git.js.map +1 -1
  425. package/dist/platform/process/hook-adapter.d.ts +2 -0
  426. package/dist/platform/process/hook-adapter.d.ts.map +1 -1
  427. package/dist/platform/process/hook-adapter.js +45 -3
  428. package/dist/platform/process/hook-adapter.js.map +1 -1
  429. package/dist/platform/process/hook-read-cache.d.ts +2 -0
  430. package/dist/platform/process/hook-read-cache.d.ts.map +1 -1
  431. package/dist/platform/process/hook-read-cache.js +25 -13
  432. package/dist/platform/process/hook-read-cache.js.map +1 -1
  433. package/dist/platform/process/process-identity.d.ts.map +1 -1
  434. package/dist/platform/process/process-identity.js +18 -51
  435. package/dist/platform/process/process-identity.js.map +1 -1
  436. package/dist/platform/process/runtime-metrics.d.ts +10 -1
  437. package/dist/platform/process/runtime-metrics.d.ts.map +1 -1
  438. package/dist/platform/process/runtime-metrics.js +37 -2
  439. package/dist/platform/process/runtime-metrics.js.map +1 -1
  440. package/dist/platform/process/windows-process-broker.d.ts +1 -0
  441. package/dist/platform/process/windows-process-broker.d.ts.map +1 -1
  442. package/dist/platform/process/windows-process-broker.js +70 -11
  443. package/dist/platform/process/windows-process-broker.js.map +1 -1
  444. package/dist/platform/process/windows-process-identity.d.ts +6 -0
  445. package/dist/platform/process/windows-process-identity.d.ts.map +1 -0
  446. package/dist/platform/process/windows-process-identity.js +190 -0
  447. package/dist/platform/process/windows-process-identity.js.map +1 -0
  448. package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +11 -3
  449. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +11 -3
  450. package/eval/local/tests/scaffold/test_task_resolution.py +6 -2
  451. package/package.json +14 -8
  452. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-QeljAKq2.js +0 -1
  453. package/dist/domains/dashboard/web/assets/channel-_AqwP0KA.js +0 -1
  454. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-CRo4aB_7.js +0 -1
  455. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-CRo4aB_7.js +0 -1
  456. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-KYANo3DQ.js +0 -1
  457. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-CSROlLuj.js +0 -1
  458. package/dist/domains/dashboard/web/assets/katex-CXMH3UgJ.js +0 -257
  459. package/dist/domains/dashboard/web/assets/purify.es-ChwZkWde.js +0 -3
  460. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CkHwwI2i.js +0 -1
  461. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-8xzEHL6v.js +0 -1
  462. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-nSHBw0tH.js +0 -1
  463. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-CNw52Fkn.js +0 -1
  464. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-6TRvbqqI.js +0 -8
@@ -1,149 +1,149 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var Lk=Object.create;var uu=Object.defineProperty;var qk=Object.getOwnPropertyDescriptor;var Fk=Object.getOwnPropertyNames;var Vk=Object.getPrototypeOf,Mk=Object.prototype.hasOwnProperty;var Qo=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var A=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var R=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},du=(e,t)=>{for(var r in t)uu(e,r,{get:t[r],enumerable:!0})},Wk=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Fk(t))!Mk.call(e,n)&&n!==r&&uu(e,n,{get:()=>t[n],enumerable:!(i=qk(t,n))||i.enumerable});return e};var br=(e,t,r)=>(r=e!=null?Lk(Vk(e)):{},Wk(t||!e||!e.__esModule?uu(r,"default",{value:e,enumerable:!0}):r,e));var G=R(Ee=>{"use strict";var fu=Symbol.for("yaml.alias"),Mh=Symbol.for("yaml.document"),Zo=Symbol.for("yaml.map"),Wh=Symbol.for("yaml.pair"),pu=Symbol.for("yaml.scalar"),es=Symbol.for("yaml.seq"),er=Symbol.for("yaml.node.type"),zk=e=>!!e&&typeof e=="object"&&e[er]===fu,Jk=e=>!!e&&typeof e=="object"&&e[er]===Mh,Gk=e=>!!e&&typeof e=="object"&&e[er]===Zo,Uk=e=>!!e&&typeof e=="object"&&e[er]===Wh,zh=e=>!!e&&typeof e=="object"&&e[er]===pu,Kk=e=>!!e&&typeof e=="object"&&e[er]===es;function Jh(e){if(e&&typeof e=="object")switch(e[er]){case Zo:case es:return!0}return!1}function Yk(e){if(e&&typeof e=="object")switch(e[er]){case fu:case Zo:case pu:case es:return!0}return!1}var Xk=e=>(zh(e)||Jh(e))&&!!e.anchor;Ee.ALIAS=fu;Ee.DOC=Mh;Ee.MAP=Zo;Ee.NODE_TYPE=er;Ee.PAIR=Wh;Ee.SCALAR=pu;Ee.SEQ=es;Ee.hasAnchor=Xk;Ee.isAlias=zk;Ee.isCollection=Jh;Ee.isDocument=Jk;Ee.isMap=Gk;Ee.isNode=Yk;Ee.isPair=Uk;Ee.isScalar=zh;Ee.isSeq=Kk});var Jn=R(hu=>{"use strict";var ge=G(),De=Symbol("break visit"),Gh=Symbol("skip children"),Ot=Symbol("remove node");function ts(e,t){let r=Uh(t);ge.isDocument(e)?Bi(null,e.contents,r,Object.freeze([e]))===Ot&&(e.contents=null):Bi(null,e,r,Object.freeze([]))}ts.BREAK=De;ts.SKIP=Gh;ts.REMOVE=Ot;function Bi(e,t,r,i){let n=Kh(e,t,r,i);if(ge.isNode(n)||ge.isPair(n))return Yh(e,i,n),Bi(e,n,r,i);if(typeof n!="symbol"){if(ge.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=Bi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===De)return De;o===Ot&&(t.items.splice(a,1),a-=1)}}}else if(ge.isPair(t)){i=Object.freeze(i.concat(t));let a=Bi("key",t.key,r,i);if(a===De)return De;a===Ot&&(t.key=null);let o=Bi("value",t.value,r,i);if(o===De)return De;o===Ot&&(t.value=null)}}return n}async function rs(e,t){let r=Uh(t);ge.isDocument(e)?await Li(null,e.contents,r,Object.freeze([e]))===Ot&&(e.contents=null):await Li(null,e,r,Object.freeze([]))}rs.BREAK=De;rs.SKIP=Gh;rs.REMOVE=Ot;async function Li(e,t,r,i){let n=await Kh(e,t,r,i);if(ge.isNode(n)||ge.isPair(n))return Yh(e,i,n),Li(e,n,r,i);if(typeof n!="symbol"){if(ge.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Li(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===De)return De;o===Ot&&(t.items.splice(a,1),a-=1)}}}else if(ge.isPair(t)){i=Object.freeze(i.concat(t));let a=await Li("key",t.key,r,i);if(a===De)return De;a===Ot&&(t.key=null);let o=await Li("value",t.value,r,i);if(o===De)return De;o===Ot&&(t.value=null)}}return n}function Uh(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Kh(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(ge.isMap(t))return r.Map?.(e,t,i);if(ge.isSeq(t))return r.Seq?.(e,t,i);if(ge.isPair(t))return r.Pair?.(e,t,i);if(ge.isScalar(t))return r.Scalar?.(e,t,i);if(ge.isAlias(t))return r.Alias?.(e,t,i)}function Yh(e,t,r){let i=t[t.length-1];if(ge.isCollection(i))i.items[e]=r;else if(ge.isPair(i))e==="key"?i.key=r:i.value=r;else if(ge.isDocument(i))i.contents=r;else{let n=ge.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}hu.visit=ts;hu.visitAsync=rs});var mu=R(Qh=>{"use strict";var Xh=G(),Qk=Jn(),Zk={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},eS=e=>e.replace(/[!,[\]{}]/g,t=>Zk[t]),Gn=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+eS(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Xh.isNode(t.contents)){let a={};Qk.visit(t.contents,(o,s)=>{Xh.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
- `)}};Gn.defaultYaml={explicit:!1,version:"1.2"};Gn.defaultTags={"!!":"tag:yaml.org,2002:"};Qh.Directives=Gn});var is=R(Un=>{"use strict";var Zh=G(),tS=Jn();function rS(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function em(e){let t=new Set;return tS.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function tm(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function iS(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=em(e));let o=tm(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Zh.isScalar(o.node)||Zh.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}Un.anchorIsValid=rS;Un.anchorNames=em;Un.createNodeAnchors=iS;Un.findNewAnchor=tm});var vu=R(rm=>{"use strict";function Kn(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Kn(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Kn(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Kn(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Kn(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}rm.applyReviver=Kn});var kr=R(nm=>{"use strict";var nS=G();function im(e,t,r){if(Array.isArray(e))return e.map((i,n)=>im(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!nS.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}nm.toJS=im});var ns=R(om=>{"use strict";var aS=vu(),am=G(),oS=kr(),gu=class{constructor(t){Object.defineProperty(this,am.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!am.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=oS.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?aS.applyReviver(a,{"":s},"",s):s}};om.NodeBase=gu});var Yn=R(sm=>{"use strict";var sS=is(),cS=Jn(),qi=G(),lS=ns(),uS=kr(),wu=class extends lS.NodeBase{constructor(t){super(qi.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],cS.visit(t,{Node:(a,o)=>{(qi.isAlias(o)||qi.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(uS.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=as(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(sS.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function as(e,t,r){if(qi.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(qi.isCollection(t)){let i=0;for(let n of t.items){let a=as(e,n,r);a>i&&(i=a)}return i}else if(qi.isPair(t)){let i=as(e,t.key,r),n=as(e,t.value,r);return Math.max(i,n)}return 1}sm.Alias=wu});var de=R(yu=>{"use strict";var dS=G(),fS=ns(),pS=kr(),hS=e=>!e||typeof e!="function"&&typeof e!="object",Sr=class extends fS.NodeBase{constructor(t){super(dS.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:pS.toJS(this.value,t,r)}toString(){return String(this.value)}};Sr.BLOCK_FOLDED="BLOCK_FOLDED";Sr.BLOCK_LITERAL="BLOCK_LITERAL";Sr.PLAIN="PLAIN";Sr.QUOTE_DOUBLE="QUOTE_DOUBLE";Sr.QUOTE_SINGLE="QUOTE_SINGLE";yu.Scalar=Sr;yu.isScalarValue=hS});var Xn=R(lm=>{"use strict";var mS=Yn(),ii=G(),cm=de(),vS="tag:yaml.org,2002:";function gS(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function wS(e,t,r){if(ii.isDocument(e)&&(e=e.contents),ii.isNode(e))return e;if(ii.isPair(e)){let f=r.schema[ii.MAP].createNode?.(r.schema,null,r);return f.items.push(e),f}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new mS.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=vS+t.slice(2));let l=gS(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let f=new cm.Scalar(e);return c&&(c.node=f),f}l=e instanceof Map?o[ii.MAP]:Symbol.iterator in Object(e)?o[ii.SEQ]:o[ii.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new cm.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}lm.createNode=wS});var ss=R(os=>{"use strict";var yS=Xn(),Ht=G(),NS=ns();function Nu(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return yS.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var um=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,bu=class extends NS.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>Ht.isNode(i)||Ht.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(um(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(Ht.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Nu(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(Ht.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&Ht.isScalar(a)?a.value:a:Ht.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Ht.isPair(r))return!1;let i=r.value;return i==null||t&&Ht.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return Ht.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(Ht.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Nu(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};os.Collection=bu;os.collectionFromPath=Nu;os.isEmptyPath=um});var Qn=R(cs=>{"use strict";var bS=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ku(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var kS=(e,t,r)=>e.endsWith(`
6
- `)?ku(r,t):r.includes(`
4
+ var qE=Object.create;var Zu=Object.defineProperty;var ME=Object.getOwnPropertyDescriptor;var VE=Object.getOwnPropertyNames;var WE=Object.getPrototypeOf,zE=Object.prototype.hasOwnProperty;var Bs=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var T=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var R=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},ed=(e,t)=>{for(var r in t)Zu(e,r,{get:t[r],enumerable:!0})},GE=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of VE(t))!zE.call(e,n)&&n!==r&&Zu(e,n,{get:()=>t[n],enumerable:!(i=ME(t,n))||i.enumerable});return e};var hr=(e,t,r)=>(r=e!=null?qE(WE(e)):{},GE(t||!e||!e.__esModule?Zu(r,"default",{value:e,enumerable:!0}):r,e));var U=R(Ie=>{"use strict";var td=Symbol.for("yaml.alias"),ov=Symbol.for("yaml.document"),Ls=Symbol.for("yaml.map"),sv=Symbol.for("yaml.pair"),rd=Symbol.for("yaml.scalar"),Fs=Symbol.for("yaml.seq"),mr=Symbol.for("yaml.node.type"),JE=e=>!!e&&typeof e=="object"&&e[mr]===td,UE=e=>!!e&&typeof e=="object"&&e[mr]===ov,KE=e=>!!e&&typeof e=="object"&&e[mr]===Ls,YE=e=>!!e&&typeof e=="object"&&e[mr]===sv,cv=e=>!!e&&typeof e=="object"&&e[mr]===rd,XE=e=>!!e&&typeof e=="object"&&e[mr]===Fs;function lv(e){if(e&&typeof e=="object")switch(e[mr]){case Ls:case Fs:return!0}return!1}function QE(e){if(e&&typeof e=="object")switch(e[mr]){case td:case Ls:case rd:case Fs:return!0}return!1}var ZE=e=>(cv(e)||lv(e))&&!!e.anchor;Ie.ALIAS=td;Ie.DOC=ov;Ie.MAP=Ls;Ie.NODE_TYPE=mr;Ie.PAIR=sv;Ie.SCALAR=rd;Ie.SEQ=Fs;Ie.hasAnchor=ZE;Ie.isAlias=JE;Ie.isCollection=lv;Ie.isDocument=UE;Ie.isMap=KE;Ie.isNode=QE;Ie.isPair=YE;Ie.isScalar=cv;Ie.isSeq=XE});var ya=R(id=>{"use strict";var Ne=U(),Me=Symbol("break visit"),uv=Symbol("skip children"),Wt=Symbol("remove node");function qs(e,t){let r=dv(t);Ne.isDocument(e)?cn(null,e.contents,r,Object.freeze([e]))===Wt&&(e.contents=null):cn(null,e,r,Object.freeze([]))}qs.BREAK=Me;qs.SKIP=uv;qs.REMOVE=Wt;function cn(e,t,r,i){let n=pv(e,t,r,i);if(Ne.isNode(n)||Ne.isPair(n))return fv(e,i,n),cn(e,n,r,i);if(typeof n!="symbol"){if(Ne.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=cn(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Me)return Me;o===Wt&&(t.items.splice(a,1),a-=1)}}}else if(Ne.isPair(t)){i=Object.freeze(i.concat(t));let a=cn("key",t.key,r,i);if(a===Me)return Me;a===Wt&&(t.key=null);let o=cn("value",t.value,r,i);if(o===Me)return Me;o===Wt&&(t.value=null)}}return n}async function Ms(e,t){let r=dv(t);Ne.isDocument(e)?await ln(null,e.contents,r,Object.freeze([e]))===Wt&&(e.contents=null):await ln(null,e,r,Object.freeze([]))}Ms.BREAK=Me;Ms.SKIP=uv;Ms.REMOVE=Wt;async function ln(e,t,r,i){let n=await pv(e,t,r,i);if(Ne.isNode(n)||Ne.isPair(n))return fv(e,i,n),ln(e,n,r,i);if(typeof n!="symbol"){if(Ne.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await ln(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Me)return Me;o===Wt&&(t.items.splice(a,1),a-=1)}}}else if(Ne.isPair(t)){i=Object.freeze(i.concat(t));let a=await ln("key",t.key,r,i);if(a===Me)return Me;a===Wt&&(t.key=null);let o=await ln("value",t.value,r,i);if(o===Me)return Me;o===Wt&&(t.value=null)}}return n}function dv(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function pv(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(Ne.isMap(t))return r.Map?.(e,t,i);if(Ne.isSeq(t))return r.Seq?.(e,t,i);if(Ne.isPair(t))return r.Pair?.(e,t,i);if(Ne.isScalar(t))return r.Scalar?.(e,t,i);if(Ne.isAlias(t))return r.Alias?.(e,t,i)}function fv(e,t,r){let i=t[t.length-1];if(Ne.isCollection(i))i.items[e]=r;else if(Ne.isPair(i))e==="key"?i.key=r:i.value=r;else if(Ne.isDocument(i))i.contents=r;else{let n=Ne.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}id.visit=qs;id.visitAsync=Ms});var nd=R(mv=>{"use strict";var hv=U(),ex=ya(),tx={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},rx=e=>e.replace(/[!,[\]{}]/g,t=>tx[t]),ba=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+rx(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&hv.isNode(t.contents)){let a={};ex.visit(t.contents,(o,s)=>{hv.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
+ `)}};ba.defaultYaml={explicit:!1,version:"1.2"};ba.defaultTags={"!!":"tag:yaml.org,2002:"};mv.Directives=ba});var Vs=R(Na=>{"use strict";var vv=U(),ix=ya();function nx(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function gv(e){let t=new Set;return ix.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function wv(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function ax(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=gv(e));let o=wv(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(vv.isScalar(o.node)||vv.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}Na.anchorIsValid=nx;Na.anchorNames=gv;Na.createNodeAnchors=ax;Na.findNewAnchor=wv});var ad=R(yv=>{"use strict";function ka(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=ka(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=ka(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=ka(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=ka(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}yv.applyReviver=ka});var Hr=R(Nv=>{"use strict";var ox=U();function bv(e,t,r){if(Array.isArray(e))return e.map((i,n)=>bv(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!ox.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}Nv.toJS=bv});var Ws=R(Sv=>{"use strict";var sx=ad(),kv=U(),cx=Hr(),od=class{constructor(t){Object.defineProperty(this,kv.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!kv.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=cx.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?sx.applyReviver(a,{"":s},"",s):s}};Sv.NodeBase=od});var Sa=R(Ev=>{"use strict";var lx=Vs(),ux=ya(),un=U(),dx=Ws(),px=Hr(),sd=class extends dx.NodeBase{constructor(t){super(un.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],ux.visit(t,{Node:(a,o)=>{(un.isAlias(o)||un.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(px.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=zs(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(lx.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function zs(e,t,r){if(un.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(un.isCollection(t)){let i=0;for(let n of t.items){let a=zs(e,n,r);a>i&&(i=a)}return i}else if(un.isPair(t)){let i=zs(e,t.key,r),n=zs(e,t.value,r);return Math.max(i,n)}return 1}Ev.Alias=sd});var we=R(cd=>{"use strict";var fx=U(),hx=Ws(),mx=Hr(),vx=e=>!e||typeof e!="function"&&typeof e!="object",Dr=class extends hx.NodeBase{constructor(t){super(fx.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:mx.toJS(this.value,t,r)}toString(){return String(this.value)}};Dr.BLOCK_FOLDED="BLOCK_FOLDED";Dr.BLOCK_LITERAL="BLOCK_LITERAL";Dr.PLAIN="PLAIN";Dr.QUOTE_DOUBLE="QUOTE_DOUBLE";Dr.QUOTE_SINGLE="QUOTE_SINGLE";cd.Scalar=Dr;cd.isScalarValue=vx});var Ea=R(Rv=>{"use strict";var gx=Sa(),wi=U(),xv=we(),wx="tag:yaml.org,2002:";function yx(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function bx(e,t,r){if(wi.isDocument(e)&&(e=e.contents),wi.isNode(e))return e;if(wi.isPair(e)){let p=r.schema[wi.MAP].createNode?.(r.schema,null,r);return p.items.push(e),p}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new gx.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=wx+t.slice(2));let l=yx(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let p=new xv.Scalar(e);return c&&(c.node=p),p}l=e instanceof Map?o[wi.MAP]:Symbol.iterator in Object(e)?o[wi.SEQ]:o[wi.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new xv.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Rv.createNode=bx});var Js=R(Gs=>{"use strict";var Nx=Ea(),zt=U(),kx=Ws();function ld(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return Nx.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Cv=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ud=class extends kx.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>zt.isNode(i)||zt.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Cv(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(zt.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,ld(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(zt.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&zt.isScalar(a)?a.value:a:zt.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!zt.isPair(r))return!1;let i=r.value;return i==null||t&&zt.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return zt.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(zt.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,ld(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Gs.Collection=ud;Gs.collectionFromPath=ld;Gs.isEmptyPath=Cv});var xa=R(Us=>{"use strict";var Sx=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function dd(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Ex=(e,t,r)=>e.endsWith(`
6
+ `)?dd(r,t):r.includes(`
7
7
  `)?`
8
- `+ku(r,t):(e.endsWith(" ")?"":" ")+r;cs.indentComment=ku;cs.lineComment=kS;cs.stringifyComment=bS});var fm=R(Zn=>{"use strict";var SS="flow",Su="block",ls="quoted";function ES(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},f=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):f=n-i);let d,p,m=!1,h=-1,g=-1,v=-1;r===Su&&(h=dm(e,h,t.length),h!==-1&&(f=h+c));for(let y;y=e[h+=1];){if(r===ls&&y==="\\"){switch(g=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}v=h}if(y===`
9
- `)r===Su&&(h=dm(e,h,t.length)),f=h+t.length+c,d=void 0;else{if(y===" "&&p&&p!==" "&&p!==`
10
- `&&p!==" "){let b=e[h+1];b&&b!==" "&&b!==`
11
- `&&b!==" "&&(d=h)}if(h>=f)if(d)l.push(d),f=d+c,d=void 0;else if(r===ls){for(;p===" "||p===" ";)p=y,y=e[h+=1],m=!0;let b=h>v+1?h-2:g-1;if(u[b])return e;l.push(b),u[b]=!0,f=b+c,d=void 0}else m=!0}p=y}if(m&&s&&s(),l.length===0)return e;o&&o();let w=e.slice(0,l[0]);for(let y=0;y<l.length;++y){let b=l[y],S=l[y+1]||e.length;b===0?w=`
12
- ${t}${e.slice(0,S)}`:(r===ls&&u[b]&&(w+=`${e[b]}\\`),w+=`
13
- ${t}${e.slice(b+1,S)}`)}return w}function dm(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
- `);i=t,n=t+1,a=e[n]}return i}Zn.FOLD_BLOCK=Su;Zn.FOLD_FLOW=SS;Zn.FOLD_QUOTED=ls;Zn.foldFlowLines=ES});var ta=R(pm=>{"use strict";var vt=de(),Er=fm(),ds=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),fs=e=>/^(%|---|\.\.\.)/m.test(e);function xS(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
- `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function ea(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(fs(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
8
+ `+dd(r,t):(e.endsWith(" ")?"":" ")+r;Us.indentComment=dd;Us.lineComment=Ex;Us.stringifyComment=Sx});var _v=R(Ra=>{"use strict";var xx="flow",pd="block",Ks="quoted";function Rx(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},p=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):p=n-i);let d,f,h=!1,m=-1,v=-1,g=-1;r===pd&&(m=Pv(e,m,t.length),m!==-1&&(p=m+c));for(let N;N=e[m+=1];){if(r===Ks&&N==="\\"){switch(v=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}g=m}if(N===`
9
+ `)r===pd&&(m=Pv(e,m,t.length)),p=m+t.length+c,d=void 0;else{if(N===" "&&f&&f!==" "&&f!==`
10
+ `&&f!==" "){let y=e[m+1];y&&y!==" "&&y!==`
11
+ `&&y!==" "&&(d=m)}if(m>=p)if(d)l.push(d),p=d+c,d=void 0;else if(r===Ks){for(;f===" "||f===" ";)f=N,N=e[m+=1],h=!0;let y=m>g+1?m-2:v-1;if(u[y])return e;l.push(y),u[y]=!0,p=y+c,d=void 0}else h=!0}f=N}if(h&&s&&s(),l.length===0)return e;o&&o();let w=e.slice(0,l[0]);for(let N=0;N<l.length;++N){let y=l[N],E=l[N+1]||e.length;y===0?w=`
12
+ ${t}${e.slice(0,E)}`:(r===Ks&&u[y]&&(w+=`${e[y]}\\`),w+=`
13
+ ${t}${e.slice(y+1,E)}`)}return w}function Pv(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
+ `);i=t,n=t+1,a=e[n]}return i}Ra.FOLD_BLOCK=pd;Ra.FOLD_FLOW=xx;Ra.FOLD_QUOTED=Ks;Ra.foldFlowLines=Rx});var Pa=R(Av=>{"use strict";var Rt=we(),Br=_v(),Xs=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Qs=e=>/^(%|---|\.\.\.)/m.test(e);function Cx(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
+ `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function Ca(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Qs(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
16
16
 
17
17
  `;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
18
- `,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:Er.foldFlowLines(o,a,Er.FOLD_QUOTED,ds(t,!1))}function Eu(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(e))return ea(e,t);let r=t.indent||(fs(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${r}`)+"'";return t.implicitKey?i:Er.foldFlowLines(i,r,Er.FOLD_FLOW,ds(t,!1))}function Fi(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=ea;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Eu:a&&!n?i=ea:i=r?Eu:ea}return i(e,t)}var xu;try{xu=new RegExp(`(^|(?<!
18
+ `,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:Br.foldFlowLines(o,a,Br.FOLD_QUOTED,Xs(t,!1))}function fd(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(e))return Ca(e,t);let r=t.indent||(Qs(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${r}`)+"'";return t.implicitKey?i:Br.foldFlowLines(i,r,Br.FOLD_FLOW,Xs(t,!1))}function dn(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=Ca;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=fd:a&&!n?i=Ca:i=r?fd:Ca}return i(e,t)}var hd;try{hd=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{xu=/\n+(?!\n|$)/g}function us({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return Fi(r,i);let l=i.indent||(i.forceBlockIndent||fs(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===vt.Scalar.BLOCK_FOLDED?!1:t===vt.Scalar.BLOCK_LITERAL?!0:!xS(r,c,l.length);if(!r)return u?`|
23
+ |$)`,"g")}catch{hd=/\n+(?!\n|$)/g}function Ys({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return dn(r,i);let l=i.indent||(i.forceBlockIndent||Qs(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===Rt.Scalar.BLOCK_FOLDED?!1:t===Rt.Scalar.BLOCK_LITERAL?!0:!Cx(r,c,l.length);if(!r)return u?`|
24
24
  `:`>
25
- `;let f,d;for(d=r.length;d>0;--d){let S=r[d-1];if(S!==`
26
- `&&S!==" "&&S!==" ")break}let p=r.substring(d),m=p.indexOf(`
27
- `);m===-1?f="-":r===p||m!==p.length-1?(f="+",a&&a()):f="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
28
- `&&(p=p.slice(0,-1)),p=p.replace(xu,`$&${l}`));let h=!1,g,v=-1;for(g=0;g<r.length;++g){let S=r[g];if(S===" ")h=!0;else if(S===`
29
- `)v=g;else break}let w=r.substring(0,v<g?v+1:g);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let b=(h?l?"2":"1":"")+f;if(e&&(b+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let S=r.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),N=!1,x=ds(i,!0);o!=="folded"&&t!==vt.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{N=!0});let k=Er.foldFlowLines(`${w}${S}${p}`,l,Er.FOLD_BLOCK,x);if(!N)return`>${b}
31
- ${l}${k}`}return r=r.replace(/\n+/g,`$&${l}`),`|${b}
32
- ${l}${w}${r}${p}`}function CS(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
33
- `)||u&&/[[\]{},]/.test(a))return Fi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
- `)?Fi(a,t):us(e,t,r,i);if(!s&&!u&&n!==vt.Scalar.PLAIN&&a.includes(`
35
- `))return us(e,t,r,i);if(fs(a)){if(c==="")return t.forceBlockIndent=!0,us(e,t,r,i);if(s&&c===l)return Fi(a,t)}let f=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let d=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(f),{compat:p,tags:m}=t.doc.schema;if(m.some(d)||p?.some(d))return Fi(a,t)}return s?f:Er.foldFlowLines(f,c,Er.FOLD_FLOW,ds(t,!1))}function RS(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==vt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=vt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case vt.Scalar.BLOCK_FOLDED:case vt.Scalar.BLOCK_LITERAL:return n||a?Fi(o.value,t):us(o,t,r,i);case vt.Scalar.QUOTE_DOUBLE:return ea(o.value,t);case vt.Scalar.QUOTE_SINGLE:return Eu(o.value,t);case vt.Scalar.PLAIN:return CS(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:f}=t.options,d=n&&u||f;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}pm.stringifyString=RS});var ra=R(Cu=>{"use strict";var PS=is(),xr=G(),_S=Qn(),AS=ta();function IS(e,t){let r=Object.assign({blockQuote:!0,commentString:_S.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function TS(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(xr.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function jS(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(xr.isScalar(e)||xr.isCollection(e))&&e.anchor;a&&PS.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function $S(e,t,r,i){if(xr.isPair(e))return e.toString(t,r,i);if(xr.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=xr.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=TS(t.doc.schema.tags,a));let o=jS(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):xr.isScalar(a)?AS.stringifyString(a,t,r,i):a.toString(t,r,i);return o?xr.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}Cu.createStringifyContext=IS;Cu.stringify=$S});var gm=R(vm=>{"use strict";var tr=G(),hm=de(),mm=ra(),ia=Qn();function OS({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:f}}=r,d=tr.isNode(e)&&e.comment||null;if(f){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(tr.isCollection(e)||!tr.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let p=!f&&(!e||d&&t==null&&!r.inFlow||tr.isCollection(e)||(tr.isScalar(e)?e.type===hm.Scalar.BLOCK_FOLDED||e.type===hm.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(f||!a),indent:s+c});let m=!1,h=!1,g=mm.stringify(e,r,()=>m=!0,()=>h=!0);if(!p&&!r.inFlow&&g.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(a||t==null)return m&&i&&i(),g===""?"?":p?`? ${g}`:g}else if(a&&!f||t==null&&p)return g=`? ${g}`,d&&!m?g+=ia.lineComment(g,r.indent,l(d)):h&&n&&n(),g;m&&(d=null),p?(d&&(g+=ia.lineComment(g,r.indent,l(d))),g=`? ${g}
38
- ${s}:`):(g=`${g}:`,d&&(g+=ia.lineComment(g,r.indent,l(d))));let v,w,y;tr.isNode(t)?(v=!!t.spaceBefore,w=t.commentBefore,y=t.comment):(v=!1,w=null,y=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!d&&tr.isScalar(t)&&(r.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!p&&tr.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let b=!1,S=mm.stringify(t,r,()=>b=!0,()=>h=!0),N=" ";if(d||v||w){if(N=v?`
39
- `:"",w){let x=l(w);N+=`
40
- ${ia.indentComment(x,r.indent)}`}S===""&&!r.inFlow?N===`
41
- `&&y&&(N=`
25
+ `;let p,d;for(d=r.length;d>0;--d){let E=r[d-1];if(E!==`
26
+ `&&E!==" "&&E!==" ")break}let f=r.substring(d),h=f.indexOf(`
27
+ `);h===-1?p="-":r===f||h!==f.length-1?(p="+",a&&a()):p="",f&&(r=r.slice(0,-f.length),f[f.length-1]===`
28
+ `&&(f=f.slice(0,-1)),f=f.replace(hd,`$&${l}`));let m=!1,v,g=-1;for(v=0;v<r.length;++v){let E=r[v];if(E===" ")m=!0;else if(E===`
29
+ `)g=v;else break}let w=r.substring(0,g<v?g+1:v);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let y=(m?l?"2":"1":"")+p;if(e&&(y+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let E=r.replace(/\n+/g,`
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),b=!1,x=Xs(i,!0);o!=="folded"&&t!==Rt.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{b=!0});let k=Br.foldFlowLines(`${w}${E}${f}`,l,Br.FOLD_BLOCK,x);if(!b)return`>${y}
31
+ ${l}${k}`}return r=r.replace(/\n+/g,`$&${l}`),`|${y}
32
+ ${l}${w}${r}${f}`}function Px(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
33
+ `)||u&&/[[\]{},]/.test(a))return dn(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
+ `)?dn(a,t):Ys(e,t,r,i);if(!s&&!u&&n!==Rt.Scalar.PLAIN&&a.includes(`
35
+ `))return Ys(e,t,r,i);if(Qs(a)){if(c==="")return t.forceBlockIndent=!0,Ys(e,t,r,i);if(s&&c===l)return dn(a,t)}let p=a.replace(/\n+/g,`$&
36
+ ${c}`);if(o){let d=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(p),{compat:f,tags:h}=t.doc.schema;if(h.some(d)||f?.some(d))return dn(a,t)}return s?p:Br.foldFlowLines(p,c,Br.FOLD_FLOW,Xs(t,!1))}function _x(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Rt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Rt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Rt.Scalar.BLOCK_FOLDED:case Rt.Scalar.BLOCK_LITERAL:return n||a?dn(o.value,t):Ys(o,t,r,i);case Rt.Scalar.QUOTE_DOUBLE:return Ca(o.value,t);case Rt.Scalar.QUOTE_SINGLE:return fd(o.value,t);case Rt.Scalar.PLAIN:return Px(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:p}=t.options,d=n&&u||p;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Av.stringifyString=_x});var _a=R(md=>{"use strict";var Ax=Vs(),Lr=U(),Ix=xa(),Tx=Pa();function $x(e,t){let r=Object.assign({blockQuote:!0,commentString:Ix.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function jx(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(Lr.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function Ox(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Lr.isScalar(e)||Lr.isCollection(e))&&e.anchor;a&&Ax.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function Hx(e,t,r,i){if(Lr.isPair(e))return e.toString(t,r,i);if(Lr.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=Lr.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=jx(t.doc.schema.tags,a));let o=Ox(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):Lr.isScalar(a)?Tx.stringifyString(a,t,r,i):a.toString(t,r,i);return o?Lr.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}md.createStringifyContext=$x;md.stringify=Hx});var jv=R($v=>{"use strict";var vr=U(),Iv=we(),Tv=_a(),Aa=xa();function Dx({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:p}}=r,d=vr.isNode(e)&&e.comment||null;if(p){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(vr.isCollection(e)||!vr.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let f=!p&&(!e||d&&t==null&&!r.inFlow||vr.isCollection(e)||(vr.isScalar(e)?e.type===Iv.Scalar.BLOCK_FOLDED||e.type===Iv.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!f&&(p||!a),indent:s+c});let h=!1,m=!1,v=Tv.stringify(e,r,()=>h=!0,()=>m=!0);if(!f&&!r.inFlow&&v.length>1024){if(p)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");f=!0}if(r.inFlow){if(a||t==null)return h&&i&&i(),v===""?"?":f?`? ${v}`:v}else if(a&&!p||t==null&&f)return v=`? ${v}`,d&&!h?v+=Aa.lineComment(v,r.indent,l(d)):m&&n&&n(),v;h&&(d=null),f?(d&&(v+=Aa.lineComment(v,r.indent,l(d))),v=`? ${v}
38
+ ${s}:`):(v=`${v}:`,d&&(v+=Aa.lineComment(v,r.indent,l(d))));let g,w,N;vr.isNode(t)?(g=!!t.spaceBefore,w=t.commentBefore,N=t.comment):(g=!1,w=null,N=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!f&&!d&&vr.isScalar(t)&&(r.indentAtStart=v.length+1),m=!1,!u&&c.length>=2&&!r.inFlow&&!f&&vr.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let y=!1,E=Tv.stringify(t,r,()=>y=!0,()=>m=!0),b=" ";if(d||g||w){if(b=g?`
39
+ `:"",w){let x=l(w);b+=`
40
+ ${Aa.indentComment(x,r.indent)}`}E===""&&!r.inFlow?b===`
41
+ `&&N&&(b=`
42
42
 
43
- `):N+=`
44
- ${r.indent}`}else if(!p&&tr.isCollection(t)){let x=S[0],k=S.indexOf(`
45
- `),E=k!==-1,C=r.inFlow??t.flow??t.items.length===0;if(E||!C){let H=!1;if(E&&(x==="&"||x==="!")){let P=S.indexOf(" ");x==="&"&&P!==-1&&P<k&&S[P+1]==="!"&&(P=S.indexOf(" ",P+1)),(P===-1||k<P)&&(H=!0)}H||(N=`
46
- ${r.indent}`)}}else(S===""||S[0]===`
47
- `)&&(N="");return g+=N+S,r.inFlow?b&&i&&i():y&&!b?g+=ia.lineComment(g,r.indent,l(y)):h&&n&&n(),g}vm.stringifyPair=OS});var Pu=R(Ru=>{"use strict";var wm=Qo("process");function HS(e,...t){e==="debug"&&console.log(...t)}function DS(e,t){(e==="debug"||e==="warn")&&(typeof wm.emitWarning=="function"?wm.emitWarning(t):console.warn(t))}Ru.debug=HS;Ru.warn=DS});var gs=R(vs=>{"use strict";var ms=G(),ym=de(),ps="<<",hs={identify:e=>e===ps||typeof e=="symbol"&&e.description===ps,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new ym.Scalar(Symbol(ps)),{addToJSMap:Nm}),stringify:()=>ps},BS=(e,t)=>(hs.identify(t)||ms.isScalar(t)&&(!t.type||t.type===ym.Scalar.PLAIN)&&hs.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===hs.tag&&r.default);function Nm(e,t,r){let i=bm(e,r);if(ms.isSeq(i))for(let n of i.items)_u(e,t,n);else if(Array.isArray(i))for(let n of i)_u(e,t,n);else _u(e,t,i)}function _u(e,t,r){let i=bm(e,r);if(!ms.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function bm(e,t){return e&&ms.isAlias(t)?t.resolve(e.doc,e):t}vs.addMergeToJSMap=Nm;vs.isMergeKey=BS;vs.merge=hs});var Iu=R(Em=>{"use strict";var LS=Pu(),km=gs(),qS=ra(),Sm=G(),Au=kr();function FS(e,t,{key:r,value:i}){if(Sm.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(km.isMergeKey(e,r))km.addMergeToJSMap(e,t,i);else{let n=Au.toJS(r,"",e);if(t instanceof Map)t.set(n,Au.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=VS(r,n,e),o=Au.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function VS(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Sm.isNode(e)&&r?.doc){let i=qS.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),LS.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}Em.addPairToJSMap=FS});var Cr=R(Tu=>{"use strict";var xm=Xn(),MS=gm(),WS=Iu(),ws=G();function zS(e,t,r){let i=xm.createNode(e,void 0,r),n=xm.createNode(t,void 0,r);return new ys(i,n)}var ys=class e{constructor(t,r=null){Object.defineProperty(this,ws.NODE_TYPE,{value:ws.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return ws.isNode(r)&&(r=r.clone(t)),ws.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return WS.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?MS.stringifyPair(this,t,r,i):JSON.stringify(this)}};Tu.Pair=ys;Tu.createPair=zS});var ju=R(Rm=>{"use strict";var ni=G(),Cm=ra(),Ns=Qn();function JS(e,t,r){return(t.inFlow??e.flow?US:GS)(e,t,r)}function GS({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),f=!1,d=[];for(let m=0;m<t.length;++m){let h=t[m],g=null;if(ni.isNode(h))!f&&h.spaceBefore&&d.push(""),bs(r,d,h.commentBefore,f),h.comment&&(g=h.comment);else if(ni.isPair(h)){let w=ni.isNode(h.key)?h.key:null;w&&(!f&&w.spaceBefore&&d.push(""),bs(r,d,w.commentBefore,f))}f=!1;let v=Cm.stringify(h,u,()=>g=null,()=>f=!0);g&&(v+=Ns.lineComment(v,a,l(g))),f&&g&&(f=!1),d.push(i+v)}let p;if(d.length===0)p=n.start+n.end;else{p=d[0];for(let m=1;m<d.length;++m){let h=d[m];p+=h?`
48
- ${c}${h}`:`
49
- `}}return e?(p+=`
50
- `+Ns.indentComment(l(e),c),s&&s()):f&&o&&o(),p}function US({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,u=0,f=[];for(let m=0;m<e.length;++m){let h=e[m],g=null;if(ni.isNode(h))h.spaceBefore&&f.push(""),bs(t,f,h.commentBefore,!1),h.comment&&(g=h.comment);else if(ni.isPair(h)){let w=ni.isNode(h.key)?h.key:null;w&&(w.spaceBefore&&f.push(""),bs(t,f,w.commentBefore,!1),w.comment&&(l=!0));let y=ni.isNode(h.value)?h.value:null;y?(y.comment&&(g=y.comment),y.commentBefore&&(l=!0)):h.value==null&&w?.comment&&(g=w.comment)}g&&(l=!0);let v=Cm.stringify(h,c,()=>g=null);l||(l=f.length>u||v.includes(`
51
- `)),m<e.length-1?v+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=f.reduce((w,y)=>w+y.length+2,2)+(v.length+2)>t.options.lineWidth)),l&&(v+=",")),g&&(v+=Ns.lineComment(v,i,s(g))),f.push(v),u=f.length}let{start:d,end:p}=r;if(f.length===0)return d+p;if(!l){let m=f.reduce((h,g)=>h+g.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=d;for(let h of f)m+=h?`
52
- ${a}${n}${h}`:`
53
- `;return`${m}
54
- ${n}${p}`}else return`${d}${o}${f.join(" ")}${o}${p}`}function bs({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=Ns.indentComment(t(i),e);r.push(a.trimStart())}}Rm.stringifyCollection=JS});var Pr=R(Ou=>{"use strict";var KS=ju(),YS=Iu(),XS=ss(),Rr=G(),ks=Cr(),QS=de();function na(e,t){let r=Rr.isScalar(t)?t.value:t;for(let i of e)if(Rr.isPair(i)&&(i.key===t||i.key===r||Rr.isScalar(i.key)&&i.key.value===r))return i}var $u=class extends XS.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Rr.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(ks.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;Rr.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new ks.Pair(t,t?.value):i=new ks.Pair(t.key,t.value);let n=na(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Rr.isScalar(n.value)&&QS.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=na(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=na(this.items,t)?.value;return(!r&&Rr.isScalar(n)?n.value:n)??void 0}has(t){return!!na(this.items,t)}set(t,r){this.add(new ks.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)YS.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Rr.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),KS.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Ou.YAMLMap=$u;Ou.findPair=na});var Vi=R(_m=>{"use strict";var ZS=G(),Pm=Pr(),eE={collection:"map",default:!0,nodeClass:Pm.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return ZS.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Pm.YAMLMap.from(e,t,r)};_m.map=eE});var _r=R(Am=>{"use strict";var tE=Xn(),rE=ju(),iE=ss(),Es=G(),nE=de(),aE=kr(),Hu=class extends iE.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Es.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Ss(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=Ss(t);if(typeof i!="number")return;let n=this.items[i];return!r&&Es.isScalar(n)?n.value:n}has(t){let r=Ss(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=Ss(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];Es.isScalar(n)&&nE.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(aE.toJS(a,String(n++),r));return i}toString(t,r,i){return t?rE.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(tE.createNode(s,void 0,i))}}return a}};function Ss(e){let t=Es.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Am.YAMLSeq=Hu});var Mi=R(Tm=>{"use strict";var oE=G(),Im=_r(),sE={collection:"seq",default:!0,nodeClass:Im.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return oE.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Im.YAMLSeq.from(e,t,r)};Tm.seq=sE});var aa=R(jm=>{"use strict";var cE=ta(),lE={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),cE.stringifyString(e,t,r,i)}};jm.string=lE});var xs=R(Hm=>{"use strict";var $m=de(),Om={identify:e=>e==null,createNode:()=>new $m.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new $m.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Om.test.test(e)?e:t.options.nullStr};Hm.nullTag=Om});var Du=R(Bm=>{"use strict";var uE=de(),Dm={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new uE.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Dm.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Bm.boolTag=Dm});var Wi=R(Lm=>{"use strict";function dE({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Lm.stringifyNumber=dE});var Lu=R(Cs=>{"use strict";var fE=de(),Bu=Wi(),pE={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Bu.stringifyNumber},hE={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Bu.stringifyNumber(e)}},mE={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new fE.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Bu.stringifyNumber};Cs.float=mE;Cs.floatExp=hE;Cs.floatNaN=pE});var Fu=R(Ps=>{"use strict";var qm=Wi(),Rs=e=>typeof e=="bigint"||Number.isInteger(e),qu=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Fm(e,t,r){let{value:i}=e;return Rs(i)&&i>=0?r+i.toString(t):qm.stringifyNumber(e)}var vE={identify:e=>Rs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>qu(e,2,8,r),stringify:e=>Fm(e,8,"0o")},gE={identify:Rs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>qu(e,0,10,r),stringify:qm.stringifyNumber},wE={identify:e=>Rs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>qu(e,2,16,r),stringify:e=>Fm(e,16,"0x")};Ps.int=gE;Ps.intHex=wE;Ps.intOct=vE});var Mm=R(Vm=>{"use strict";var yE=Vi(),NE=xs(),bE=Mi(),kE=aa(),SE=Du(),Vu=Lu(),Mu=Fu(),EE=[yE.map,bE.seq,kE.string,NE.nullTag,SE.boolTag,Mu.intOct,Mu.int,Mu.intHex,Vu.floatNaN,Vu.floatExp,Vu.float];Vm.schema=EE});var Jm=R(zm=>{"use strict";var xE=de(),CE=Vi(),RE=Mi();function Wm(e){return typeof e=="bigint"||Number.isInteger(e)}var _s=({value:e})=>JSON.stringify(e),PE=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:_s},{identify:e=>e==null,createNode:()=>new xE.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:_s},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:_s},{identify:Wm,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>Wm(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:_s}],_E={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},AE=[CE.map,RE.seq].concat(PE,_E);zm.schema=AE});var zu=R(Gm=>{"use strict";var oa=Qo("buffer"),Wu=de(),IE=ta(),TE={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof oa.Buffer=="function")return oa.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof oa.Buffer=="function")s=o instanceof oa.Buffer?o.toString("base64"):oa.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Wu.Scalar.BLOCK_LITERAL),t!==Wu.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let f=0,d=0;f<l;++f,d+=c)u[f]=s.substr(d,c);s=u.join(t===Wu.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return IE.stringifyString({comment:e,type:t,value:s},i,n,a)}};Gm.binary=TE});var Ts=R(Is=>{"use strict";var As=G(),Ju=Cr(),jE=de(),$E=_r();function Um(e,t){if(As.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!As.isPair(i)){if(As.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new Ju.Pair(new jE.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
43
+ `):b+=`
44
+ ${r.indent}`}else if(!f&&vr.isCollection(t)){let x=E[0],k=E.indexOf(`
45
+ `),S=k!==-1,C=r.inFlow??t.flow??t.items.length===0;if(S||!C){let P=!1;if(S&&(x==="&"||x==="!")){let _=E.indexOf(" ");x==="&"&&_!==-1&&_<k&&E[_+1]==="!"&&(_=E.indexOf(" ",_+1)),(_===-1||k<_)&&(P=!0)}P||(b=`
46
+ ${r.indent}`)}}else(E===""||E[0]===`
47
+ `)&&(b="");return v+=b+E,r.inFlow?y&&i&&i():N&&!y?v+=Aa.lineComment(v,r.indent,l(N)):m&&n&&n(),v}$v.stringifyPair=Dx});var gd=R(vd=>{"use strict";var Ov=Bs("process");function Bx(e,...t){e==="debug"&&console.log(...t)}function Lx(e,t){(e==="debug"||e==="warn")&&(typeof Ov.emitWarning=="function"?Ov.emitWarning(t):console.warn(t))}vd.debug=Bx;vd.warn=Lx});var ic=R(rc=>{"use strict";var tc=U(),Hv=we(),Zs="<<",ec={identify:e=>e===Zs||typeof e=="symbol"&&e.description===Zs,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Hv.Scalar(Symbol(Zs)),{addToJSMap:Dv}),stringify:()=>Zs},Fx=(e,t)=>(ec.identify(t)||tc.isScalar(t)&&(!t.type||t.type===Hv.Scalar.PLAIN)&&ec.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===ec.tag&&r.default);function Dv(e,t,r){let i=Bv(e,r);if(tc.isSeq(i))for(let n of i.items)wd(e,t,n);else if(Array.isArray(i))for(let n of i)wd(e,t,n);else wd(e,t,i)}function wd(e,t,r){let i=Bv(e,r);if(!tc.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Bv(e,t){return e&&tc.isAlias(t)?t.resolve(e.doc,e):t}rc.addMergeToJSMap=Dv;rc.isMergeKey=Fx;rc.merge=ec});var bd=R(qv=>{"use strict";var qx=gd(),Lv=ic(),Mx=_a(),Fv=U(),yd=Hr();function Vx(e,t,{key:r,value:i}){if(Fv.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(Lv.isMergeKey(e,r))Lv.addMergeToJSMap(e,t,i);else{let n=yd.toJS(r,"",e);if(t instanceof Map)t.set(n,yd.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=Wx(r,n,e),o=yd.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Wx(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Fv.isNode(e)&&r?.doc){let i=Mx.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),qx.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}qv.addPairToJSMap=Vx});var Fr=R(Nd=>{"use strict";var Mv=Ea(),zx=jv(),Gx=bd(),nc=U();function Jx(e,t,r){let i=Mv.createNode(e,void 0,r),n=Mv.createNode(t,void 0,r);return new ac(i,n)}var ac=class e{constructor(t,r=null){Object.defineProperty(this,nc.NODE_TYPE,{value:nc.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return nc.isNode(r)&&(r=r.clone(t)),nc.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return Gx.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?zx.stringifyPair(this,t,r,i):JSON.stringify(this)}};Nd.Pair=ac;Nd.createPair=Jx});var kd=R(Wv=>{"use strict";var yi=U(),Vv=_a(),oc=xa();function Ux(e,t,r){return(t.inFlow??e.flow?Yx:Kx)(e,t,r)}function Kx({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),p=!1,d=[];for(let h=0;h<t.length;++h){let m=t[h],v=null;if(yi.isNode(m))!p&&m.spaceBefore&&d.push(""),sc(r,d,m.commentBefore,p),m.comment&&(v=m.comment);else if(yi.isPair(m)){let w=yi.isNode(m.key)?m.key:null;w&&(!p&&w.spaceBefore&&d.push(""),sc(r,d,w.commentBefore,p))}p=!1;let g=Vv.stringify(m,u,()=>v=null,()=>p=!0);v&&(g+=oc.lineComment(g,a,l(v))),p&&v&&(p=!1),d.push(i+g)}let f;if(d.length===0)f=n.start+n.end;else{f=d[0];for(let h=1;h<d.length;++h){let m=d[h];f+=m?`
48
+ ${c}${m}`:`
49
+ `}}return e?(f+=`
50
+ `+oc.indentComment(l(e),c),s&&s()):p&&o&&o(),f}function Yx({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,u=0,p=[];for(let h=0;h<e.length;++h){let m=e[h],v=null;if(yi.isNode(m))m.spaceBefore&&p.push(""),sc(t,p,m.commentBefore,!1),m.comment&&(v=m.comment);else if(yi.isPair(m)){let w=yi.isNode(m.key)?m.key:null;w&&(w.spaceBefore&&p.push(""),sc(t,p,w.commentBefore,!1),w.comment&&(l=!0));let N=yi.isNode(m.value)?m.value:null;N?(N.comment&&(v=N.comment),N.commentBefore&&(l=!0)):m.value==null&&w?.comment&&(v=w.comment)}v&&(l=!0);let g=Vv.stringify(m,c,()=>v=null);l||(l=p.length>u||g.includes(`
51
+ `)),h<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=p.reduce((w,N)=>w+N.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),v&&(g+=oc.lineComment(g,i,s(v))),p.push(g),u=p.length}let{start:d,end:f}=r;if(p.length===0)return d+f;if(!l){let h=p.reduce((m,v)=>m+v.length+2,2);l=t.options.lineWidth>0&&h>t.options.lineWidth}if(l){let h=d;for(let m of p)h+=m?`
52
+ ${a}${n}${m}`:`
53
+ `;return`${h}
54
+ ${n}${f}`}else return`${d}${o}${p.join(" ")}${o}${f}`}function sc({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=oc.indentComment(t(i),e);r.push(a.trimStart())}}Wv.stringifyCollection=Ux});var Mr=R(Ed=>{"use strict";var Xx=kd(),Qx=bd(),Zx=Js(),qr=U(),cc=Fr(),eR=we();function Ia(e,t){let r=qr.isScalar(t)?t.value:t;for(let i of e)if(qr.isPair(i)&&(i.key===t||i.key===r||qr.isScalar(i.key)&&i.key.value===r))return i}var Sd=class extends Zx.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(qr.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(cc.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;qr.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new cc.Pair(t,t?.value):i=new cc.Pair(t.key,t.value);let n=Ia(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);qr.isScalar(n.value)&&eR.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=Ia(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=Ia(this.items,t)?.value;return(!r&&qr.isScalar(n)?n.value:n)??void 0}has(t){return!!Ia(this.items,t)}set(t,r){this.add(new cc.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)Qx.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!qr.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Xx.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Ed.YAMLMap=Sd;Ed.findPair=Ia});var pn=R(Gv=>{"use strict";var tR=U(),zv=Mr(),rR={collection:"map",default:!0,nodeClass:zv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return tR.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>zv.YAMLMap.from(e,t,r)};Gv.map=rR});var Vr=R(Jv=>{"use strict";var iR=Ea(),nR=kd(),aR=Js(),uc=U(),oR=we(),sR=Hr(),xd=class extends aR.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(uc.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=lc(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=lc(t);if(typeof i!="number")return;let n=this.items[i];return!r&&uc.isScalar(n)?n.value:n}has(t){let r=lc(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=lc(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];uc.isScalar(n)&&oR.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(sR.toJS(a,String(n++),r));return i}toString(t,r,i){return t?nR.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(iR.createNode(s,void 0,i))}}return a}};function lc(e){let t=uc.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Jv.YAMLSeq=xd});var fn=R(Kv=>{"use strict";var cR=U(),Uv=Vr(),lR={collection:"seq",default:!0,nodeClass:Uv.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return cR.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Uv.YAMLSeq.from(e,t,r)};Kv.seq=lR});var Ta=R(Yv=>{"use strict";var uR=Pa(),dR={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),uR.stringifyString(e,t,r,i)}};Yv.string=dR});var dc=R(Zv=>{"use strict";var Xv=we(),Qv={identify:e=>e==null,createNode:()=>new Xv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Xv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Qv.test.test(e)?e:t.options.nullStr};Zv.nullTag=Qv});var Rd=R(tg=>{"use strict";var pR=we(),eg={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new pR.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&eg.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};tg.boolTag=eg});var hn=R(rg=>{"use strict";function fR({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}rg.stringifyNumber=fR});var Pd=R(pc=>{"use strict";var hR=we(),Cd=hn(),mR={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Cd.stringifyNumber},vR={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Cd.stringifyNumber(e)}},gR={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new hR.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Cd.stringifyNumber};pc.float=gR;pc.floatExp=vR;pc.floatNaN=mR});var Ad=R(hc=>{"use strict";var ig=hn(),fc=e=>typeof e=="bigint"||Number.isInteger(e),_d=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function ng(e,t,r){let{value:i}=e;return fc(i)&&i>=0?r+i.toString(t):ig.stringifyNumber(e)}var wR={identify:e=>fc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>_d(e,2,8,r),stringify:e=>ng(e,8,"0o")},yR={identify:fc,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>_d(e,0,10,r),stringify:ig.stringifyNumber},bR={identify:e=>fc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>_d(e,2,16,r),stringify:e=>ng(e,16,"0x")};hc.int=yR;hc.intHex=bR;hc.intOct=wR});var og=R(ag=>{"use strict";var NR=pn(),kR=dc(),SR=fn(),ER=Ta(),xR=Rd(),Id=Pd(),Td=Ad(),RR=[NR.map,SR.seq,ER.string,kR.nullTag,xR.boolTag,Td.intOct,Td.int,Td.intHex,Id.floatNaN,Id.floatExp,Id.float];ag.schema=RR});var lg=R(cg=>{"use strict";var CR=we(),PR=pn(),_R=fn();function sg(e){return typeof e=="bigint"||Number.isInteger(e)}var mc=({value:e})=>JSON.stringify(e),AR=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:mc},{identify:e=>e==null,createNode:()=>new CR.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:mc},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:mc},{identify:sg,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>sg(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:mc}],IR={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},TR=[PR.map,_R.seq].concat(AR,IR);cg.schema=TR});var jd=R(ug=>{"use strict";var $a=Bs("buffer"),$d=we(),$R=Pa(),jR={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof $a.Buffer=="function")return $a.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof $a.Buffer=="function")s=o instanceof $a.Buffer?o.toString("base64"):$a.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=$d.Scalar.BLOCK_LITERAL),t!==$d.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let p=0,d=0;p<l;++p,d+=c)u[p]=s.substr(d,c);s=u.join(t===$d.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return $R.stringifyString({comment:e,type:t,value:s},i,n,a)}};ug.binary=jR});var wc=R(gc=>{"use strict";var vc=U(),Od=Fr(),OR=we(),HR=Vr();function dg(e,t){if(vc.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!vc.isPair(i)){if(vc.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new Od.Pair(new OR.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
56
56
  ${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comment=a.comment?`${i.comment}
57
- ${a.comment}`:i.comment}i=n}e.items[r]=As.isPair(i)?i:new Ju.Pair(i)}}else t("Expected a sequence for this tag");return e}function Km(e,t,r){let{replacer:i}=r,n=new $E.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Ju.createPair(s,c,r))}return n}var OE={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Um,createNode:Km};Is.createPairs=Km;Is.pairs=OE;Is.resolvePairs=Um});var Ku=R(Uu=>{"use strict";var Ym=G(),Gu=kr(),sa=Pr(),HE=_r(),Xm=Ts(),ai=class e extends HE.YAMLSeq{constructor(){super(),this.add=sa.YAMLMap.prototype.add.bind(this),this.delete=sa.YAMLMap.prototype.delete.bind(this),this.get=sa.YAMLMap.prototype.get.bind(this),this.has=sa.YAMLMap.prototype.has.bind(this),this.set=sa.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Ym.isPair(n)?(a=Gu.toJS(n.key,"",r),o=Gu.toJS(n.value,a,r)):a=Gu.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=Xm.createPairs(t,r,i),a=new this;return a.items=n.items,a}};ai.tag="tag:yaml.org,2002:omap";var DE={collection:"seq",identify:e=>e instanceof Map,nodeClass:ai,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Xm.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Ym.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new ai,r)},createNode:(e,t,r)=>ai.from(e,t,r)};Uu.YAMLOMap=ai;Uu.omap=DE});var rv=R(Yu=>{"use strict";var Qm=de();function Zm({value:e,source:t},r){return t&&(e?ev:tv).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var ev={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Qm.Scalar(!0),stringify:Zm},tv={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Qm.Scalar(!1),stringify:Zm};Yu.falseTag=tv;Yu.trueTag=ev});var iv=R(js=>{"use strict";var BE=de(),Xu=Wi(),LE={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Xu.stringifyNumber},qE={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Xu.stringifyNumber(e)}},FE={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new BE.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:Xu.stringifyNumber};js.float=FE;js.floatExp=qE;js.floatNaN=LE});var av=R(la=>{"use strict";var nv=Wi(),ca=e=>typeof e=="bigint"||Number.isInteger(e);function $s(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function Qu(e,t,r){let{value:i}=e;if(ca(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return nv.stringifyNumber(e)}var VE={identify:ca,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>$s(e,2,2,r),stringify:e=>Qu(e,2,"0b")},ME={identify:ca,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>$s(e,1,8,r),stringify:e=>Qu(e,8,"0")},WE={identify:ca,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>$s(e,0,10,r),stringify:nv.stringifyNumber},zE={identify:ca,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>$s(e,2,16,r),stringify:e=>Qu(e,16,"0x")};la.int=WE;la.intBin=VE;la.intHex=zE;la.intOct=ME});var ed=R(Zu=>{"use strict";var Ds=G(),Os=Cr(),Hs=Pr(),oi=class e extends Hs.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Ds.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Os.Pair(t.key,null):r=new Os.Pair(t,null),Hs.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Hs.findPair(this.items,t);return!r&&Ds.isPair(i)?Ds.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Hs.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Os.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Os.createPair(o,null,i));return a}};oi.tag="tag:yaml.org,2002:set";var JE={collection:"map",identify:e=>e instanceof Set,nodeClass:oi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>oi.from(e,t,r),resolve(e,t){if(Ds.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new oi,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Zu.YAMLSet=oi;Zu.set=JE});var rd=R(Bs=>{"use strict";var GE=Wi();function td(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function ov(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return GE.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var UE={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>td(e,r),stringify:ov},KE={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>td(e,!1),stringify:ov},sv={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(sv.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let f=td(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Bs.floatTime=KE;Bs.intTime=UE;Bs.timestamp=sv});var uv=R(lv=>{"use strict";var YE=Vi(),XE=xs(),QE=Mi(),ZE=aa(),ex=zu(),cv=rv(),id=iv(),Ls=av(),tx=gs(),rx=Ku(),ix=Ts(),nx=ed(),nd=rd(),ax=[YE.map,QE.seq,ZE.string,XE.nullTag,cv.trueTag,cv.falseTag,Ls.intBin,Ls.intOct,Ls.int,Ls.intHex,id.floatNaN,id.floatExp,id.float,ex.binary,tx.merge,rx.omap,ix.pairs,nx.set,nd.intTime,nd.floatTime,nd.timestamp];lv.schema=ax});var Nv=R(sd=>{"use strict";var hv=Vi(),ox=xs(),mv=Mi(),sx=aa(),cx=Du(),ad=Lu(),od=Fu(),lx=Mm(),ux=Jm(),vv=zu(),ua=gs(),gv=Ku(),wv=Ts(),dv=uv(),yv=ed(),qs=rd(),fv=new Map([["core",lx.schema],["failsafe",[hv.map,mv.seq,sx.string]],["json",ux.schema],["yaml11",dv.schema],["yaml-1.1",dv.schema]]),pv={binary:vv.binary,bool:cx.boolTag,float:ad.float,floatExp:ad.floatExp,floatNaN:ad.floatNaN,floatTime:qs.floatTime,int:od.int,intHex:od.intHex,intOct:od.intOct,intTime:qs.intTime,map:hv.map,merge:ua.merge,null:ox.nullTag,omap:gv.omap,pairs:wv.pairs,seq:mv.seq,set:yv.set,timestamp:qs.timestamp},dx={"tag:yaml.org,2002:binary":vv.binary,"tag:yaml.org,2002:merge":ua.merge,"tag:yaml.org,2002:omap":gv.omap,"tag:yaml.org,2002:pairs":wv.pairs,"tag:yaml.org,2002:set":yv.set,"tag:yaml.org,2002:timestamp":qs.timestamp};function fx(e,t,r){let i=fv.get(t);if(i&&!e)return r&&!i.includes(ua.merge)?i.concat(ua.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(fv.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(ua.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?pv[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(pv).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}sd.coreKnownTags=dx;sd.getTags=fx});var ud=R(bv=>{"use strict";var cd=G(),px=Vi(),hx=Mi(),mx=aa(),Fs=Nv(),vx=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,ld=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Fs.getTags(t,"compat"):t?Fs.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Fs.coreKnownTags:{},this.tags=Fs.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,cd.MAP,{value:px.map}),Object.defineProperty(this,cd.SCALAR,{value:mx.string}),Object.defineProperty(this,cd.SEQ,{value:hx.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?vx:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};bv.Schema=ld});var Sv=R(kv=>{"use strict";var gx=G(),dd=ra(),da=Qn();function wx(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=dd.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(da.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(gx.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(da.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=dd.stringify(e.contents,n,()=>s=null,c);s&&(l+=da.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(dd.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
- `)?(r.push("..."),r.push(da.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(da.indentComment(a(c),"")))}return r.join(`
57
+ ${a.comment}`:i.comment}i=n}e.items[r]=vc.isPair(i)?i:new Od.Pair(i)}}else t("Expected a sequence for this tag");return e}function pg(e,t,r){let{replacer:i}=r,n=new HR.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Od.createPair(s,c,r))}return n}var DR={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:dg,createNode:pg};gc.createPairs=pg;gc.pairs=DR;gc.resolvePairs=dg});var Bd=R(Dd=>{"use strict";var fg=U(),Hd=Hr(),ja=Mr(),BR=Vr(),hg=wc(),bi=class e extends BR.YAMLSeq{constructor(){super(),this.add=ja.YAMLMap.prototype.add.bind(this),this.delete=ja.YAMLMap.prototype.delete.bind(this),this.get=ja.YAMLMap.prototype.get.bind(this),this.has=ja.YAMLMap.prototype.has.bind(this),this.set=ja.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(fg.isPair(n)?(a=Hd.toJS(n.key,"",r),o=Hd.toJS(n.value,a,r)):a=Hd.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=hg.createPairs(t,r,i),a=new this;return a.items=n.items,a}};bi.tag="tag:yaml.org,2002:omap";var LR={collection:"seq",identify:e=>e instanceof Map,nodeClass:bi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=hg.resolvePairs(e,t),i=[];for(let{key:n}of r.items)fg.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new bi,r)},createNode:(e,t,r)=>bi.from(e,t,r)};Dd.YAMLOMap=bi;Dd.omap=LR});var yg=R(Ld=>{"use strict";var mg=we();function vg({value:e,source:t},r){return t&&(e?gg:wg).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var gg={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new mg.Scalar(!0),stringify:vg},wg={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new mg.Scalar(!1),stringify:vg};Ld.falseTag=wg;Ld.trueTag=gg});var bg=R(yc=>{"use strict";var FR=we(),Fd=hn(),qR={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Fd.stringifyNumber},MR={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Fd.stringifyNumber(e)}},VR={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new FR.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:Fd.stringifyNumber};yc.float=VR;yc.floatExp=MR;yc.floatNaN=qR});var kg=R(Ha=>{"use strict";var Ng=hn(),Oa=e=>typeof e=="bigint"||Number.isInteger(e);function bc(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function qd(e,t,r){let{value:i}=e;if(Oa(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Ng.stringifyNumber(e)}var WR={identify:Oa,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>bc(e,2,2,r),stringify:e=>qd(e,2,"0b")},zR={identify:Oa,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>bc(e,1,8,r),stringify:e=>qd(e,8,"0")},GR={identify:Oa,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>bc(e,0,10,r),stringify:Ng.stringifyNumber},JR={identify:Oa,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>bc(e,2,16,r),stringify:e=>qd(e,16,"0x")};Ha.int=GR;Ha.intBin=WR;Ha.intHex=JR;Ha.intOct=zR});var Vd=R(Md=>{"use strict";var Sc=U(),Nc=Fr(),kc=Mr(),Ni=class e extends kc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Sc.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Nc.Pair(t.key,null):r=new Nc.Pair(t,null),kc.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=kc.findPair(this.items,t);return!r&&Sc.isPair(i)?Sc.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=kc.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Nc.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Nc.createPair(o,null,i));return a}};Ni.tag="tag:yaml.org,2002:set";var UR={collection:"map",identify:e=>e instanceof Set,nodeClass:Ni,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Ni.from(e,t,r),resolve(e,t){if(Sc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Ni,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Md.YAMLSet=Ni;Md.set=UR});var zd=R(Ec=>{"use strict";var KR=hn();function Wd(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function Sg(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return KR.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var YR={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>Wd(e,r),stringify:Sg},XR={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>Wd(e,!1),stringify:Sg},Eg={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(Eg.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let p=Wd(u,!1);Math.abs(p)<30&&(p*=60),l-=6e4*p}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Ec.floatTime=XR;Ec.intTime=YR;Ec.timestamp=Eg});var Cg=R(Rg=>{"use strict";var QR=pn(),ZR=dc(),eC=fn(),tC=Ta(),rC=jd(),xg=yg(),Gd=bg(),xc=kg(),iC=ic(),nC=Bd(),aC=wc(),oC=Vd(),Jd=zd(),sC=[QR.map,eC.seq,tC.string,ZR.nullTag,xg.trueTag,xg.falseTag,xc.intBin,xc.intOct,xc.int,xc.intHex,Gd.floatNaN,Gd.floatExp,Gd.float,rC.binary,iC.merge,nC.omap,aC.pairs,oC.set,Jd.intTime,Jd.floatTime,Jd.timestamp];Rg.schema=sC});var Dg=R(Yd=>{"use strict";var Ig=pn(),cC=dc(),Tg=fn(),lC=Ta(),uC=Rd(),Ud=Pd(),Kd=Ad(),dC=og(),pC=lg(),$g=jd(),Da=ic(),jg=Bd(),Og=wc(),Pg=Cg(),Hg=Vd(),Rc=zd(),_g=new Map([["core",dC.schema],["failsafe",[Ig.map,Tg.seq,lC.string]],["json",pC.schema],["yaml11",Pg.schema],["yaml-1.1",Pg.schema]]),Ag={binary:$g.binary,bool:uC.boolTag,float:Ud.float,floatExp:Ud.floatExp,floatNaN:Ud.floatNaN,floatTime:Rc.floatTime,int:Kd.int,intHex:Kd.intHex,intOct:Kd.intOct,intTime:Rc.intTime,map:Ig.map,merge:Da.merge,null:cC.nullTag,omap:jg.omap,pairs:Og.pairs,seq:Tg.seq,set:Hg.set,timestamp:Rc.timestamp},fC={"tag:yaml.org,2002:binary":$g.binary,"tag:yaml.org,2002:merge":Da.merge,"tag:yaml.org,2002:omap":jg.omap,"tag:yaml.org,2002:pairs":Og.pairs,"tag:yaml.org,2002:set":Hg.set,"tag:yaml.org,2002:timestamp":Rc.timestamp};function hC(e,t,r){let i=_g.get(t);if(i&&!e)return r&&!i.includes(Da.merge)?i.concat(Da.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(_g.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(Da.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Ag[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Ag).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Yd.coreKnownTags=fC;Yd.getTags=hC});var Zd=R(Bg=>{"use strict";var Xd=U(),mC=pn(),vC=fn(),gC=Ta(),Cc=Dg(),wC=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Qd=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Cc.getTags(t,"compat"):t?Cc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Cc.coreKnownTags:{},this.tags=Cc.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Xd.MAP,{value:mC.map}),Object.defineProperty(this,Xd.SCALAR,{value:gC.string}),Object.defineProperty(this,Xd.SEQ,{value:vC.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?wC:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Bg.Schema=Qd});var Fg=R(Lg=>{"use strict";var yC=U(),ep=_a(),Ba=xa();function bC(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=ep.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Ba.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(yC.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(Ba.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=ep.stringify(e.contents,n,()=>s=null,c);s&&(l+=Ba.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(ep.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
+ `)?(r.push("..."),r.push(Ba.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(Ba.indentComment(a(c),"")))}return r.join(`
59
59
  `)+`
60
- `}kv.stringifyDocument=wx});var fa=R(Ev=>{"use strict";var yx=Yn(),zi=ss(),tt=G(),Nx=Cr(),bx=kr(),kx=ud(),Sx=Sv(),fd=is(),Ex=vu(),xx=Xn(),pd=mu(),hd=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,tt.NODE_TYPE,{value:tt.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new pd.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[tt.NODE_TYPE]:{value:tt.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=tt.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Ji(this.contents)&&this.contents.add(t)}addIn(t,r){Ji(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=fd.anchorNames(this);t.anchor=!r||i.has(r)?fd.findNewAnchor(r||"a",i):r}return new yx.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let g=w=>typeof w=="number"||w instanceof String||w instanceof Number,v=r.filter(g).map(String);v.length>0&&(r=r.concat(v)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=i??{},{onAnchor:f,setAnchors:d,sourceObjects:p}=fd.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},h=xx.createNode(t,u,m);return s&&tt.isCollection(h)&&(h.flow=!0),d(),h}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new Nx.Pair(n,a)}delete(t){return Ji(this.contents)?this.contents.delete(t):!1}deleteIn(t){return zi.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Ji(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return tt.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return zi.isEmptyPath(t)?!r&&tt.isScalar(this.contents)?this.contents.value:this.contents:tt.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return tt.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return zi.isEmptyPath(t)?this.contents!==void 0:tt.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=zi.collectionFromPath(this.schema,[t],r):Ji(this.contents)&&this.contents.set(t,r)}setIn(t,r){zi.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=zi.collectionFromPath(this.schema,Array.from(t),r):Ji(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new pd.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new pd.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new kx.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=bx.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?Ex.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return Sx.stringifyDocument(this,t)}};function Ji(e){if(tt.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Ev.Document=hd});var ma=R(ha=>{"use strict";var pa=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},md=class extends pa{constructor(t,r,i){super("YAMLParseError",t,r,i)}},vd=class extends pa{constructor(t,r,i){super("YAMLWarning",t,r,i)}},Cx=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
60
+ `}Lg.stringifyDocument=bC});var La=R(qg=>{"use strict";var NC=Sa(),mn=Js(),ft=U(),kC=Fr(),SC=Hr(),EC=Zd(),xC=Fg(),tp=Vs(),RC=ad(),CC=Ea(),rp=nd(),ip=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ft.NODE_TYPE,{value:ft.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new rp.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[ft.NODE_TYPE]:{value:ft.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=ft.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){vn(this.contents)&&this.contents.add(t)}addIn(t,r){vn(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=tp.anchorNames(this);t.anchor=!r||i.has(r)?tp.findNewAnchor(r||"a",i):r}return new NC.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let v=w=>typeof w=="number"||w instanceof String||w instanceof Number,g=r.filter(v).map(String);g.length>0&&(r=r.concat(g)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=i??{},{onAnchor:p,setAnchors:d,sourceObjects:f}=tp.createNodeAnchors(this,o||"a"),h={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:p,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:f},m=CC.createNode(t,u,h);return s&&ft.isCollection(m)&&(m.flow=!0),d(),m}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new kC.Pair(n,a)}delete(t){return vn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return mn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):vn(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return ft.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return mn.isEmptyPath(t)?!r&&ft.isScalar(this.contents)?this.contents.value:this.contents:ft.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return ft.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return mn.isEmptyPath(t)?this.contents!==void 0:ft.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=mn.collectionFromPath(this.schema,[t],r):vn(this.contents)&&this.contents.set(t,r)}setIn(t,r){mn.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=mn.collectionFromPath(this.schema,Array.from(t),r):vn(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new rp.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new rp.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new EC.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=SC.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?RC.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return xC.stringifyDocument(this,t)}};function vn(e){if(ft.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}qg.Document=ip});var Ma=R(qa=>{"use strict";var Fa=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},np=class extends Fa{constructor(t,r,i){super("YAMLParseError",t,r,i)}},ap=class extends Fa{constructor(t,r,i){super("YAMLWarning",t,r,i)}},PC=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
61
61
  `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
62
62
 
63
63
  ${o}
64
64
  ${l}
65
- `}};ha.YAMLError=pa;ha.YAMLParseError=md;ha.YAMLWarning=vd;ha.prettifyError=Cx});var va=R(xv=>{"use strict";function Rx(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,f="",d="",p=!1,m=!1,h=null,g=null,v=null,w=null,y=null,b=null,S=null;for(let k of e)switch(m&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&a(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&k.type!=="comment"&&k.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),k.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&k.source.includes(" ")&&(h=k),u=!0;break;case"comment":{u||a(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let E=k.source.substring(1)||" ";f?f+=d+E:f=E,d="",l=!1;break}case"newline":l?f?f+=k.source:(!b||r!=="seq-item-ind")&&(c=!0):d+=k.source,l=!0,p=!0,(g||v)&&(w=k),u=!0;break;case"anchor":g&&a(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&a(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=k,S??(S=k.offset),l=!1,u=!1,m=!0;break;case"tag":{v&&a(k,"MULTIPLE_TAGS","A node can have at most one tag"),v=k,S??(S=k.offset),l=!1,u=!1,m=!0;break}case r:(g||v)&&a(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),b&&a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${t??"collection"}`),b=k,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){y&&a(k,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=k,l=!1,u=!1;break}default:a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),l=!1,u=!1}let N=e[e.length-1],x=N?N.offset+N.source.length:n;return m&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:y,found:b,spaceBefore:c,comment:f,hasNewline:p,anchor:g,tag:v,newlineAfterProp:w,end:x,start:S??x}}xv.resolveProps=Rx});var Vs=R(Cv=>{"use strict";function gd(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
66
- `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(gd(t.key)||gd(t.value))return!0}return!1;default:return!0}}Cv.containsNewline=gd});var wd=R(Rv=>{"use strict";var Px=Vs();function _x(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&Px.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Rv.flowIndentCheck=_x});var yd=R(_v=>{"use strict";var Pv=G();function Ax(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Pv.isScalar(a)&&Pv.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}_v.mapIncludes=Ax});var Ov=R($v=>{"use strict";var Av=Cr(),Ix=Pr(),Iv=va(),Tx=Vs(),Tv=wd(),jx=yd(),jv="All mapping items must start at the same column";function $x({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??Ix.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let u of i.items){let{start:f,key:d,sep:p,value:m}=u,h=Iv.resolveProps(f,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),g=!h.found;if(g){if(d&&(d.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&n(c,"BAD_INDENT",jv)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
67
- `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||Tx.containsNewline(d))&&n(d??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&n(c,"BAD_INDENT",jv);r.atKey=!0;let v=h.end,w=d?e(r,d,h,n):t(r,v,f,null,h,n);r.schema.compat&&Tv.flowIndentCheck(i.indent,d,n),r.atKey=!1,jx.mapIncludes(r,s.items,w)&&n(v,"DUPLICATE_KEY","Map keys must be unique");let y=Iv.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:w.range[2],onError:n,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=y.end,y.found){g&&(m?.type==="block-map"&&!y.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<y.found.offset-1024&&n(w.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let b=m?e(r,m,y,n):t(r,c,p,null,y,n);r.schema.compat&&Tv.flowIndentCheck(i.indent,m,n),c=b.range[2];let S=new Av.Pair(w,b);r.options.keepSourceTokens&&(S.srcToken=u),s.items.push(S)}else{g&&n(w.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(w.comment?w.comment+=`
68
- `+y.comment:w.comment=y.comment);let b=new Av.Pair(w);r.options.keepSourceTokens&&(b.srcToken=u),s.items.push(b)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}$v.resolveBlockMap=$x});var Dv=R(Hv=>{"use strict";var Ox=_r(),Hx=va(),Dx=wd();function Bx({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??Ox.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:u,value:f}of i.items){let d=Hx.resolveProps(u,{indicator:"seq-item-ind",next:f,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||f)f?.type==="block-seq"?n(d.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let p=f?e(r,f,d,n):t(r,d.end,u,null,d,n);r.schema.compat&&Dx.flowIndentCheck(i.indent,f,n),c=p.range[2],s.items.push(p)}return s.range=[i.offset,c,l??c],s}Hv.resolveBlockSeq=Bx});var Gi=R(Bv=>{"use strict";function Lx(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Bv.resolveEnd=Lx});var Vv=R(Fv=>{"use strict";var qx=G(),Fx=Cr(),Lv=Pr(),Vx=_r(),Mx=Gi(),qv=va(),Wx=Vs(),zx=yd(),Nd="Block collections are not allowed within flow collections",bd=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Jx({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Lv.YAMLMap:Vx.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let f=i.offset+i.start.source.length;for(let g=0;g<i.items.length;++g){let v=i.items[g],{start:w,key:y,sep:b,value:S}=v,N=qv.resolveProps(w,{flow:s,indicator:"explicit-key-ind",next:y??b?.[0],offset:f,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!N.found){if(!N.anchor&&!N.tag&&!b&&!S){g===0&&N.comma?n(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):g<i.items.length-1&&n(N.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),N.comment&&(l.comment?l.comment+=`
69
- `+N.comment:l.comment=N.comment),f=N.end;continue}!o&&r.options.strict&&Wx.containsNewline(y)&&n(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)N.comma&&n(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(N.comma||n(N.start,"MISSING_CHAR",`Missing , between ${s} items`),N.comment){let x="";e:for(let k of w)switch(k.type){case"comma":case"space":break;case"comment":x=k.source.substring(1);break e;default:break e}if(x){let k=l.items[l.items.length-1];qx.isPair(k)&&(k=k.value??k.key),k.comment?k.comment+=`
70
- `+x:k.comment=x,N.comment=N.comment.substring(x.length+1)}}if(!o&&!b&&!N.found){let x=S?e(r,S,N,n):t(r,N.end,b,null,N,n);l.items.push(x),f=x.range[2],bd(S)&&n(x.range,"BLOCK_IN_FLOW",Nd)}else{r.atKey=!0;let x=N.end,k=y?e(r,y,N,n):t(r,x,w,null,N,n);bd(y)&&n(k.range,"BLOCK_IN_FLOW",Nd),r.atKey=!1;let E=qv.resolveProps(b??[],{flow:s,indicator:"map-value-ind",next:S,offset:k.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(E.found){if(!o&&!N.found&&r.options.strict){if(b)for(let P of b){if(P===E.found)break;if(P.type==="newline"){n(P,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}N.start<E.found.offset-1024&&n(E.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?n(S,"MISSING_CHAR",`Missing space after : in ${s}`):n(E.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let C=S?e(r,S,E,n):E.found?t(r,E.end,b,null,E,n):null;C?bd(S)&&n(C.range,"BLOCK_IN_FLOW",Nd):E.comment&&(k.comment?k.comment+=`
71
- `+E.comment:k.comment=E.comment);let H=new Fx.Pair(k,C);if(r.options.keepSourceTokens&&(H.srcToken=v),o){let P=l;zx.mapIncludes(r,P.items,k)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),P.items.push(H)}else{let P=new Lv.YAMLMap(r.schema);P.flow=!0,P.items.push(H);let W=(C??k).range;P.range=[k.range[0],W[1],W[2]],l.items.push(P)}f=C?C.range[2]:E.end}}let d=o?"}":"]",[p,...m]=i.end,h=f;if(p?.source===d)h=p.offset+p.source.length;else{let g=s[0].toUpperCase()+s.substring(1),v=u?`${g} must end with a ${d}`:`${g} in block collection must be sufficiently indented and end with a ${d}`;n(f,u?"MISSING_CHAR":"BAD_INDENT",v),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let g=Mx.resolveEnd(m,h,r.options.strict,n);g.comment&&(l.comment?l.comment+=`
72
- `+g.comment:l.comment=g.comment),l.range=[i.offset,h,g.offset]}else l.range=[i.offset,h,h];return l}Fv.resolveFlowCollection=Jx});var Wv=R(Mv=>{"use strict";var Gx=G(),Ux=de(),Kx=Pr(),Yx=_r(),Xx=Ov(),Qx=Dv(),Zx=Vv();function kd(e,t,r,i,n,a){let o=r.type==="block-map"?Xx.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?Qx.resolveBlockSeq(e,t,r,i,a):Zx.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function eC(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,d=>n(a,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=i,m=d&&a?d.offset>a.offset?d:a:d??a;m&&(!p||p.offset<m.offset)&&n(m,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===Kx.YAMLMap.tagName&&s==="map"||o===Yx.YAMLSeq.tagName&&s==="seq")return kd(e,t,r,n,o);let c=t.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=t.schema.knownTags[o];if(d?.collection===s)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?n(a,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),kd(e,t,r,n,o)}let l=kd(e,t,r,n,o,c),u=c.resolve?.(l,d=>n(a,"TAG_RESOLVE_FAILED",d),t.options)??l,f=Gx.isNode(u)?u:new Ux.Scalar(u);return f.range=l.range,f.tag=o,c?.format&&(f.format=c.format),f}Mv.composeCollection=eC});var Ed=R(zv=>{"use strict";var Sd=de();function tC(e,t,r){let i=t.offset,n=rC(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Sd.Scalar.BLOCK_FOLDED:Sd.Scalar.BLOCK_LITERAL,o=t.source?iC(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let g=o[h][1];if(g===""||g==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
73
- `.repeat(Math.max(1,o.length-1)):"",g=i+n.length;return t.source&&(g+=t.source.length),{value:h,type:a,comment:n.comment,range:[i,g,g]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let h=0;h<s;++h){let[g,v]=o[h];if(v===""||v==="\r")n.indent===0&&g.length>c&&(c=g.length);else{g.length<c&&r(l+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=g.length),u=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=g.length+v.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let f="",d="",p=!1;for(let h=0;h<u;++h)f+=o[h][0].slice(c)+`
74
- `;for(let h=u;h<s;++h){let[g,v]=o[h];l+=g.length+v.length+1;let w=v[v.length-1]==="\r";if(w&&(v=v.slice(0,-1)),v&&g.length<c){let b=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-v.length-(w?2:1),"BAD_INDENT",b),g=""}a===Sd.Scalar.BLOCK_LITERAL?(f+=d+g.slice(c)+v,d=`
75
- `):g.length>c||v[0]===" "?(d===" "?d=`
76
- `:!p&&d===`
65
+ `}};qa.YAMLError=Fa;qa.YAMLParseError=np;qa.YAMLWarning=ap;qa.prettifyError=PC});var Va=R(Mg=>{"use strict";function _C(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,p="",d="",f=!1,h=!1,m=null,v=null,g=null,w=null,N=null,y=null,E=null;for(let k of e)switch(h&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&a(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h=!1),m&&(l&&k.type!=="comment"&&k.type!=="newline"&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),k.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&k.source.includes(" ")&&(m=k),u=!0;break;case"comment":{u||a(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let S=k.source.substring(1)||" ";p?p+=d+S:p=S,d="",l=!1;break}case"newline":l?p?p+=k.source:(!y||r!=="seq-item-ind")&&(c=!0):d+=k.source,l=!0,f=!0,(v||g)&&(w=k),u=!0;break;case"anchor":v&&a(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&a(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=k,E??(E=k.offset),l=!1,u=!1,h=!0;break;case"tag":{g&&a(k,"MULTIPLE_TAGS","A node can have at most one tag"),g=k,E??(E=k.offset),l=!1,u=!1,h=!0;break}case r:(v||g)&&a(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),y&&a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${t??"collection"}`),y=k,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){N&&a(k,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=k,l=!1,u=!1;break}default:a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),l=!1,u=!1}let b=e[e.length-1],x=b?b.offset+b.source.length:n;return h&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:N,found:y,spaceBefore:c,comment:p,hasNewline:f,anchor:v,tag:g,newlineAfterProp:w,end:x,start:E??x}}Mg.resolveProps=_C});var Pc=R(Vg=>{"use strict";function op(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
66
+ `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(op(t.key)||op(t.value))return!0}return!1;default:return!0}}Vg.containsNewline=op});var sp=R(Wg=>{"use strict";var AC=Pc();function IC(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&AC.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Wg.flowIndentCheck=IC});var cp=R(Gg=>{"use strict";var zg=U();function TC(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||zg.isScalar(a)&&zg.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}Gg.mapIncludes=TC});var Qg=R(Xg=>{"use strict";var Jg=Fr(),$C=Mr(),Ug=Va(),jC=Pc(),Kg=sp(),OC=cp(),Yg="All mapping items must start at the same column";function HC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??$C.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let u of i.items){let{start:p,key:d,sep:f,value:h}=u,m=Ug.resolveProps(p,{indicator:"explicit-key-ind",next:d??f?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),v=!m.found;if(v){if(d&&(d.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&n(c,"BAD_INDENT",Yg)),!m.anchor&&!m.tag&&!f){l=m.end,m.comment&&(s.comment?s.comment+=`
67
+ `+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||jC.containsNewline(d))&&n(d??p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==i.indent&&n(c,"BAD_INDENT",Yg);r.atKey=!0;let g=m.end,w=d?e(r,d,m,n):t(r,g,p,null,m,n);r.schema.compat&&Kg.flowIndentCheck(i.indent,d,n),r.atKey=!1,OC.mapIncludes(r,s.items,w)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let N=Ug.resolveProps(f??[],{indicator:"map-value-ind",next:h,offset:w.range[2],onError:n,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=N.end,N.found){v&&(h?.type==="block-map"&&!N.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&m.start<N.found.offset-1024&&n(w.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let y=h?e(r,h,N,n):t(r,c,f,null,N,n);r.schema.compat&&Kg.flowIndentCheck(i.indent,h,n),c=y.range[2];let E=new Jg.Pair(w,y);r.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{v&&n(w.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),N.comment&&(w.comment?w.comment+=`
68
+ `+N.comment:w.comment=N.comment);let y=new Jg.Pair(w);r.options.keepSourceTokens&&(y.srcToken=u),s.items.push(y)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}Xg.resolveBlockMap=HC});var ew=R(Zg=>{"use strict";var DC=Vr(),BC=Va(),LC=sp();function FC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??DC.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:u,value:p}of i.items){let d=BC.resolveProps(u,{indicator:"seq-item-ind",next:p,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||p)p?.type==="block-seq"?n(d.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let f=p?e(r,p,d,n):t(r,d.end,u,null,d,n);r.schema.compat&&LC.flowIndentCheck(i.indent,p,n),c=f.range[2],s.items.push(f)}return s.range=[i.offset,c,l??c],s}Zg.resolveBlockSeq=FC});var gn=R(tw=>{"use strict";function qC(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}tw.resolveEnd=qC});var aw=R(nw=>{"use strict";var MC=U(),VC=Fr(),rw=Mr(),WC=Vr(),zC=gn(),iw=Va(),GC=Pc(),JC=cp(),lp="Block collections are not allowed within flow collections",up=e=>e&&(e.type==="block-map"||e.type==="block-seq");function UC({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?rw.YAMLMap:WC.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let p=i.offset+i.start.source.length;for(let v=0;v<i.items.length;++v){let g=i.items[v],{start:w,key:N,sep:y,value:E}=g,b=iw.resolveProps(w,{flow:s,indicator:"explicit-key-ind",next:N??y?.[0],offset:p,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!b.found){if(!b.anchor&&!b.tag&&!y&&!E){v===0&&b.comma?n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<i.items.length-1&&n(b.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),b.comment&&(l.comment?l.comment+=`
69
+ `+b.comment:l.comment=b.comment),p=b.end;continue}!o&&r.options.strict&&GC.containsNewline(N)&&n(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)b.comma&&n(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(b.comma||n(b.start,"MISSING_CHAR",`Missing , between ${s} items`),b.comment){let x="";e:for(let k of w)switch(k.type){case"comma":case"space":break;case"comment":x=k.source.substring(1);break e;default:break e}if(x){let k=l.items[l.items.length-1];MC.isPair(k)&&(k=k.value??k.key),k.comment?k.comment+=`
70
+ `+x:k.comment=x,b.comment=b.comment.substring(x.length+1)}}if(!o&&!y&&!b.found){let x=E?e(r,E,b,n):t(r,b.end,y,null,b,n);l.items.push(x),p=x.range[2],up(E)&&n(x.range,"BLOCK_IN_FLOW",lp)}else{r.atKey=!0;let x=b.end,k=N?e(r,N,b,n):t(r,x,w,null,b,n);up(N)&&n(k.range,"BLOCK_IN_FLOW",lp),r.atKey=!1;let S=iw.resolveProps(y??[],{flow:s,indicator:"map-value-ind",next:E,offset:k.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(S.found){if(!o&&!b.found&&r.options.strict){if(y)for(let _ of y){if(_===S.found)break;if(_.type==="newline"){n(_,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}b.start<S.found.offset-1024&&n(S.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?n(E,"MISSING_CHAR",`Missing space after : in ${s}`):n(S.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let C=E?e(r,E,S,n):S.found?t(r,S.end,y,null,S,n):null;C?up(E)&&n(C.range,"BLOCK_IN_FLOW",lp):S.comment&&(k.comment?k.comment+=`
71
+ `+S.comment:k.comment=S.comment);let P=new VC.Pair(k,C);if(r.options.keepSourceTokens&&(P.srcToken=g),o){let _=l;JC.mapIncludes(r,_.items,k)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),_.items.push(P)}else{let _=new rw.YAMLMap(r.schema);_.flow=!0,_.items.push(P);let j=(C??k).range;_.range=[k.range[0],j[1],j[2]],l.items.push(_)}p=C?C.range[2]:S.end}}let d=o?"}":"]",[f,...h]=i.end,m=p;if(f?.source===d)m=f.offset+f.source.length;else{let v=s[0].toUpperCase()+s.substring(1),g=u?`${v} must end with a ${d}`:`${v} in block collection must be sufficiently indented and end with a ${d}`;n(p,u?"MISSING_CHAR":"BAD_INDENT",g),f&&f.source.length!==1&&h.unshift(f)}if(h.length>0){let v=zC.resolveEnd(h,m,r.options.strict,n);v.comment&&(l.comment?l.comment+=`
72
+ `+v.comment:l.comment=v.comment),l.range=[i.offset,m,v.offset]}else l.range=[i.offset,m,m];return l}nw.resolveFlowCollection=UC});var sw=R(ow=>{"use strict";var KC=U(),YC=we(),XC=Mr(),QC=Vr(),ZC=Qg(),eP=ew(),tP=aw();function dp(e,t,r,i,n,a){let o=r.type==="block-map"?ZC.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?eP.resolveBlockSeq(e,t,r,i,a):tP.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function rP(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,d=>n(a,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:f}=i,h=d&&a?d.offset>a.offset?d:a:d??a;h&&(!f||f.offset<h.offset)&&n(h,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===XC.YAMLMap.tagName&&s==="map"||o===QC.YAMLSeq.tagName&&s==="seq")return dp(e,t,r,n,o);let c=t.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=t.schema.knownTags[o];if(d?.collection===s)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?n(a,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),dp(e,t,r,n,o)}let l=dp(e,t,r,n,o,c),u=c.resolve?.(l,d=>n(a,"TAG_RESOLVE_FAILED",d),t.options)??l,p=KC.isNode(u)?u:new YC.Scalar(u);return p.range=l.range,p.tag=o,c?.format&&(p.format=c.format),p}ow.composeCollection=rP});var fp=R(cw=>{"use strict";var pp=we();function iP(e,t,r){let i=t.offset,n=nP(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?pp.Scalar.BLOCK_FOLDED:pp.Scalar.BLOCK_LITERAL,o=t.source?aP(t.source):[],s=o.length;for(let m=o.length-1;m>=0;--m){let v=o[m][1];if(v===""||v==="\r")s=m;else break}if(s===0){let m=n.chomp==="+"&&o.length>0?`
73
+ `.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return t.source&&(v+=t.source.length),{value:m,type:a,comment:n.comment,range:[i,v,v]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let m=0;m<s;++m){let[v,g]=o[m];if(g===""||g==="\r")n.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&r(l+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=v.length),u=m,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+g.length+1}for(let m=o.length-1;m>=s;--m)o[m][0].length>c&&(s=m+1);let p="",d="",f=!1;for(let m=0;m<u;++m)p+=o[m][0].slice(c)+`
74
+ `;for(let m=u;m<s;++m){let[v,g]=o[m];l+=v.length+g.length+1;let w=g[g.length-1]==="\r";if(w&&(g=g.slice(0,-1)),g&&v.length<c){let y=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-g.length-(w?2:1),"BAD_INDENT",y),v=""}a===pp.Scalar.BLOCK_LITERAL?(p+=d+v.slice(c)+g,d=`
75
+ `):v.length>c||g[0]===" "?(d===" "?d=`
76
+ `:!f&&d===`
77
77
  `&&(d=`
78
78
 
79
- `),f+=d+g.slice(c)+v,d=`
80
- `,p=!0):v===""?d===`
81
- `?f+=`
79
+ `),p+=d+v.slice(c)+g,d=`
80
+ `,f=!0):g===""?d===`
81
+ `?p+=`
82
82
  `:d=`
83
- `:(f+=d+v,d=" ",p=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)f+=`
84
- `+o[h][0].slice(c);f[f.length-1]!==`
85
- `&&(f+=`
86
- `);break;default:f+=`
87
- `}let m=i+n.length+t.source.length;return{value:f,type:a,comment:n.comment,range:[i,m,m]}}function rC({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let d=1;d<n.length;++d){let p=n[d];if(!s&&(p==="-"||p==="+"))s=p;else{let m=Number(p);!o&&m?o=m:c===-1&&(c=e+d)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",f=n.length;for(let d=1;d<t.length;++d){let p=t[d];switch(p.type){case"space":l=!0;case"newline":f+=p.source.length;break;case"comment":r&&!l&&i(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=p.source.length,u=p.source.substring(1);break;case"error":i(p,"UNEXPECTED_TOKEN",p.message),f+=p.source.length;break;default:{let m=`Unexpected token in block scalar header: ${p.type}`;i(p,"UNEXPECTED_TOKEN",m);let h=p.source;h&&typeof h=="string"&&(f+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:f}}function iC(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}zv.resolveBlockScalar=tC});var Cd=R(Gv=>{"use strict";var xd=de(),nC=Gi();function aC(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(d,p,m)=>r(i+d,p,m);switch(n){case"scalar":s=xd.Scalar.PLAIN,c=oC(a,l);break;case"single-quoted-scalar":s=xd.Scalar.QUOTE_SINGLE,c=sC(a,l);break;case"double-quoted-scalar":s=xd.Scalar.QUOTE_DOUBLE,c=cC(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let u=i+a.length,f=nC.resolveEnd(o,u,t,r);return{value:c,type:s,comment:f.comment,range:[i,u,f.offset]}}function oC(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),Jv(e)}function sC(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Jv(e.slice(1,-1)).replace(/''/g,"'")}function Jv(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
83
+ `:(p+=d+g,d=" ",f=!1)}switch(n.chomp){case"-":break;case"+":for(let m=s;m<o.length;++m)p+=`
84
+ `+o[m][0].slice(c);p[p.length-1]!==`
85
+ `&&(p+=`
86
+ `);break;default:p+=`
87
+ `}let h=i+n.length+t.source.length;return{value:p,type:a,comment:n.comment,range:[i,h,h]}}function nP({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let d=1;d<n.length;++d){let f=n[d];if(!s&&(f==="-"||f==="+"))s=f;else{let h=Number(f);!o&&h?o=h:c===-1&&(c=e+d)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",p=n.length;for(let d=1;d<t.length;++d){let f=t[d];switch(f.type){case"space":l=!0;case"newline":p+=f.source.length;break;case"comment":r&&!l&&i(f,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),p+=f.source.length,u=f.source.substring(1);break;case"error":i(f,"UNEXPECTED_TOKEN",f.message),p+=f.source.length;break;default:{let h=`Unexpected token in block scalar header: ${f.type}`;i(f,"UNEXPECTED_TOKEN",h);let m=f.source;m&&typeof m=="string"&&(p+=m.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:p}}function aP(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}cw.resolveBlockScalar=iP});var mp=R(uw=>{"use strict";var hp=we(),oP=gn();function sP(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(d,f,h)=>r(i+d,f,h);switch(n){case"scalar":s=hp.Scalar.PLAIN,c=cP(a,l);break;case"single-quoted-scalar":s=hp.Scalar.QUOTE_SINGLE,c=lP(a,l);break;case"double-quoted-scalar":s=hp.Scalar.QUOTE_DOUBLE,c=uP(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let u=i+a.length,p=oP.resolveEnd(o,u,t,r);return{value:c,type:s,comment:p.comment,range:[i,u,p.offset]}}function cP(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),lw(e)}function lP(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),lw(e.slice(1,-1)).replace(/''/g,"'")}function lw(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
88
  `,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
89
89
  `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=t.exec(e);if(!i)return e;let n=i[1],a=" ",o=t.lastIndex;for(r.lastIndex=o;i=r.exec(e);)i[1]===""?a===`
90
90
  `?n+=a:a=`
91
- `:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function cC(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
91
+ `:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function uP(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
92
92
  `))if(n===`
93
- `){let{fold:a,offset:o}=lC(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=uC[a];if(o)r+=o;else if(a===`
93
+ `){let{fold:a,offset:o}=dP(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=pP[a];if(o)r+=o;else if(a===`
94
94
  `)for(a=e[i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="\r"&&e[i+1]===`
95
- `)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=dC(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
95
+ `)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=fP(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
96
96
  `&&!(o==="\r"&&e[i+2]===`
97
- `)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function lC(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
97
+ `)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function dP(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
98
98
  `||i==="\r")&&!(i==="\r"&&e[t+2]!==`
99
99
  `);)i===`
100
100
  `&&(r+=`
101
- `),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var uC={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function dC(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Gv.resolveFlowScalar=aC});var Yv=R(Kv=>{"use strict";var si=G(),Uv=de(),fC=Ed(),pC=Cd();function hC(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?fC.resolveBlockScalar(e,t,i):pC.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,f=>i(r,"TAG_RESOLVE_FAILED",f)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[si.SCALAR]:c?l=mC(e.schema,n,c,r,i):t.type==="scalar"?l=vC(e,n,t,i):l=e.schema[si.SCALAR];let u;try{let f=l.resolve(n,d=>i(r??t,"TAG_RESOLVE_FAILED",d),e.options);u=si.isScalar(f)?f:new Uv.Scalar(f)}catch(f){let d=f instanceof Error?f.message:String(f);i(r??t,"TAG_RESOLVE_FAILED",d),u=new Uv.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function mC(e,t,r,i,n){if(r==="!")return e[si.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[si.SCALAR])}function vC({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[si.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[si.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}Kv.composeScalar=hC});var Qv=R(Xv=>{"use strict";function gC(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}Xv.emptyScalarPosition=gC});var tg=R(Pd=>{"use strict";var wC=Yn(),yC=G(),NC=Wv(),Zv=Yv(),bC=Gi(),kC=Qv(),SC={composeNode:eg,composeEmptyNode:Rd};function eg(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(t.type){case"alias":l=EC(e,t,i),(s||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Zv.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=NC.composeCollection(SC,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(f){let d=f instanceof Error?f.message:String(f);i(t,"RESOURCE_EXHAUSTION",d)}break;default:{let f=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",f),u=!1}}return l??(l=Rd(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!yC.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Rd(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:kC.emptyScalarPosition(t,r,i),indent:-1,source:""},f=Zv.composeScalar(e,u,s,l);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(f.spaceBefore=!0),a&&(f.comment=a,f.range[2]=c),f}function EC({options:e},{offset:t,source:r,end:i},n){let a=new wC.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=bC.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Pd.composeEmptyNode=Rd;Pd.composeNode=eg});var ng=R(ig=>{"use strict";var xC=fa(),rg=tg(),CC=Gi(),RC=va();function PC(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new xC.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=RC.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?rg.composeNode(l,n,u,o):rg.composeEmptyNode(l,u.end,i,null,u,o);let f=c.contents.range[2],d=CC.resolveEnd(a,f,!1,o);return d.comment&&(c.comment=d.comment),c.range=[r,f,d.offset],c}ig.composeDoc=PC});var Ad=R(sg=>{"use strict";var _C=Qo("process"),AC=mu(),IC=fa(),ga=ma(),ag=G(),TC=ng(),jC=Gi();function wa(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function og(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
101
+ `),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var pP={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function fP(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}uw.resolveFlowScalar=sP});var fw=R(pw=>{"use strict";var ki=U(),dw=we(),hP=fp(),mP=mp();function vP(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?hP.resolveBlockScalar(e,t,i):mP.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,p=>i(r,"TAG_RESOLVE_FAILED",p)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[ki.SCALAR]:c?l=gP(e.schema,n,c,r,i):t.type==="scalar"?l=wP(e,n,t,i):l=e.schema[ki.SCALAR];let u;try{let p=l.resolve(n,d=>i(r??t,"TAG_RESOLVE_FAILED",d),e.options);u=ki.isScalar(p)?p:new dw.Scalar(p)}catch(p){let d=p instanceof Error?p.message:String(p);i(r??t,"TAG_RESOLVE_FAILED",d),u=new dw.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function gP(e,t,r,i,n){if(r==="!")return e[ki.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[ki.SCALAR])}function wP({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[ki.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[ki.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}pw.composeScalar=vP});var mw=R(hw=>{"use strict";function yP(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}hw.emptyScalarPosition=yP});var ww=R(gp=>{"use strict";var bP=Sa(),NP=U(),kP=sw(),vw=fw(),SP=gn(),EP=mw(),xP={composeNode:gw,composeEmptyNode:vp};function gw(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(t.type){case"alias":l=RP(e,t,i),(s||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=vw.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=kP.composeCollection(xP,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(p){let d=p instanceof Error?p.message:String(p);i(t,"RESOURCE_EXHAUSTION",d)}break;default:{let p=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",p),u=!1}}return l??(l=vp(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!NP.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function vp(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:EP.emptyScalarPosition(t,r,i),indent:-1,source:""},p=vw.composeScalar(e,u,s,l);return o&&(p.anchor=o.source.substring(1),p.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(p.spaceBefore=!0),a&&(p.comment=a,p.range[2]=c),p}function RP({options:e},{offset:t,source:r,end:i},n){let a=new bP.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=SP.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}gp.composeEmptyNode=vp;gp.composeNode=gw});var Nw=R(bw=>{"use strict";var CP=La(),yw=ww(),PP=gn(),_P=Va();function AP(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new CP.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=_P.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?yw.composeNode(l,n,u,o):yw.composeEmptyNode(l,u.end,i,null,u,o);let p=c.contents.range[2],d=PP.resolveEnd(a,p,!1,o);return d.comment&&(c.comment=d.comment),c.range=[r,p,d.offset],c}bw.composeDoc=AP});var yp=R(Ew=>{"use strict";var IP=Bs("process"),TP=nd(),$P=La(),Wa=Ma(),kw=U(),jP=Nw(),OP=gn();function za(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function Sw(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
103
103
 
104
104
  `:`
105
- `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var _d=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=wa(r);a?this.warnings.push(new ga.YAMLWarning(o,i,n)):this.errors.push(new ga.YAMLParseError(o,i,n))},this.directives=new AC.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=og(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
106
- ${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(ag.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];ag.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
105
+ `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var wp=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=za(r);a?this.warnings.push(new Wa.YAMLWarning(o,i,n)):this.errors.push(new Wa.YAMLParseError(o,i,n))},this.directives=new TP.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=Sw(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
106
+ ${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(kw.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];kw.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
107
107
  ${s}`:i}else{let o=a.commentBefore;a.commentBefore=o?`${i}
108
- ${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:og(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(_C.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=wa(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=TC.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new ga.YAMLParseError(wa(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new ga.YAMLParseError(wa(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=jC.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
109
- ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new ga.YAMLParseError(wa(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new IC.Document(void 0,i);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,r,r],this.decorate(n,!1),yield n}}};sg.Composer=_d});var ug=R(Ms=>{"use strict";var $C=Ed(),OC=Cd(),HC=ma(),cg=ta();function DC(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new HC.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return OC.resolveFlowScalar(e,t,i);case"block-scalar":return $C.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function BC(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=cg.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
108
+ ${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Sw(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(IP.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=za(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=jP.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new Wa.YAMLParseError(za(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Wa.YAMLParseError(za(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=OP.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
109
+ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new Wa.YAMLParseError(za(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new $P.Document(void 0,i);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,r,r],this.decorate(n,!1),yield n}}};Ew.Composer=wp});var Cw=R(_c=>{"use strict";var HP=fp(),DP=mp(),BP=Ma(),xw=Pa();function LP(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new BP.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return DP.resolveFlowScalar(e,t,i);case"block-scalar":return HP.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function FP(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=xw.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
110
110
  `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
111
- `),u=s.substring(0,l),f=s.substring(l+1)+`
112
- `,d=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return lg(d,c)||d.push({type:"newline",offset:-1,indent:i,source:`
113
- `}),{type:"block-scalar",offset:a,indent:i,props:d,source:f}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function LC(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=cg.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":qC(e,c);break;case'"':Id(e,c,"double-quoted-scalar");break;case"'":Id(e,c,"single-quoted-scalar");break;default:Id(e,c,"scalar")}}function qC(e,t){let r=t.indexOf(`
111
+ `),u=s.substring(0,l),p=s.substring(l+1)+`
112
+ `,d=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return Rw(d,c)||d.push({type:"newline",offset:-1,indent:i,source:`
113
+ `}),{type:"block-scalar",offset:a,indent:i,props:d,source:p}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function qP(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=xw.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":MP(e,c);break;case'"':bp(e,c,"double-quoted-scalar");break;case"'":bp(e,c,"single-quoted-scalar");break;default:bp(e,c,"scalar")}}function MP(e,t){let r=t.indexOf(`
114
114
  `),i=t.substring(0,r),n=t.substring(r+1)+`
115
- `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];lg(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
- `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function lg(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function Id(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
- `};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}Ms.createScalarToken=BC;Ms.resolveAsScalar=DC;Ms.setScalarValue=LC});var fg=R(dg=>{"use strict";var FC=e=>"type"in e?zs(e):Ws(e);function zs(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=zs(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Ws(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Ws(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Ws(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Ws({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=zs(t)),r)for(let a of r)n+=a.source;return i&&(n+=zs(i)),n}dg.stringify=FC});var vg=R(mg=>{"use strict";var Td=Symbol("break visit"),VC=Symbol("skip children"),pg=Symbol("remove item");function ci(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),hg(Object.freeze([]),e,t)}ci.BREAK=Td;ci.SKIP=VC;ci.REMOVE=pg;ci.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};ci.parentCollection=(e,t)=>{let r=ci.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function hg(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=hg(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Td)return Td;s===pg&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}mg.visit=ci});var Js=R(Be=>{"use strict";var jd=ug(),MC=fg(),WC=vg(),$d="\uFEFF",Od="",Hd="",Dd="",zC=e=>!!e&&"items"in e,JC=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function GC(e){switch(e){case $d:return"<BOM>";case Od:return"<DOC>";case Hd:return"<FLOW_END>";case Dd:return"<SCALAR>";default:return JSON.stringify(e)}}function UC(e){switch(e){case $d:return"byte-order-mark";case Od:return"doc-mode";case Hd:return"flow-error-end";case Dd:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
115
+ `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];Rw(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
+ `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Rw(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function bp(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
+ `};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}_c.createScalarToken=FP;_c.resolveAsScalar=LP;_c.setScalarValue=qP});var _w=R(Pw=>{"use strict";var VP=e=>"type"in e?Ic(e):Ac(e);function Ic(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Ic(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Ac(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Ac(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Ac(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Ac({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Ic(t)),r)for(let a of r)n+=a.source;return i&&(n+=Ic(i)),n}Pw.stringify=VP});var $w=R(Tw=>{"use strict";var Np=Symbol("break visit"),WP=Symbol("skip children"),Aw=Symbol("remove item");function Si(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Iw(Object.freeze([]),e,t)}Si.BREAK=Np;Si.SKIP=WP;Si.REMOVE=Aw;Si.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};Si.parentCollection=(e,t)=>{let r=Si.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Iw(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Iw(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Np)return Np;s===Aw&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}Tw.visit=Si});var Tc=R(Ve=>{"use strict";var kp=Cw(),zP=_w(),GP=$w(),Sp="\uFEFF",Ep="",xp="",Rp="",JP=e=>!!e&&"items"in e,UP=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function KP(e){switch(e){case Sp:return"<BOM>";case Ep:return"<DOC>";case xp:return"<FLOW_END>";case Rp:return"<SCALAR>";default:return JSON.stringify(e)}}function YP(e){switch(e){case Sp:return"byte-order-mark";case Ep:return"doc-mode";case xp:return"flow-error-end";case Rp:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
118
118
  `:case`\r
119
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Be.createScalarToken=jd.createScalarToken;Be.resolveAsScalar=jd.resolveAsScalar;Be.setScalarValue=jd.setScalarValue;Be.stringify=MC.stringify;Be.visit=WC.visit;Be.BOM=$d;Be.DOCUMENT=Od;Be.FLOW_END=Hd;Be.SCALAR=Dd;Be.isCollection=zC;Be.isScalar=JC;Be.prettyToken=GC;Be.tokenType=UC});var qd=R(wg=>{"use strict";var ya=Js();function gt(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var gg=new Set("0123456789ABCDEFabcdef"),KC=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Gs=new Set(",[]{}"),YC=new Set(` ,[]{}
121
- \r `),Bd=e=>!e||YC.has(e),Ld=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
119
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Ve.createScalarToken=kp.createScalarToken;Ve.resolveAsScalar=kp.resolveAsScalar;Ve.setScalarValue=kp.setScalarValue;Ve.stringify=zP.stringify;Ve.visit=GP.visit;Ve.BOM=Sp;Ve.DOCUMENT=Ep;Ve.FLOW_END=xp;Ve.SCALAR=Rp;Ve.isCollection=JP;Ve.isScalar=UP;Ve.prettyToken=KP;Ve.tokenType=YP});var _p=R(Ow=>{"use strict";var Ga=Tc();function Ct(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var jw=new Set("0123456789ABCDEFabcdef"),XP=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),$c=new Set(",[]{}"),QP=new Set(` ,[]{}
121
+ \r `),Cp=e=>!e||QP.has(e),Pp=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
122
122
  `?!0:r==="\r"?this.buffer[t+1]===`
123
123
  `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
124
124
  `||!n&&!this.atEnd)return t+i+1}return r===`
125
- `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&gt(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
126
- `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===ya.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield ya.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&gt(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!gt(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&gt(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Bd),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&gt(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield ya.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Bd),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||gt(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
125
+ `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&Ct(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
126
+ `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Ga.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield Ga.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&Ct(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ct(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Ct(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Cp),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&Ct(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Ga.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Cp),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ct(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
127
127
  `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
128
- `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>gt(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
128
+ `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>Ct(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
129
129
  `:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
130
130
  `)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
131
131
  `,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
132
132
  `;)i=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
133
- `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield ya.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(gt(a)||t&&Gs.has(a))break;r=i}else if(gt(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
133
+ `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Ga.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(Ct(a)||t&&$c.has(a))break;r=i}else if(Ct(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
134
134
  `?(i+=1,n=`
135
- `,a=this.buffer[i+1]):r=i),a==="#"||t&&Gs.has(a))break;if(n===`
136
- `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Gs.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield ya.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Bd),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(gt(i)||r&&Gs.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!gt(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(KC.has(r))r=this.buffer[++t];else if(r==="%"&&gg.has(this.buffer[t+1])&&gg.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
135
+ `,a=this.buffer[i+1]):r=i),a==="#"||t&&$c.has(a))break;if(n===`
136
+ `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&$c.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Ga.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Cp),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Ct(i)||r&&$c.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!Ct(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(XP.has(r))r=this.buffer[++t];else if(r==="%"&&jw.has(this.buffer[t+1])&&jw.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
137
137
  `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
138
- `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};wg.Lexer=Ld});var Vd=R(yg=>{"use strict";var Fd=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};yg.LineCounter=Fd});var Wd=R(Eg=>{"use strict";var XC=Qo("process"),Ng=Js(),QC=qd();function Ar(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function bg(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Sg(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Us(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Ui(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Ks(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function kg(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Ar(t.start,"explicit-key-ind")&&!Ar(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Sg(t.value)?t.value.end?Ks(t.value.end,t.sep):t.value.end=t.sep:Ks(t.start,t.sep),delete t.sep)}var Md=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new QC.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,XC.env.LOG_TOKENS&&console.log("|",Ng.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Ng.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&kg(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&bg(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{bg(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=Us(this.peek(2)),i=Ui(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
138
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};Ow.Lexer=Pp});var Ip=R(Hw=>{"use strict";var Ap=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};Hw.LineCounter=Ap});var $p=R(qw=>{"use strict";var ZP=Bs("process"),Dw=Tc(),e_=_p();function Wr(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function Bw(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Fw(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function jc(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function wn(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function Oc(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function Lw(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Wr(t.start,"explicit-key-ind")&&!Wr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Fw(t.value)?t.value.end?Oc(t.value.end,t.sep):t.value.end=t.sep:Oc(t.start,t.sep),delete t.sep)}var Tp=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new e_.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,ZP.env.LOG_TOKENS&&console.log("|",Dw.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Dw.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&Lw(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Bw(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Bw(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=jc(this.peek(2)),i=wn(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
139
139
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
140
- `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Ks(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Ar(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Sg(r.key)&&!Ar(r.sep,"newline")){let o=Ui(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Ar(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Ui(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Ar(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Ar(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Ks(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Ar(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=Us(i),a=Ui(n);kg(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
140
+ `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Oc(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Wr(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Fw(r.key)&&!Wr(r.sep,"newline")){let o=wn(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Wr(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=wn(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Wr(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Wr(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Oc(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Wr(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=jc(i),a=wn(n);Lw(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
141
141
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
142
- `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Us(t),i=Ui(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Us(t),i=Ui(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Eg.Parser=Md});var _g=R(ba=>{"use strict";var xg=Ad(),ZC=fa(),Na=ma(),eR=Pu(),tR=G(),rR=Vd(),Cg=Wd();function Rg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new rR.LineCounter||null,prettyErrors:t}}function iR(e,t={}){let{lineCounter:r,prettyErrors:i}=Rg(t),n=new Cg.Parser(r?.addNewLine),a=new xg.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Na.prettifyError(e,r)),s.warnings.forEach(Na.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Pg(e,t={}){let{lineCounter:r,prettyErrors:i}=Rg(t),n=new Cg.Parser(r?.addNewLine),a=new xg.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Na.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Na.prettifyError(e,r)),o.warnings.forEach(Na.prettifyError(e,r))),o}function nR(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Pg(e,r);if(!n)return null;if(n.warnings.forEach(a=>eR.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function aR(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return tR.isDocument(e)&&!i?e.toString(r):new ZC.Document(e,i,r).toString(r)}ba.parse=nR;ba.parseAllDocuments=iR;ba.parseDocument=Pg;ba.stringify=aR});var rr=R(Y=>{"use strict";var oR=Ad(),sR=fa(),cR=ud(),zd=ma(),lR=Yn(),Ir=G(),uR=Cr(),dR=de(),fR=Pr(),pR=_r(),hR=Js(),mR=qd(),vR=Vd(),gR=Wd(),Ys=_g(),Ag=Jn();Y.Composer=oR.Composer;Y.Document=sR.Document;Y.Schema=cR.Schema;Y.YAMLError=zd.YAMLError;Y.YAMLParseError=zd.YAMLParseError;Y.YAMLWarning=zd.YAMLWarning;Y.Alias=lR.Alias;Y.isAlias=Ir.isAlias;Y.isCollection=Ir.isCollection;Y.isDocument=Ir.isDocument;Y.isMap=Ir.isMap;Y.isNode=Ir.isNode;Y.isPair=Ir.isPair;Y.isScalar=Ir.isScalar;Y.isSeq=Ir.isSeq;Y.Pair=uR.Pair;Y.Scalar=dR.Scalar;Y.YAMLMap=fR.YAMLMap;Y.YAMLSeq=pR.YAMLSeq;Y.CST=hR;Y.Lexer=mR.Lexer;Y.LineCounter=vR.LineCounter;Y.Parser=gR.Parser;Y.parse=Ys.parse;Y.parseAllDocuments=Ys.parseAllDocuments;Y.parseDocument=Ys.parseDocument;Y.stringify=Ys.stringify;Y.visit=Ag.visit;Y.visitAsync=Ag.visitAsync});function jg(){NR+=1}var NR,$g=A(()=>{"use strict";NR=0});import{execFileSync as bR}from"node:child_process";function Og(e,t){jg();try{return bR("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:kR,maxBuffer:SR,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Jd(e,t,i)}}function I(e,t){return Og(e,t).trim()}function Zs(e){return I(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function Gd(e,t){I(e,["check-ref-format","--branch",t])}function ka(e){let t=Og(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}var kR,SR,Jd,rt=A(()=>{"use strict";$g();kR=3e4,SR=8*1024*1024,Jd=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});function CR(e){return e.toLowerCase().startsWith(".env")}function Xi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>CR(i))?"environment-file":r.some(i=>xR.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>ER.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var ER,xR,Sa=A(()=>{"use strict";ER=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),xR=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Tr(e){return e!==0&&e!==0n&&e!=="0"}function wt(e,t){return Tr(e.dev)&&Tr(t.dev)&&Tr(e.ino)&&Tr(t.ino)}function Z(e,t){let r=Tr(e.dev)&&Tr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Tr(e.ino)&&Tr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var Ea=A(()=>{"use strict"});var Dt=A(()=>{"use strict";Ea()});import{createHash as RR}from"node:crypto";import{promises as yt}from"node:fs";import it from"node:path";import{TextDecoder as PR}from"node:util";function Ud(e,t){let r=it.relative(e,t);return r===""||!it.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${it.sep}`)}function _R(e){let t=it.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||it.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=Xi(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function AR(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function IR(e,t){return Z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ec(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return wt(r,i)?Z(r,i):Z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Hg(e){let t=await yt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await yt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function TR(e,t){let r=it.resolve(e),i=it.resolve(t);if(!Ud(r,i))throw new Error("Native artifact path is outside its root");let n=[await Hg(r)],a=r;for(let o of it.relative(r,i).split(it.sep).filter(Boolean)){a=it.join(a,o);let s=await Hg(a);if(!Ud(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Dg(e){for(let t of e){let r=await yt.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!IR(t,r)||await yt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Q(e){let t=_R(e.ref),r=e.maxBytes===null?null:AR(e.maxBytes??Kd),i=it.resolve(e.root,...t.split("/")),n=await TR(e.root,it.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await yt.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await yt.realpath(i);if(!Ud(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await yt.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),yt.lstat(i),yt.realpath(i)]);if(await Dg(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!ec(a,c)||!ec(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let f=[],d=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let y=r===null?p.length:r+1-d,b=await s.read(p,0,Math.min(p.length,y),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);f.push(Buffer.from(p.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([s.stat(),yt.lstat(i),yt.realpath(i)]);if(await Dg(n),!h.isFile()||h.isSymbolicLink()||g!==o||!ec(c,m)||!ec(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let v=Buffer.concat(f,d),w;try{w=new PR("utf-8",{fatal:!0}).decode(v)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:y})}return{ref:t,size:d,hash:e.includeHash===!1?null:RR("sha256").update(v).digest("hex"),text:w}}finally{await s.close()}}var Kd,nt=A(()=>{"use strict";Sa();Dt();Kd=1024*1024});import{createHash as jR}from"crypto";function Nt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function $R(e,t){t.has(e)&&Nt("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||Nt("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&Nt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Nt("symbol properties are not supported"),`[${e.map(i=>Yd(i,t)).join(",")}]`}finally{t.delete(e)}}function OR(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Nt("only plain objects are supported"),t.has(e)&&Nt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Nt("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&Nt("accessor properties are not supported"),`${JSON.stringify(o)}:${Yd(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Yd(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Nt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?$R(e,t):OR(e,t);case"bigint":case"function":case"symbol":case"undefined":return Nt(`${typeof e} values are not supported`)}return Nt("unsupported value type")}function tc(e){return Yd(e,new Set)}function T(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return jR("sha256").update(`${e}
143
- ${tc(t)}`).digest("hex")}var fe=A(()=>{"use strict"});import jr from"path";function Mg(e,t){return Qi[t][e]}function qR(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in Qi.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Qi.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in Qi.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in Qi.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in Qi.en)return s}return null}function _a(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,Ra.stringify)(e).trimEnd().split(`
144
- `)){let s=qR(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of Mg(s,t).split(`
142
+ `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=jc(t),i=wn(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=jc(t),i=wn(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};qw.Parser=Tp});var Gw=R(Ua=>{"use strict";var Mw=yp(),t_=La(),Ja=Ma(),r_=gd(),i_=U(),n_=Ip(),Vw=$p();function Ww(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new n_.LineCounter||null,prettyErrors:t}}function a_(e,t={}){let{lineCounter:r,prettyErrors:i}=Ww(t),n=new Vw.Parser(r?.addNewLine),a=new Mw.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Ja.prettifyError(e,r)),s.warnings.forEach(Ja.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function zw(e,t={}){let{lineCounter:r,prettyErrors:i}=Ww(t),n=new Vw.Parser(r?.addNewLine),a=new Mw.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Ja.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Ja.prettifyError(e,r)),o.warnings.forEach(Ja.prettifyError(e,r))),o}function o_(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=zw(e,r);if(!n)return null;if(n.warnings.forEach(a=>r_.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function s_(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return i_.isDocument(e)&&!i?e.toString(r):new t_.Document(e,i,r).toString(r)}Ua.parse=o_;Ua.parseAllDocuments=a_;Ua.parseDocument=zw;Ua.stringify=s_});var Gt=R(Q=>{"use strict";var c_=yp(),l_=La(),u_=Zd(),jp=Ma(),d_=Sa(),zr=U(),p_=Fr(),f_=we(),h_=Mr(),m_=Vr(),v_=Tc(),g_=_p(),w_=Ip(),y_=$p(),Hc=Gw(),Jw=ya();Q.Composer=c_.Composer;Q.Document=l_.Document;Q.Schema=u_.Schema;Q.YAMLError=jp.YAMLError;Q.YAMLParseError=jp.YAMLParseError;Q.YAMLWarning=jp.YAMLWarning;Q.Alias=d_.Alias;Q.isAlias=zr.isAlias;Q.isCollection=zr.isCollection;Q.isDocument=zr.isDocument;Q.isMap=zr.isMap;Q.isNode=zr.isNode;Q.isPair=zr.isPair;Q.isScalar=zr.isScalar;Q.isSeq=zr.isSeq;Q.Pair=p_.Pair;Q.Scalar=f_.Scalar;Q.YAMLMap=h_.YAMLMap;Q.YAMLSeq=m_.YAMLSeq;Q.CST=v_;Q.Lexer=g_.Lexer;Q.LineCounter=w_.LineCounter;Q.Parser=y_.Parser;Q.parse=Hc.parse;Q.parseAllDocuments=Hc.parseAllDocuments;Q.parseDocument=Hc.parseDocument;Q.stringify=Hc.stringify;Q.visit=Jw.visit;Q.visitAsync=Jw.visitAsync});import{AsyncLocalStorage as b_}from"node:async_hooks";import{performance as Dc}from"node:perf_hooks";function Op(e=0){N_+=1,k_+=e;let t=S_.getStore();t&&(t.gitCommands+=1,t.gitDurationMs+=e)}function Ka(e){let t=Dc.now();try{return e()}finally{Op(Dc.now()-t)}}async function Hp(e){let t=Dc.now();try{return await e()}finally{Op(Dc.now()-t)}}var N_,k_,S_,yn=T(()=>{"use strict";N_=0,k_=0,S_=new b_});import{spawn as Dp}from"node:child_process";import{existsSync as Uw}from"node:fs";import Ei from"node:path";function Bp(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function P_(e){let t=(Bp(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function __(e,t,r){let n=Ei.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Bp(t,"PATH")??"").split(Ei.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Ei.win32.extname(e)?[e]:P_(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?Ei.join(s,c):Ei.resolve(r,c)))}function xi(e,t,r){return __(e,t,r).find(i=>Uw(i))??e}function A_(e){let t=Bp(e,"SystemRoot");if(t){let r=Ei.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(Uw(r))return r}return"powershell.exe"}function Ya(e){if(e.some(t=>R_.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function I_(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(C_,"utf16le").toString("base64");return Dp(A_(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function Lp(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return Dp(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=xi(e,i,r.cwd),a=Ei.win32.extname(n).toLowerCase();return x_.has(a)&&Ya(t),E_.has(a)?I_(n,t,{cwd:r.cwd,env:i}):Dp(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}var E_,x_,R_,C_,Xa=T(()=>{"use strict";E_=new Set([".bat",".cmd",".ps1"]),x_=new Set([".bat",".cmd"]),R_=/[&|<>()^%"!\r\n]/u,C_=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});import{execFile as T_,execFileSync as uF}from"node:child_process";import Kw from"node:path";async function Gr(e,t,r={}){let i=r.timeoutMs??$_,n=r.maxBufferBytes??j_;if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(n)||n<1)throw new Error("External command limits must be positive integers");let a=Kw.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?xi(e,o,a):e,c=process.platform==="win32"&&/\.(?:bat|cmd)$/iu.test(s);c&&Ya(t);let l=()=>new Promise((u,p)=>{let d=!1,f=T_(s,[...t],{cwd:a,env:o,encoding:"utf8",maxBuffer:n,windowsHide:!0,shell:c},(g,w,N)=>{d||(d=!0,clearTimeout(v),r.signal?.removeEventListener("abort",m),g?p(new Qa(e,t,N.trim(),{cause:g,timedOut:O_(g)})):u(w))}),h=g=>{d||(d=!0,clearTimeout(v),r.signal?.removeEventListener("abort",m),f.kill("SIGKILL"),f.stdin?.destroy(),f.stdout?.destroy(),f.stderr?.destroy(),f.unref(),p(new Qa(e,t,"",{timedOut:g})))},m=()=>h(!1),v=setTimeout(()=>h(!0),i);r.signal?.addEventListener("abort",m,{once:!0}),r.signal?.aborted&&m(),f.stdin?.end(r.input)});return/^(?:git|git\.exe)$/iu.test(Kw.win32.basename(e))?Hp(l):l()}function O_(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}var $_,j_,Qa,bn=T(()=>{"use strict";yn();Xa();$_=6e4,j_=8*1024*1024;Qa=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError",this.timedOut=a?.timedOut===!0}command;args;stderr;timedOut}});import{execFileSync as F_}from"node:child_process";function ry(e,t){try{return Ka(()=>F_("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:q_,maxBuffer:M_,windowsHide:!0}))}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Fp(e,t,i)}}function I(e,t){return ry(e,t).trim()}function Lc(e){return I(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function qp(e,t){I(e,["check-ref-format","--branch",t])}function Za(e){let t=ry(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}var q_,M_,Fp,We=T(()=>{"use strict";yn();q_=3e4,M_=8*1024*1024,Fp=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});function z_(e){return e.toLowerCase().startsWith(".env")}function kn(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>z_(i))?"environment-file":r.some(i=>W_.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>V_.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var V_,W_,eo=T(()=>{"use strict";V_=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),W_=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Yr(e){return e!==0&&e!==0n&&e!=="0"}function Pt(e,t){return Yr(e.dev)&&Yr(t.dev)&&Yr(e.ino)&&Yr(t.ino)}function te(e,t){let r=Yr(e.dev)&&Yr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Yr(e.ino)&&Yr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var to=T(()=>{"use strict"});var Jt=T(()=>{"use strict";to()});import{createHash as G_}from"node:crypto";import{promises as _t}from"node:fs";import ht from"node:path";import{TextDecoder as J_}from"node:util";function Mp(e,t){let r=ht.relative(e,t);return r===""||!ht.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ht.sep}`)}function U_(e){let t=ht.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||ht.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=kn(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function K_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Y_(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Fc(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Pt(r,i)?te(r,i):te(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function iy(e){let t=await _t.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await _t.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function X_(e,t){let r=ht.resolve(e),i=ht.resolve(t);if(!Mp(r,i))throw new Error("Native artifact path is outside its root");let n=[await iy(r)],a=r;for(let o of ht.relative(r,i).split(ht.sep).filter(Boolean)){a=ht.join(a,o);let s=await iy(a);if(!Mp(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function ny(e){for(let t of e){let r=await _t.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Y_(t,r)||await _t.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Z(e){let t=U_(e.ref),r=e.maxBytes===null?null:K_(e.maxBytes??Vp),i=ht.resolve(e.root,...t.split("/")),n=await X_(e.root,ht.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await _t.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await _t.realpath(i);if(!Mp(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await _t.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),_t.lstat(i),_t.realpath(i)]);if(await ny(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Fc(a,c)||!Fc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let p=[],d=0,f=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let N=r===null?f.length:r+1-d,y=await s.read(f,0,Math.min(f.length,N),null);if(y.bytesRead===0)break;if(d+=y.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);p.push(Buffer.from(f.subarray(0,y.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[h,m,v]=await Promise.all([s.stat(),_t.lstat(i),_t.realpath(i)]);if(await ny(n),!m.isFile()||m.isSymbolicLink()||v!==o||!Fc(c,h)||!Fc(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(p,d),w;try{w=new J_("utf-8",{fatal:!0}).decode(g)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:d,hash:e.includeHash===!1?null:G_("sha256").update(g).digest("hex"),text:w}}finally{await s.close()}}var Vp,rt=T(()=>{"use strict";eo();Jt();Vp=1024*1024});import{createHash as Q_}from"crypto";function At(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function Z_(e,t){t.has(e)&&At("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||At("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&At("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&At("symbol properties are not supported"),`[${e.map(i=>Wp(i,t)).join(",")}]`}finally{t.delete(e)}}function eA(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&At("only plain objects are supported"),t.has(e)&&At("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&At("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&At("accessor properties are not supported"),`${JSON.stringify(o)}:${Wp(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Wp(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||At("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?Z_(e,t):eA(e,t);case"bigint":case"function":case"symbol":case"undefined":return At(`${typeof e} values are not supported`)}return At("unsupported value type")}function qc(e){return Wp(e,new Set)}function $(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return Q_("sha256").update(`${e}
143
+ ${qc(t)}`).digest("hex")}var pe=T(()=>{"use strict"});import Xr from"path";function uy(e,t){return Sn[t][e]}function aA(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in Sn.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Sn.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in Sn.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in Sn.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in Sn.en)return s}return null}function oo(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,no.stringify)(e).trimEnd().split(`
144
+ `)){let s=aA(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of uy(s,t).split(`
145
145
  `))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?i="native":o.startsWith("classic:")?i="classic":o.startsWith("hook:")?i="hook":o.startsWith("memory:")?i="memory":o.startsWith("knowledge:")?i="knowledge":i=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(i==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),i==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
146
- `)}function FR(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||jr.posix.isAbsolute(r)||jr.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function li(e){let t=FR(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Wg(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function ac(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||jr.posix.isAbsolute(i)||jr.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function or(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function zg(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function oc(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>rc)throw new Error(`${t} exceeds ${rc} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>ic)throw new Error(`${t} contains more than ${ic} wildcard tokens`);return e}function Fg(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>oc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function xa(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function Vg(e,t,r){let i=xa(e,t,r);if(i>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return i}function VR(e){if(e===void 0)return{...Le,include:[...Le.include],exclude:[...Le.exclude]};let t=or(e,"native.snapshot");return{include:Fg(t.include,"native.snapshot.include",Le.include),exclude:Fg(t.exclude,"native.snapshot.exclude",Le.exclude),max_files:xa(t.max_files,Le.max_files,"native.snapshot.max_files"),max_total_bytes:xa(t.max_total_bytes,Le.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:xa(t.max_duration_ms,Le.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:xa(t.max_selection_records,Le.max_selection_records,"native.snapshot.max_selection_records")}}function MR(e){if(e===void 0)return;let t=or(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=or(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:li(i),toArtifactRoot:li(n),stage:a,...o?{cleanup:o}:{}}}function WR(e){if(e===void 0)return;let t=or(e,"native.finish");if(t.pull_request===void 0)return{};let r=or(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(jr.posix.isAbsolute(i[0])||jr.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??HR;if(!Number.isSafeInteger(n)||n<1||n>qg)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${qg}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function zR(e,t={}){let r=or(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??Xd;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let c=MR(r.pending_root_move),l=WR(r.finish);return{artifact_root:li(i),language:zg(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:VR(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function JR(e){let t=or(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");let a=t.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:Wg(t.artifact_layout),language:zg(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function GR(e){let r=or(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>ac(i,`hook.allow_paths[${n}]`)))]}}function UR(e){if(e===void 0)return{...Ca};let t=or(e,"memory"),r=t.learning??Ca.learning,i=t.retrieval??Ca.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function Zd(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function KR(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||jr.posix.isAbsolute(r)||jr.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>Bg)throw new Error(`${t} exceeds ${Bg} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>Lg)throw new Error(`${t} contains more than ${Lg} wildcard tokens`);return r}function YR(e){let t=Zd(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let i={include:[...new Set(r.map((n,a)=>KR(n,`knowledge.local.include[${a}]`)))],max_file_mb:Vg(t.max_file_mb,nc.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Vg(t.max_total_mb,nc.max_total_mb,"knowledge.local.max_total_mb")};if(i.max_file_mb>i.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return i}function XR(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function QR(e){let t=Zd(e,"knowledge.remote"),r=XR(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function ZR(e){if(e===void 0)return{...Qd};let t=Zd(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:YR(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:QR(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function eP(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function tP(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(d=>d!=="native"&&d!=="classic"))throw new Error("workflows must contain native and/or classic");let f=[...new Set(u)];if(!f.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(f.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:f,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Zi(e,t={}){let r=(0,Ra.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=eP(n.ambient_resume),o=n.hook===void 0?void 0:GR(n.hook),s=UR(n.memory),c=ZR(n.knowledge),l=n.native===void 0?void 0:zR(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:JR(n.classic),f=tP(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:f,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function Jg(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Gg(e){let t=e.knowledge??{...Qd};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Ca},knowledge:{provider:t.provider,...t.local?{local:{include:[...t.local.include],max_file_mb:t.local.max_file_mb??nc.max_file_mb,max_total_mb:t.local.max_total_mb??nc.max_total_mb}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.document_writes?{document_writes:e.native.document_writes}:{},...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Jg(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition,...e.classic.document_evidence?{document_evidence:e.classic.document_evidence}:{}}}:{}}}function Ge(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Aa(e,t){let r=Gg(t),i=Zi((0,Ra.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...Ge(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=Ge(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=Ge(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local?o.local={...Ge(a.local),include:[...i.knowledge.local.include],max_file_mb:i.knowledge.local.max_file_mb,max_total_mb:i.knowledge.local.max_total_mb}:delete o.local,i.knowledge.remote){let c={...Ge(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=Ge(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures,...i.native.document_writes?{document_writes:i.native.document_writes}:{}};if(i.native.finish?.pull_request){let s=Ge(a.finish);o.finish={...s,pull_request:{...Ge(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...Ge(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=Ge(a.pending_root_move),c=Jg(i.native.pending_root_move),l=Ge(s.cleanup),u=Ge(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...Ge(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition,...i.classic.document_evidence?{document_evidence:i.classic.document_evidence}:{}}),n}function sc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Ca},knowledge:{...Qd},native:{artifact_root:li(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Xd,snapshot:{...Le,include:[...Le.include],exclude:[...Le.exclude]}}}}var Ra,Pa,rc,ic,Bg,Lg,Xd,Ca,nc,Qd,HR,qg,DR,BR,LR,Le,Qi,$r=A(()=>{"use strict";Ra=br(rr(),1),Pa=Number.MAX_SAFE_INTEGER,rc=1024,ic=64,Bg=1024,Lg=64,Xd=5,Ca={learning:!0,retrieval:!0},nc={include:[],max_file_mb:1,max_total_mb:32},Qd={provider:"local"},HR=12e4,qg=6e5,DR=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],BR=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],LR=[...DR,...BR].sort((e,t)=>e.localeCompare(t,"en")),Le={include:["**/*"],exclude:[...LR],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4},Qi={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
146
+ `)}function oA(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Xr.posix.isAbsolute(r)||Xr.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Pi(e){let t=oA(e,"native.artifact_root");return t.length===0?".":t.join("/")}function dy(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function zc(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Xr.posix.isAbsolute(i)||Xr.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function yr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function py(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function Gc(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>Mc)throw new Error(`${t} exceeds ${Mc} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>Vc)throw new Error(`${t} contains more than ${Vc} wildcard tokens`);return e}function cy(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>Gc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function ro(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function ly(e,t,r){let i=ro(e,t,r);if(i>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return i}function sA(e){if(e===void 0)return{...ze,include:[...ze.include],exclude:[...ze.exclude]};let t=yr(e,"native.snapshot");return{include:cy(t.include,"native.snapshot.include",ze.include),exclude:cy(t.exclude,"native.snapshot.exclude",ze.exclude),max_files:ro(t.max_files,ze.max_files,"native.snapshot.max_files"),max_total_bytes:ro(t.max_total_bytes,ze.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ro(t.max_duration_ms,ze.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:ro(t.max_selection_records,ze.max_selection_records,"native.snapshot.max_selection_records")}}function cA(e){if(e===void 0)return;let t=yr(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=yr(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:Pi(i),toArtifactRoot:Pi(n),stage:a,...o?{cleanup:o}:{}}}function lA(e){if(e===void 0)return;let t=yr(e,"native.finish");if(t.pull_request===void 0)return{};let r=yr(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Xr.posix.isAbsolute(i[0])||Xr.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??tA;if(!Number.isSafeInteger(n)||n<1||n>sy)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${sy}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function uA(e,t={}){let r=yr(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??zp;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let c=cA(r.pending_root_move),l=lA(r.finish);return{artifact_root:Pi(i),language:py(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:sA(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function dA(e){let t=yr(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");let a=t.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:dy(t.artifact_layout),language:py(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function pA(e){let r=yr(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>zc(i,`hook.allow_paths[${n}]`)))]}}function fA(e){if(e===void 0)return{...io};let t=yr(e,"memory"),r=t.learning??io.learning,i=t.retrieval??io.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function Jp(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function hA(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Xr.posix.isAbsolute(r)||Xr.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>ay)throw new Error(`${t} exceeds ${ay} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>oy)throw new Error(`${t} contains more than ${oy} wildcard tokens`);return r}function mA(e){let t=Jp(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let i={include:[...new Set(r.map((n,a)=>hA(n,`knowledge.local.include[${a}]`)))],max_file_mb:ly(t.max_file_mb,Wc.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:ly(t.max_total_mb,Wc.max_total_mb,"knowledge.local.max_total_mb")};if(i.max_file_mb>i.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return i}function vA(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function gA(e){let t=Jp(e,"knowledge.remote"),r=vA(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function wA(e){if(e===void 0)return{...Gp};let t=Jp(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:mA(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:gA(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function yA(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function bA(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(d=>d!=="native"&&d!=="classic"))throw new Error("workflows must contain native and/or classic");let p=[...new Set(u)];if(!p.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(p.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:p,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function En(e,t={}){let r=(0,no.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=yA(n.ambient_resume),o=n.hook===void 0?void 0:pA(n.hook),s=fA(n.memory),c=wA(n.knowledge),l=n.native===void 0?void 0:uA(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:dA(n.classic),p=bA(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:p,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function fy(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function hy(e){let t=e.knowledge??{...Gp};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...io},knowledge:{provider:t.provider,...t.local?{local:{include:[...t.local.include],max_file_mb:t.local.max_file_mb??Wc.max_file_mb,max_total_mb:t.local.max_total_mb??Wc.max_total_mb}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.document_writes?{document_writes:e.native.document_writes}:{},...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:fy(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition,...e.classic.document_evidence?{document_evidence:e.classic.document_evidence}:{}}}:{}}}function it(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function so(e,t){let r=hy(t),i=En((0,no.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...it(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=it(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=it(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local?o.local={...it(a.local),include:[...i.knowledge.local.include],max_file_mb:i.knowledge.local.max_file_mb,max_total_mb:i.knowledge.local.max_total_mb}:delete o.local,i.knowledge.remote){let c={...it(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=it(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures,...i.native.document_writes?{document_writes:i.native.document_writes}:{}};if(i.native.finish?.pull_request){let s=it(a.finish);o.finish={...s,pull_request:{...it(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...it(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=it(a.pending_root_move),c=fy(i.native.pending_root_move),l=it(s.cleanup),u=it(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...it(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition,...i.classic.document_evidence?{document_evidence:i.classic.document_evidence}:{}}),n}function Jc(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...io},knowledge:{...Gp},native:{artifact_root:Pi(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:zp,snapshot:{...ze,include:[...ze.include],exclude:[...ze.exclude]}}}}var no,ao,Mc,Vc,ay,oy,zp,io,Wc,Gp,tA,sy,rA,iA,nA,ze,Sn,Qr=T(()=>{"use strict";no=hr(Gt(),1),ao=Number.MAX_SAFE_INTEGER,Mc=1024,Vc=64,ay=1024,oy=64,zp=5,io={learning:!0,retrieval:!0},Wc={include:[],max_file_mb:1,max_total_mb:32},Gp={provider:"local"},tA=12e4,sy=6e5,rA=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],iA=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],nA=[...rA,...iA].sort((e,t)=>e.localeCompare(t,"en")),ze={include:["**/*"],exclude:[...nA],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4},Sn={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
147
147
  # ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
148
148
  # learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
149
149
  # retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
@@ -171,61 +171,145 @@ ${tc(t)}`).digest("hex")}var fe=A(()=>{"use strict"});import jr from"path";funct
171
171
  # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
172
172
  # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
173
173
  # 可选值:true | false`,"classic.document_evidence":`# 文档编辑对已记录检查证据的影响:neutral 在只有文档文件变化时保持 build 和 verify 证据有效,strict 重新绑定工作区的全部文件。
174
- # 可选值:neutral | strict`}}});import{constants as cc,promises as ui}from"fs";function ef(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ug(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ia(e){return{dev:e.dev,ino:e.ino,birthtime:ef(e)}}function lc(e,t){let r=Ia(e),i=Ia(t);return wt(r,i)?Z(r,i):Z(r,i)&&ef(e)===ef(t)&&Ug(e)===Ug(t)&&e.size===t.size}async function en(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await ui.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new bt("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new bt("too-large",`${i} exceeds ${t} bytes`);let o=await ui.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Ia(a)});let s=process.platform==="win32"?cc.O_RDONLY:cc.O_RDONLY|cc.O_NOFOLLOW|cc.O_NONBLOCK,c;try{c=await ui.open(e,s)}catch(l){throw l.code==="ELOOP"?new bt("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:n}),ui.lstat(e,{bigint:n}),ui.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!lc(a,l)||!lc(a,u))throw new bt("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:f,identity:Ia(l)}),await r.hooks?.afterOpen?.();let d=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:y}=await c.read(m,0,Math.min(m.length,w),null);if(y===0)break;if(p+=y,p>t)throw new bt("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(m.subarray(0,y)))}await r.hooks?.beforeFinalCheck?.();let[h,g,v]=await Promise.all([c.stat({bigint:n}),ui.lstat(e,{bigint:n}),ui.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||v!==o||!lc(a,h)||!lc(a,g))throw new bt("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:v,identity:Ia(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:v}}finally{await c.close()}}var bt,Ta=A(()=>{"use strict";Ea();bt=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as uc}from"fs";import Or from"path";function rP(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function tf(e,t){let r=Or.relative(e,t);return r===""||!Or.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Or.sep}`)}async function Kg(e,t){let r=Or.resolve(e),i=await uc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return uc.realpath(r)}async function Yg(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Or.join(n,r[a]);let o;try{o=await uc.lstat(n)}catch(u){if(rP(u))return{exists:!1,kind:"missing"};throw u}let s=Or.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await uc.realpath(n);if(!tf(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function tn(e,t,r){let i=ac(t,r.label),n=Or.resolve(e),a=await Kg(n,r.label),o=i.split("/"),s=Or.resolve(n,...o);if(!tf(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Yg(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function sr(e,t,r,i){let n=await tn(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Kg(n.projectRoot,i.label);return en(n.target,r,{...i,verify:async(o,s)=>{if(!tf(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Yg(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Hr=A(()=>{"use strict";Ta();$r()});import{createHash as iP}from"crypto";function rf(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function nP(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function dc(e,t={}){return(await $a(e,t)).document}async function Xg(e){try{return(await sr(e,ja,Pa,{label:ja})).bytes}catch(t){if(nP(t))return null;throw t}}function Qg(e){return e?{exists:!0,sha256:iP("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function fc(e){return Qg(await Xg(e))}async function $a(e,t={}){let r=await Xg(e);return{document:r?Zi(r.toString("utf8"),t):null,identity:Qg(r)}}async function nf(e){return(await dc(e))?.config??null}var ja,rn=A(()=>{"use strict";$r();Hr();ja=".comet/config.yaml"});import{promises as of}from"node:fs";async function sf(e,t){let r;for(let i=0;i<=af.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===af.length||!aP.has(a??""))throw n;await new Promise(o=>setTimeout(o,af[i]))}throw r}async function cf(e,t){await sf(()=>of.rename(e,t),`rename ${t}`)}async function lf(e){await sf(()=>of.unlink(e),`unlink ${e}`)}async function uf(e,t){await sf(()=>of.link(e,t),`link ${t}`)}var aP,af,df=A(()=>{"use strict";aP=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),af=[50,100,200]});var nn=A(()=>{"use strict";df();Ea()});var TD,ff=A(()=>{"use strict";nn();rn();Hr();TD=16*1024});async function pf(e,t){if(!t)return;let r=await fc(e);if(!rf(r,t))throw new Error("Project config changed before commit; rerun the operation")}var hf=A(()=>{"use strict";nn();$r();rn();Hr();ff()});import{randomUUID as lP}from"crypto";import{promises as Pe}from"fs";import kt from"path";function pc(e,t){let r=kt.relative(e,t);return r===""||!kt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${kt.sep}`)}function uP(e,t){return Z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function hc(e,t){return Z({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function dP(e,t){return hc(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Zg(e){let t=await Pe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await Pe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function an(e){for(let t of e){let r=await Pe.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!uP(t,r)||await Pe.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function fP(e,t,r){let[i,n]=await Promise.all([Pe.lstat(e),Pe.realpath(e),r?an(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!hc(i,t)||r&&!pc(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function pP(e,t){let r=kt.resolve(e),i=kt.resolve(t);if(!pc(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Zg(r)],a=kt.relative(r,i).split(kt.sep).filter(Boolean),o=r;for(let s of a){await an(n),o=kt.join(o,s);try{await Pe.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Zg(o);if(!pc(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await an(n),n}async function hP(e){let t;try{t=await Pe.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function mP(e,t,r={}){let i=kt.dirname(e),n=r.containedRoot?await pP(r.containedRoot,i):null;n||await Pe.mkdir(i,{recursive:!0});let a=kt.join(i,`.${kt.basename(e)}.${lP()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await Pe.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([Pe.lstat(a),Pe.realpath(a)]);if(await an(n),!l.isFile()||l.isSymbolicLink()||!hc(s,l)||!pc(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!hc(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await fP(a,c,n),await r.beforeCommit?.(),n){await an(n);let l=await Pe.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!dP(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await uf(a,e),await lf(a)):await cf(a,e),await hP(i)}catch(l){if(await o?.close(),!n)await Pe.rm(a,{force:!0});else try{await an(n),await Pe.rm(a,{force:!0})}catch{}throw l}}async function at(e,t,r={}){await mP(e,t,r)}async function we(e,t,r={}){await at(e,JSON.stringify(t,null,2)+`
175
- `,r)}var ne=A(()=>{"use strict";df();Dt()});import{existsSync as ew,promises as di}from"fs";import U from"path";import vP from"os";async function mf(e){try{return await di.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function wP(e){try{let t=await di.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function sn(e,t){let r=U.relative(e,t);return r===""||!U.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${U.sep}`)}async function on(e){let t=[],r=e;for(;!await mf(r);){let n=U.dirname(r);if(n===r)break;t.push(U.basename(r)),r=n}let i=await di.realpath(r);return U.resolve(i,...t.reverse())}async function vf(e){try{return(await di.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function mc(e){let t=U.resolve(e);try{(await di.stat(t)).isDirectory()||(t=U.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=U.resolve(vP.homedir());for(;;){if(!(t===i&&r!==i)){let o=U.join(t,...Ha.split("/")),s=t===r||await wP(o);if(await mf(o)&&s)return t}if(await mf(U.join(t,".git")))return t;let a=U.dirname(t);if(a===t)return r;t=a}}function vc(e){return li(e)}async function yP(e,t){let r=vc(t),i=U.resolve(e,...r.split("/")),n=await di.realpath(e),a=await on(i);if(!sn(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Dr(e,t){let r=vc(t),i=await yP(e,r),n=U.join(i,"comet");if(await vf(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([on(i),on(n)]);if(!sn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=U.resolve(e),c=U.join(s,".comet","runtime","native");if(await vf(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([di.realpath(s),on(c)]);if(!sn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:U.join(e,...Ha.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:U.join(n,"specs"),changesDir:U.join(n,"changes"),archiveDir:U.join(n,"archive"),runtimeDir:c,changesRuntimeDir:U.join(c,"changes"),locksDir:U.join(c,"locks"),transactionsDir:U.join(c,"transactions")}}function tw(e){if(!gP.test(e))throw new Error(`Invalid Native change name: ${e}`)}function pe(e,t){tw(t);let r=U.join(e.changesRuntimeDir,t);if(!be(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function gf(e,t){tw(t);let r=U.join(e.changesDir,t,"runtime");if(!be(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function ot(e,t){let r=pe(e,t);if(ew(r))return r;let i=gf(e,t);return ew(i)?i:r}function wf(e,t){if(!t.startsWith("runtime/")||U.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=U.resolve(e,...t.slice(8).split("/"));if(!be(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function qe(e,t){let r=U.resolve(t);if(be(e.runtimeDir,r))return e.runtimeDir;if(be(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function be(e,t){return sn(U.resolve(e),U.resolve(t))}async function z(e,t){let r=U.resolve(e),i=U.resolve(t);if(!sn(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await vf(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([on(r),on(i)]);if(!sn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Ha,gP,te=A(()=>{"use strict";$r();Ha=".comet/config.yaml",gP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import NP from"path";function bP(e="docs",t="en"){return sc(e,t)}async function _e(e){let t=(await dc(e))?.config??null;return t?.native?t:null}async function wc(e){let t=await _e(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function yc(e,t,r={}){let i=await $a(e,{allowPartialProject:!0}),n=Aa(i.document?.value??{},t),a=NP.join(e,...Ha.split("/"));await at(a,_a(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await pf(e,i.identity)}})}async function rw(e){let t=await mc(e.startPath),r=await _e(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Ha} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?vc(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??bP(i??"docs"),a=await Dr(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var gc,st=A(()=>{"use strict";$r();rn();hf();ne();te();gc=oc});function bc(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var fi,Da,Nc,cn=A(()=>{"use strict";fi="comet.native.v4",Da="comet.native.local-execution.v4",Nc=["multi-session","single-session"]});var kf={};du(kf,{NativePortableStateVersionConflictError:()=>Ba,appendNativePortableHistory:()=>ye,compareAndSwapNativePortableState:()=>dn,createNativePortableState:()=>nw,parseNativePortableState:()=>B,readNativePortableState:()=>lt,writeNativePortableState:()=>La});import{promises as kP}from"node:fs";function Ae(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ie(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function ke(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function Nf(e,t){return e===null?null:ke(e,t)}function bf(e,t){let r=ke(e,t);if(!CP.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function ln(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ae(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function PP(e,t){return e===null?null:ae(e,t,Number.MIN_SAFE_INTEGER)}function he(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Bt(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function xc(e,t){return Bt(e,t,(r,i)=>ke(r,`${t}[${i}]`))}function pi(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function un(e,t){let r=ke(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Sc(e,t,r=!1){let i=ke(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function ct(e,t){let r=Ae(e,t);return Ie(r,new Set(["text","truncated"]),t),{text:ke(r.text,`${t}.text`,{empty:!0}),truncated:ln(r.truncated,`${t}.truncated`)}}function _P(e,t){let r=`Native spec_changes[${t}]`,i=Ae(e,r);Ie(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=ke(i.capability,`${r}.capability`);if(!EP.test(n))throw new Error(`${r}.capability is invalid`);let a=he(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Sc(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:Sc(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:bf(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function AP(e){let t="Native workspace",r=Ae(e,t);Ie(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=he(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Nf(r.change_branch,`${t}.change_branch`),a=Nf(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:he(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function IP(e){let t="Native loop",r=Ae(e,t);Ie(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=xc(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);pi(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:he(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:he(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:ae(r.goal_cycle,`${t}.goal_cycle`,1),iteration:ae(r.iteration,`${t}.iteration`),attempt:ae(r.attempt,`${t}.attempt`),retry_epoch:ae(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:ae(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:ae(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:ae(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Nf(r.next_action,`${t}.next_action`)}}function TP(e,t){let r=`Native acceptance[${t}]`,i=Ae(e,r);Ie(i,new Set(["id","source","text","result","reason"]),r);let n=ke(i.id,`${r}.id`);if(!xP.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Sc(i.source,`${r}.source`),text:ke(i.text,`${r}.text`),result:he(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ct(i.reason,`${r}.reason`)}}function jP(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Ae(e,r);return Ie(i,new Set(["name","result","note"]),r),{name:ct(i.name,`${r}.name`),result:he(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ct(i.note,`${r}.note`)}}function $P(e){let t="Native builder_handoff",r=Ae(e,t);Ie(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=xc(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);pi(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Ae(r.review,`${t}.review`);return n&&Ie(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ke(r.candidate_id,`${t}.candidate_id`),identity_provider:ke(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:ke(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:ae(r.iteration,`${t}.iteration`,1),summary:ct(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Bt(r.checks,`${t}.checks`,jP),checks_truncated:ln(r.checks_truncated,`${t}.checks_truncated`),known_limits:Bt(r.known_limits,`${t}.known_limits`,(a,o)=>ct(a,`${t}.known_limits[${o}]`)),known_limits_truncated:ln(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:he(n.status,["passed"],`${t}.review.status`),summary:ct(n.summary,`${t}.review.summary`),reviewer_execution_ref:ke(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:un(r.submitted_at,`${t}.submitted_at`)}}function OP(e,t){let r=`Native blockers[${t}]`,i=Ae(e,r);Ie(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=xc(i.acceptance_ids,`${r}.acceptance_ids`);return pi(n,`${r}.acceptance_ids`),{owner:he(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ct(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:he(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function HP(e,t){let r=`Native verification.checks[${t}]`,i=Ae(e,r);return Ie(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:ke(i.id,`${r}.id`),name:ct(i.name,`${r}.name`),argv_display:Bt(i.argv_display,`${r}.argv_display`,(n,a)=>ct(n,`${r}.argv_display[${a}]`)),argv_truncated:ln(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Sc(i.cwd_ref,`${r}.cwd_ref`,!0),status:he(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:PP(i.exit_code,`${r}.exit_code`),duration_ms:ae(i.duration_ms,`${r}.duration_ms`)}}function DP(e){let t="Native verification",r=Ae(e,t);Ie(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Bt(r.checks,`${t}.checks`,HP);pi(i.map(a=>a.id),`${t}.checks IDs`);let n=ke(r.identity_provider,`${t}.identity_provider`);return{candidate_id:ke(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ke(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:ae(r.iteration,`${t}.iteration`,1),attempt:ae(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":he(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:he(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ct(r.summary,`${t}.summary`),risks:Bt(r.risks,`${t}.risks`,(a,o)=>ct(a,`${t}.risks[${o}]`)),risks_truncated:ln(r.risks_truncated,`${t}.risks_truncated`),completed_at:un(r.completed_at,`${t}.completed_at`)}}function iw(e,t){let r=`Native history[${t}]`,i=Ae(e,r);Ie(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=xc(i.unresolved_ids,`${r}.unresolved_ids`);return pi(n,`${r}.unresolved_ids`),{goal_cycle:ae(i.goal_cycle,`${r}.goal_cycle`,1),iteration:ae(i.iteration,`${r}.iteration`),attempt:ae(i.attempt,`${r}.attempt`),outcome:he(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ct(i.summary,`${r}.summary`),completed_at:un(i.completed_at,`${r}.completed_at`)}}function BP(e){let t="Native history_overflow.outcome_counts",r=Ae(e,t),i=["pass","fail","blocked","execution-error","recovery"];return Ie(r,new Set(i),t),{pass:ae(r.pass,`${t}.pass`),fail:ae(r.fail,`${t}.fail`),blocked:ae(r.blocked,`${t}.blocked`),"execution-error":ae(r["execution-error"],`${t}.execution-error`),recovery:ae(r.recovery,`${t}.recovery`)}}function LP(e){let t="Native history_overflow",r=Ae(e,t);Ie(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=ae(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:un(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:un(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=BP(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function qP(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function FP(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function B(e){let t=Ae(e,"Native portable state");if(Ie(t,RP,"Native portable state"),t.schema!==fi)throw new Error(`Native portable state schema must be ${fi}`);let r=ke(t.name,"Native state name");if(!SP.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Bt(t.spec_changes,"Native spec_changes",_P);pi(i.map(s=>s.capability),"Native spec change capabilities");let n=Bt(t.acceptance,"Native acceptance",TP);pi(n.map(s=>s.id),"Native acceptance IDs");let a=Bt(t.history,"Native history",iw);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:fi,name:r,language:he(t.language,["en","zh-CN"],"Native state language"),phase:he(t.phase,["shape","build","verify","archive"],"Native state phase"),status:he(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:ae(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1?{document_constraints_version:1}:(()=>{throw new Error("Native document_constraints_version must be 1")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:bf(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:bf(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:he(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:AP(t.workspace),loop:IP(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:$P(t.builder_handoff),blockers:Bt(t.blockers,"Native blockers",OP),verification:t.verification===null?null:DP(t.verification),history:a,history_overflow:LP(t.history_overflow),verification_result:he(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:he(t.verification_report,["verification.md"],"Native verification_report"),archived:ln(t.archived,"Native archived"),created_at:un(t.created_at,"Native created_at")};return qP(o),FP(o),o}function nw(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return B({schema:fi,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:bc(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function ye(e,t){let r=B(e),i=iw(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return B({...r,history:n,history_overflow:a})}function VP(e,t){let r=(0,Ec.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function lt(e){let t=await kP.readFile(e,"utf8");return B(VP(t,"Native portable state"))}async function La(e,t,r={}){let i=B(t);await at(e,(0,Ec.stringify)(i),r)}async function MP(e,t){let r=kc.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);kc.set(e,a),await r;try{return await t()}finally{i(),kc.get(e)===a&&kc.delete(e)}}async function dn(e){return MP(e.file,async()=>{let t=ae(e.expectedStateVersion,"Native expected state version",1),r=B(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await lt(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Ba(t,i.state_version);return await La(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await lt(e.file);if(n.state_version!==t)throw new Ba(t,n.state_version)}}),r})}var Ec,SP,EP,xP,CP,RP,Ba,kc,ut=A(()=>{"use strict";Ec=br(rr(),1);ne();cn();SP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,EP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xP=/^A[1-9][0-9]*$/u,CP=/^[a-f0-9]{64}$/u,RP=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Ba=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};kc=new Map});import{promises as WP}from"node:fs";import zP from"node:path";function Rc(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Cc(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function ow(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function XP(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function sw(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function dw(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Ef&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),f=e.acceptance_index[l];u&&f&&(f.source!==u.source||f.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!cw(e.children,l)),lw(i)?i:null}if(e.schema===hi&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!cw(e.children,a)),lw(i)?i:null}return null}function cw(e,t){return e.some(r=>r.covers.includes(t))}function lw(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function dt(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function QP(e){let t=Rc(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=Rc(n,`Native children acceptance_index.${i}`);if(Cc(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function ZP(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let f=e[l];if(f.source!==u.source||f.text!==u.text){let d=["source","text"].filter(p=>f[p]!==u[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function fw(e,t,r={}){let i=(0,uw.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Rc(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==hi&&a!==Br)throw Cc(n,aw,"Native children contract"),new Error(`Native children schema must be ${hi} or ${Br}`);let o=a===hi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Cc(n,o==="indexed-v2"?GP:aw,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((d,p)=>{let m=Rc(d,`Native child ${p}`);if(Cc(m,o==="indexed-v2"?YP:o==="summary-v2"?KP:UP,`Native ${s} child fields (child ${p})`),typeof m.name!="string"||!JP.test(m.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:h?m.summary:null,depends_on:ow(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?ow(m.covers,`Native child ${m.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let d of c){let p=d.depends_on.filter(m=>!u.has(m));if(p.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${p.join(", ")}`)}XP(c);let f=r.policy==="advisory";if(a===Ef){if(o==="indexed-v2"){let d=QP(n.acceptance_index);f||ZP(d,t,r);let p=Object.keys(d);return f||sw(c,p,p),{schema:Br,acceptance_index:d,children:c}}return{schema:Br,children:c}}return t&&!f&&sw(c,t),{schema:hi,children:c}}async function Fe(e){let t=zP.join(e.changeDir,Sf);try{await WP.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await Q({root:e.changeDir,ref:Sf}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=fw(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?dw(a,e.acceptanceIds,e.validation??{}):null}}var uw,Sf,hi,Br,Ef,JP,aw,GP,UP,KP,YP,Pc=A(()=>{"use strict";uw=br(rr(),1);nt();Sf="children.yaml",hi="comet.native.children.v1",Br="comet.native.children.v2",Ef=Br,JP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,aw=new Set(["schema","children"]),GP=new Set(["schema","acceptance_index","children"]),UP=new Set(["name","depends_on","covers"]),KP=new Set(["name","summary","depends_on"]),YP=new Set(["name","depends_on","covers"])});function ee(e,t,r,i=""){let n=Object.keys(e),a=t.filter(s=>!Object.hasOwn(e,s)),o=n.filter(s=>!t.includes(s));if(a.length||o.length)throw new qa({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var qa,_c=A(()=>{"use strict";qa=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});function xf(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function Cf(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){xf(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:Ne,executionRef:xf(t.executionRef,"Native execution ref"),[pw]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:xf(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[hw]:!0})}})}function Ac(e){return typeof e=="object"&&e!==null&&e[hw]===!0}function mw(e){return typeof e=="object"&&e!==null&&e[pw]===!0}var pw,hw,Ne,mi=A(()=>{"use strict";pw=Symbol("comet.native.trusted-execution-identity"),hw=Symbol("comet.native.trusted-verifier-envelope"),Ne="skill-coordinated"});function Ic(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Fa(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function vi(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function Tc(e,t="/acceptance"){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((r,i)=>{let n=Ic(r,`Native Verifier acceptance ${i}`);ee(n,["id","result","reason"],`Native Verifier acceptance ${i}`,`${t}/${i}`);let a=vi(n.id,`Native Verifier acceptance ${i} ID`);if(!["passed","failed","blocked"].includes(String(n.result)))throw new Error(`Native Verifier acceptance ${a} result is invalid`);return{id:a,result:n.result,reason:vi(n.reason,`Native Verifier acceptance ${a} reason`)}})}function e_(e,t){let r=Ic(e,"Native Verifier final result");if(ee(r,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result",t),!["pass","fail","blocked"].includes(String(r.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(r.risks)||!r.risks.every(i=>typeof i=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:Fa(r.iteration,"Native Verifier iteration"),attempt:Fa(r.attempt,"Native Verifier attempt"),verdict:r.verdict,acceptance:Tc(r.acceptance,`${t}/acceptance`),risks:r.risks,summary:vi(r.summary,"Native Verifier summary")}}function t_(e,t,r){let i=Ic(e,`Native Verifier check request ${t}`);if(ee(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`,`${r}/${t}`),!Array.isArray(i.argv)||!i.argv.every(a=>typeof a=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let n=Fa(i.timeoutMs,`Native Verifier check request ${t} timeout`);if(n<1)throw new Error("Native Verifier check timeout must be positive");return{id:vi(i.id,`Native Verifier check request ${t} ID`),name:vi(i.name,`Native Verifier check request ${t} name`),executable:vi(i.executable,`Native Verifier check request ${t} executable`),argv:i.argv,cwdRef:vi(i.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:n,repeatable:i.repeatable}}function Va(e,t=""){let r=Ic(e,"Native Verifier response");if(r.kind==="final-result")return ee(r,["kind","result"],"Native Verifier response",t),{kind:"final-result",result:e_(r.result,`${t}/result`)};if(r.kind==="request-checks"){if(ee(r,["kind","iteration","attempt","checks"],"Native Verifier response",t),!Array.isArray(r.checks)||r.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:Fa(r.iteration,"Native Verifier iteration"),attempt:Fa(r.attempt,"Native Verifier attempt"),checks:r.checks.map((i,n)=>t_(i,n,`${t}/checks`))}}throw new Error("Native Verifier response kind is invalid")}function vw(e){if(!Ac(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=Va(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(i.kind==="request-checks")return i;let o=Rf(i.result,r);return{...i,result:{...i.result,acceptance:o}}}function Rf(e,t){Tc(e.acceptance);let r=[...t.acceptanceIds],i=new Set(t.knownAcceptanceIds??r),n=new Set(t.previouslyPassedAcceptanceIds??[]),a=r.filter(h=>!i.has(h)),o=[...n].filter(h=>!i.has(h));if(a.length>0||o.length>0)throw new Error("Native Verifier acceptance binding is internally inconsistent");let s=new Set(r),c=e.acceptance.map(({id:h})=>h),l=c.filter((h,g)=>c.indexOf(h)!==g),u=c.filter(h=>!i.has(h)),f=r.filter(h=>!c.includes(h)),d=e.acceptance.filter(({id:h,result:g})=>s.has(h)||!i.has(h)?!1:!n.has(h)||g!=="passed").map(({id:h,result:g})=>`${h}=${g}`);if(l.length>0||u.length>0||f.length>0||d.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(l)].join(", ")||"none"}; unknown: ${u.join(", ")||"none"}; missing: ${f.join(", ")||"none"}; out-of-scope: ${d.join(", ")||"none"}). Return each required scope ID exactly once and no other acceptance IDs.`);let p=e.acceptance.filter(({id:h})=>s.has(h));if(!t.requiredChecksPassed&&e.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let m=p.map(({result:h})=>h);if(e.verdict==="pass"&&m.some(h=>h!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(e.verdict==="fail"&&!m.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(e.verdict==="blocked"&&!m.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return p}var Ma=A(()=>{"use strict";_c();mi()});function ft(e,t){if(!r_.test(e))throw new Error(`${t} must be a Git commit`)}function Ve(e){return structuredClone(e)}function Ue(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function i_(e,t){if(!Pf(t.dependsOn,e.children)){let r=t.dependsOn.filter(i=>e.children.find(({name:n})=>n===i)?.status!=="integrated");throw new Error(`Native Supervisor child ${t.name} dependency ${r[0]??"?"} is not integrated`)}}function Pf(e,t){let r=new Map(t.map(({name:i,status:n})=>[i,n]));return e.every(i=>r.get(i)==="integrated")}function gw(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function Ja(e){ft(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:Wa(e.contract,i.name),contractHash:T("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:za,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function Wa(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}function _f(e){let t=Ve(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on];let o=Wa(e.contract,n.name),s=T("comet.native.supervisor-contract.v1",e.contract);n.contractHash&&n.contractHash!==s&&n.status!=="integrated"&&n.status!=="archived"&&(n.task=null,n.verifiedCommit=null,n.verification=null,n.checks=[],n.candidateCommit?(n.status="needs-reverify",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."):Pf(n.dependsOn,t.children)?(n.status="ready",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."):(n.status="pending",n.blocker=null)),n.acceptanceScope=o,n.contractHash=s,n.builderFailureCount??=0}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:Wa(e.contract,n.name),contractHash:T("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0});return t.stateVersion+=1,t}function Lr(e,t,r){let i={child:e.child,runId:e.runId},n=(e.checkExecution?.checkStates??[]).filter(({status:o})=>o==="interrupted").map(({id:o})=>o),a=e.role==="builder"?[{kind:"supervisor-builder-result",...i,candidateCommit:"<candidate-commit>"},{kind:"supervisor-builder-failure",...i,reason:"<failure-reason>"}]:[{kind:"supervisor-checks",...i,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],materials:[],...n.length>0?{retry_check_ids:n}:{}},{kind:"supervisor-verifier-result",...i,verdict:"blocked",evidence:{summary:"<verification-summary>",checks:[],acceptance:(e.acceptance??[]).map(({id:o})=>({id:o,result:"blocked",reason:"<evidence>"})),receiptRef:e.checkExecution?.receiptRef??null}}];return{...e,controlProjectRoot:r,returnAction:{cwd:r,commandArgs:["comet","native","next",t,"--runner-input","<temporary-json-file>","--json"],inputOptions:a.map(o=>({name:o.kind,exclusiveGroup:"runner-input",template:o}))}}}function Ga(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=Ve(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);i_(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n,acceptance:i.acceptanceScope??[{id:`child:${i.name}`,source:"children.yaml",text:i.summary??i.name}],contractHash:i.contractHash,verificationBoundary:"child-scope-parent-reverifies-all",checksReason:"not-run"};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,Ue(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function ww(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function Af(e,t){let r=ww(e,t),i=Ve(e);return Ue(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function jc(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=Ve(e),i=r.children.find(({name:a})=>a===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);let n=i.task.role;return n==="builder"?(i.builderFailureCount=(i.builderFailureCount??0)+1,i.status=i.builderFailureCount>=cr?"blocked":"ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=n==="builder"&&(i.builderFailureCount??0)>=cr?`Builder failed ${i.builderFailureCount} times; explicit Builder retry is required. Last failure: ${t.reason}`:t.reason,Ue(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Ua(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=Ve(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,Ue(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function If(e,t){ft(t.candidateCommit,"Native Supervisor candidate commit");let r=Ve(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.builderFailureCount=0,i.task=null,i.blocker=null,Ue(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function Tf(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=Ve(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return Rf({verdict:t.verdict,acceptance:t.evidence.acceptance??[]},{acceptanceIds:i.task.acceptance?.map(({id:n})=>n)??i.acceptanceScope?.map(({id:n})=>n)??[`child:${i.name}`],requiredChecksPassed:t.evidence.checks.length>0}),i.verification={...structuredClone(t.evidence)},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(t.verdict==="fail"?(i.status="ready",i.candidateCommit=null,i.verifiedCommit=null,i.verification=null,i.checks=[]):i.status="needs-reverify",i.blocker=t.evidence.summary),Ue(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function jf(e,t){if(!Number.isSafeInteger(t.expectedStateVersion)||t.expectedStateVersion<1)throw new Error("Native Supervisor Builder retry state version is invalid");if(e.stateVersion!==t.expectedStateVersion)throw new Error("Native Supervisor Builder retry input is stale");let r=Ve(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.status!=="blocked"||i.task!==null||(i.builderFailureCount??0)<cr)throw new Error(`Native Supervisor child ${t.child} is not waiting for an explicit Builder retry`);if(!Pf(i.dependsOn,r.children))throw new Error(`Native Supervisor child ${t.child} dependencies are not integrated`);return i.status="ready",i.candidateCommit=null,i.blocker=null,i.builderFailureCount=0,Ue(r,{kind:"task-cancelled",child:i.name,runId:null,summary:"Explicit Builder retry authorized after the failure budget was exhausted"}),r.stateVersion+=1,r}function $c(e,t){ft(t.integrationCommit,"Native Supervisor integration commit");let r=Ve(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,Ue(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}function Oc(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:(i.status==="ready"||i.status==="active")&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing",builderFailureCount:i.builderFailureCount??0}));return{contractHash:null,supervisorStateVersion:e.stateVersion,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var r_,za,cr,gi=A(()=>{"use strict";fe();Ma();r_=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;za="comet.native.supervisor.v2",cr=3});import Ka from"node:path";import{promises as Nw}from"node:fs";function $f(e,t){return Ka.join(pe(e,t),"supervisor")}function wi(e,t){return Ka.join($f(e,t),"state.json")}function bw(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==za)throw new Error(`Native Supervisor state schema must be ${za}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(ft(t.integration.targetCommit,"Native Supervisor target commit"),ft(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");ft(n.candidateCommit,"Native Supervisor integration candidate commit"),ft(n.integrationCommit,"Native Supervisor integration check commit"),yw(n.checkStates,"Native Supervisor integration")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.builderFailureCount!==void 0&&(!Number.isSafeInteger(n.builderFailureCount)||n.builderFailureCount<0))throw new Error(`Native Supervisor child ${n.name} Builder failure count is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&ft(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(ft(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.checkExecution&&yw(n.task.checkExecution.checkStates,`Native Supervisor child ${n.name}`),n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function O(e,t,r={}){try{let i=await Nw.readFile(wi(e,t),"utf8"),n=JSON.parse(i);if(bw(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(ut(),kf)),c=await s(Ka.join(o.changesDir,t,"comet-state.yaml")),l=await Fe({changeDir:Ka.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:dt(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of n.children)l.contract.children.some(({name:f})=>f===u.name)&&(u.acceptanceScope=Wa(l.contract,u.name),u.contractHash=T("comet.native.supervisor-contract.v1",l.contract),u.task&&(u.task.acceptance=structuredClone(u.acceptanceScope),u.task.contractHash=u.contractHash,u.task.verificationBoundary="child-scope-parent-reverifies-all",u.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(ut(),kf)),s=await o(Ka.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Hc(e,t){let r=await n_(e,t);if(r.length>0)throw new Error(`Native Supervisor Git binding cannot change while active child tasks exist: ${r.join(", ")}`)}async function n_(e,t){return(await O(e,t,{diagnostics:!0}))?.children.filter(({task:i})=>i!==null).map(({name:i})=>i)??[]}async function q(e,t){bw(t),await Nw.mkdir(e.changesRuntimeDir,{recursive:!0}),await we(wi(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function yw(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw new Error(`${t} check states are invalid`);let r=new Set;for(let i of e){if(!i||typeof i.id!="string"||!i.id||r.has(i.id)||typeof i.name!="string"||!["planned","running","passed","failed","interrupted"].includes(i.status)||typeof i.repeatable!="boolean"||!Number.isSafeInteger(i.executionCount)||i.executionCount<0||!Array.isArray(i.argvDisplay)||!i.argvDisplay.every(n=>typeof n=="string")||typeof i.cwdRef!="string"||!Number.isSafeInteger(i.durationMs)||i.durationMs<0||i.exitCode!==null&&!Number.isSafeInteger(i.exitCode)||i.signal!==null&&typeof i.signal!="string"||typeof i.timedOut!="boolean"||i.startedAt!==null&&typeof i.startedAt!="string"||i.completedAt!==null&&typeof i.completedAt!="string"||i.logRef!==null&&typeof i.logRef!="string")throw new Error(`${t} check state is invalid`);r.add(i.id)}}var lr=A(()=>{"use strict";ne();fe();Pc();te();gi()});import{spawn as Of}from"node:child_process";import{existsSync as kw}from"node:fs";import yi from"node:path";function Hf(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function l_(e){let t=(Hf(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function u_(e,t,r){let n=yi.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Hf(t,"PATH")??"").split(yi.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=yi.win32.extname(e)?[e]:l_(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?yi.join(s,c):yi.resolve(r,c)))}function fn(e,t,r){return u_(e,t,r).find(i=>kw(i))??e}function d_(e){let t=Hf(e,"SystemRoot");if(t){let r=yi.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(kw(r))return r}return"powershell.exe"}function Ya(e){if(e.some(t=>s_.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function f_(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(c_,"utf16le").toString("base64");return Of(d_(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function Df(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return Of(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=fn(e,i,r.cwd),a=yi.win32.extname(n).toLowerCase();return o_.has(a)&&Ya(t),a_.has(a)?f_(n,t,{cwd:r.cwd,env:i}):Of(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}var a_,o_,s_,c_,Dc=A(()=>{"use strict";a_=new Set([".bat",".cmd",".ps1"]),o_=new Set([".bat",".cmd"]),s_=/[&|<>()^%"!\r\n]/u,c_=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});import{execFileSync as p_}from"node:child_process";import Sw from"node:path";function v_(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function pn(e,t,r={}){let i=r.timeoutMs??h_,n=r.maxBufferBytes??m_;if(!Number.isSafeInteger(i)||i<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(n)||n<1)throw new Error("External command max buffer must be a positive integer");let a=Sw.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?fn(e,o,a):e,c=Sw.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&Ya(t);try{return p_(s,[...t],{cwd:a,env:o,...r.input!==void 0?{input:r.input}:{},encoding:"utf8",stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:i,maxBuffer:n,windowsHide:!0,shell:process.platform==="win32"&&l})}catch(u){let f=typeof u.stderr=="string"?u.stderr.trim():Buffer.isBuffer(u.stderr)?u.stderr.toString("utf8").trim():"";throw new Bf(e,t,f,{cause:u,timedOut:v_(u)})}}var h_,m_,Bf,Bc=A(()=>{"use strict";Dc();h_=6e4,m_=8*1024*1024,Bf=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError",this.timedOut=a?.timedOut===!0}command;args;stderr;timedOut}});import{promises as Ew}from"node:fs";import xw from"node:path";function y_(e){let t=qf.get(e);if(!t)return;let r=t.value===null?w_:g_;if(Date.now()-t.at>r){qf.delete(e);return}return t.value}async function Ke(e){if(e===process.pid&&Lf!==null)return Lf;let t=y_(e);if(t!==void 0)return t;let r=await N_(e);return e===process.pid&&r!==null&&(Lf=r),e!==process.pid&&qf.set(e,{value:r,at:Date.now()}),r}async function N_(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Ew.readFile(`/proc/${e}/stat`,"utf8"),Ew.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32")return await k_(e);if(process.platform==="darwin"){let t=pn("/bin/ps",["-p",String(e),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}}).trim();return t?`darwin:${t}`:null}}catch{}return null}function b_(e){let t=e.trim();return/^\d+$/u.test(t)?`win32-ps:${t}`:null}async function k_(e){try{let n=pn(xw.win32.join(process.env.SystemRoot??"C:\\Windows","System32","wbem","WMIC.exe"),["process","where",`processid=${e}`,"get","creationdate","/value"],{timeoutMs:5e3,maxBufferBytes:4096}),a=/^CreationDate=(\S+)/mu.exec(n);if(a)return`win32-wmic:${a[1]}`}catch{}let t=process.env.SystemRoot??"C:\\Windows",r=xw.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),i=pn(r,["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:8e3,maxBufferBytes:4096}).trim();return b_(i)}function Lc(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function hn(e,t){if(!Number.isSafeInteger(e)||e<=0)return"alive";try{process.kill(e,0)}catch(i){if(i.code==="ESRCH")return"dead"}if(!t)return"unknown";let r=await Ke(e);return r===t?"alive":r===null||Lc(r)!==Lc(t)&&Cw.has(Lc(r))&&Cw.has(Lc(t))?"unknown":"dead"}async function mn(e,t){return await hn(e,t)!=="dead"}var Lf,g_,w_,qf,Cw,Xa=A(()=>{"use strict";Bc();Lf=null,g_=6e4,w_=1e4,qf=new Map;Cw=new Set(["win32-wmic","win32-ps"])});import{spawn as S_}from"node:child_process";import Ff from"node:path";async function Qa(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&Ff.win32.isAbsolute(r)?Ff.win32.resolve(r):"C:\\Windows",n=Ff.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(f,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(f))};try{c=S_(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",f=>u(f===0)),l=setTimeout(()=>u(!1,!0),E_)}catch{u(!1)}});for(let o=0;o<x_;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var E_,x_,Vf=A(()=>{"use strict";E_=1e3,x_=2});function Me(e){return e.replace(C_,"$1 [REDACTED]").replace(R_,"[REDACTED PRIVATE KEY]").replace(P_,"$1[REDACTED]@").replace(__,"[REDACTED TOKEN]").replace(A_,'$1"[REDACTED]"').replace(I_,"$1$2$1$3$4[REDACTED]$4").replace(T_,"$1$2[REDACTED]")}var C_,R_,P_,__,A_,I_,T_,qr=A(()=>{"use strict";C_=/\b(Bearer|Basic)\s+[^\s"']+/giu,R_=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,P_=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,__=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,A_=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,I_=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,T_=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu});import{accessSync as j_,constants as $_,createWriteStream as O_,existsSync as Mf,promises as H_,statSync as D_}from"node:fs";import me from"node:path";function Pw(e,t){let r=me.relative(e,t);return r===""||!me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${me.sep}`)}function _w(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function Za(e,t){if(t.length===0||t.includes("\\")||me.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||me.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=me.resolve(e),i=me.resolve(r,...t.split("/"));if(!Pw(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=D_(i)}catch(a){throw new Error(`Native check cwd does not exist: ${t}`,{cause:a})}if(!n.isDirectory())throw new Error(`Native check cwd is not a directory: ${t}`);return i}function vn(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}function Rw(e,t){return me.isAbsolute(e)||/[\\/]/u.test(e)?[me.resolve(t,e)]:(process.env.PATH??"").split(me.delimiter).map(r=>r.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean).map(r=>me.join(r,e))}function B_(e,t){if(process.platform==="win32"){let i=fn(e,process.env,t),n=me.win32.isAbsolute(i)?i:Rw(e,t).find(a=>Mf(a));if(!n||!Mf(n))throw new Error(`executable is not available: ${e}`);return[".bat",".cmd"].includes(me.win32.extname(n).toLowerCase()),void 0}let r=Rw(e,t).find(i=>Mf(i));if(!r)throw new Error(`executable is not available: ${e}`);try{j_(r,$_.X_OK)}catch(i){throw new Error(`executable is not executable: ${e}`,{cause:i})}}function Ye(e,t){let r=new Set;t.forEach((i,n)=>{if(r.has(i.id))throw new Error(`Native check plan duplicate ID ${i.id} at /checks/${n}/id`);r.add(i.id);let a;try{if(a=to(e,i),process.platform==="win32"){let o=fn(i.executable,process.env,a),s=me.win32.extname(o).toLowerCase();(s===".bat"||s===".cmd")&&Ya(i.argv)}B_(i.executable,a)}catch(o){throw new Error(`Native check ${i.id} is invalid at /checks/${n}: ${o.message}`,{cause:o})}})}function eo(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=Me(r);return L_.test(r)&&(t=!0),i})}function to(e,t){if(_w(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return Za(e,t.cwdRef)}async function Ni(e){let{plan:t}=e;_w(e.operationId,"Native check operation ID");let r=to(e.projectRoot,t),i=me.join(e.runtimeDir,"logs","checks"),n=me.join(i,`${e.operationId}-${t.id}.log`);if(!Pw(me.resolve(e.runtimeDir),me.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await H_.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=O_(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=Df(t.executable,t.argv,{cwd:r,env:process.env})}catch(g){o.destroy(),c(g);return}let u=!1,f=null,d=null,p=Promise.resolve(),m=!1,h=setTimeout(()=>{u=!0,Qa(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);if(h.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",g=>{f=g,o.write(`
176
- [comet] failed to start check: ${Me(g.message)}
177
- `)}),l.once("close",(g,v)=>{m=!0,clearTimeout(h);let w=(e.now??(()=>new Date))();p.then(()=>{if(d!==null){o.destroy(),c(d);return}o.end(()=>{let y=u||f!==null||v!==null;s({id:t.id,name:t.name,argvDisplay:eo(t.argv),cwdRef:t.cwdRef,status:y?"interrupted":g===0?"passed":"failed",exitCode:g,signal:v,timedOut:u,durationMs:Math.max(0,w.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:w.toISOString(),repeatable:t.repeatable,logRef:me.relative(e.runtimeDir,n).split(me.sep).join("/")})})})}),o.once("error",g=>{clearTimeout(h),d??=g,m?p.then(()=>c(d)):Qa(l).catch(()=>l.kill("SIGKILL"))}),l.pid!==void 0&&e.onSpawn){let g=l.pid;p=Promise.resolve().then(()=>e.onSpawn({pid:g})).catch(async v=>{d=v,l.exitCode===null&&l.signalCode===null&&await Qa(l).catch(()=>l.kill("SIGKILL"))})}})}var L_,gn=A(()=>{"use strict";Dc();Vf();qr();L_=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu});import{AsyncLocalStorage as q_}from"async_hooks";import{randomUUID as Tw}from"crypto";import{promises as pt}from"fs";import jw from"os";import oe from"path";function M_(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function W_(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0||r.processIdentity!==void 0&&(typeof r.processIdentity!="string"||r.processIdentity.length===0))throw new Error(`Invalid Native lock metadata: ${t}`);return r}function $w(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function Fc(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return wt(r,i)?Z(r,i):Z(r,i)&&e.size===t.size}function Vc(e,t){return Fc(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function z_(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&Vc(e.identity,t.identity)}async function St(e){let t,r;try{let i=await en(e,Aw,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof bt?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Aw} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:W_(JSON.parse(t.toString("utf8")),e),identity:$w(r)}}async function J_(e){return(await St(e))?.owner??null}async function zf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==jw.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await hn(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function G_(e,t){try{await pt.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await pt.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Mc(e,t){let r=await St(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Vc(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await pt.mkdir(t,{recursive:!0});let i=oe.join(t,`${oe.basename(e.file)}.${e.owner.id}.${Tw()}.removed`);try{await pt.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await St(i);if(!n||n.owner.id!==e.owner.id||!Fc(n.identity,e.identity))throw await G_(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await pt.rm(i,{force:!0}),"removed"}async function Ow(e){let t=await Ke(process.pid);return{id:Tw(),pid:process.pid,hostname:jw.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function Hw(e,t){let r;try{r=await pt.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await J_(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
178
- `,"utf8"),await r.sync(),i=$w(await r.stat({bigint:!0}))}finally{await r.close()}let n=await St(e);if(!i||!n||n.owner.id!==t.id||!Fc(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function U_(e,t){let r=await z(e.runtimeDir,e.locksDir);await pt.mkdir(r,{recursive:!0});let i=await z(e.runtimeDir,oe.join(r,Wf));await pt.mkdir(i,{recursive:!0});let n=await Ow(t),a=oe.join(i,`.${n.id}.tmp`),o=oe.join(i,`${n.id}.claim`);try{let s=await Hw(a,n);await pt.rename(a,o);let c=await St(o);if(!c||!Fc(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await pt.rm(a,{force:!0})}}async function K_(e){let t=oe.dirname(e.file),r=!1,i=oe.basename(e.file);for(let n of await pt.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=oe.join(t,n.name);if(oe.resolve(a)!==oe.resolve(e.file))try{let o=await St(a),s=await zf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Mc(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Dw(e){let t=await St(e.file);if(t){if(t.owner.id!==e.owner.id||!Vc(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Mc(t,oe.dirname(e.file))}}async function Y_(e,t){let r=Date.now()+F_;for(;;){let i=await U_(e,t);if(!await K_(i))return i;if(await Dw(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function X_(e){let t=qc.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return qc.set(e,n),await t,()=>{r(),qc.get(e)===n&&qc.delete(e)}}async function Wc(e,t,r){let i=oe.resolve(e.locksDir),n=Iw.getStore();if(n?.has(i))return r();let a=await X_(i);try{let o=await Y_(e,t),s=new Map(n??[]);return s.set(i,o),await Iw.run(s,async()=>{try{return await r()}finally{await Dw(o)}})}finally{a()}}async function Bw(e,t,r){let i=[...new Map(e.map(a=>[oe.resolve(a.locksDir),a])).values()].sort((a,o)=>oe.resolve(a.locksDir).localeCompare(oe.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Wc(o,t,()=>n(a+1)):r()};return n(0)}async function zc(e,t,r){return Wc(e,`acquire ${t}`,async()=>{let i=await z(e.runtimeDir,e.locksDir);await pt.mkdir(i,{recursive:!0});let n=await z(e.runtimeDir,oe.join(i,M_(t))),a=await Ow(r),o=await Hw(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Jc(e){await St(e.file)&&await Wc({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${oe.basename(e.file)}`,async()=>{let t=await St(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Vc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=oe.join(e.locksDir,Wf);await Mc(t,r)})}function Q_(e,t=Date.now()){if(!e)return 0;let r=Date.parse(e.createdAt);return Number.isFinite(r)?Math.max(0,t-r):Number.POSITIVE_INFINITY}async function Lw(e){return zf(await St(e))}async function qw(e,t,r,i={}){return Wc(e,`take over ${oe.basename(t)}`,async()=>{let n=await z(e.runtimeDir,e.locksDir),a=await z(e.runtimeDir,t);if(oe.resolve(oe.dirname(a))!==oe.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let o=await St(a),s=await zf(o);if(s.status==="missing")return{status:"missing"};if(r&&!z_(r,s))return{status:"changed",diagnosis:s};let c=i.allowAgedUnknown===!0&&s.status==="unknown"&&Q_(o?.owner??null)>=V_;if(s.status!=="stale"&&!c||!o)return{status:"changed",diagnosis:s};let l=oe.join(n,Wf);return await Mc(o,l)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var Aw,Wf,F_,V_,Iw,qc,ro=A(()=>{"use strict";Ta();Xa();te();Dt();Aw=16*1024,Wf=".coordinator",F_=5e3,V_=900*1e3,Iw=new q_,qc=new Map});import{createHash as Z_}from"node:crypto";function Si(e){return e.replaceAll(`\r
174
+ # 可选值:neutral | strict`}}});import{constants as Uc,promises as _i}from"fs";function Up(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function my(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function co(e){return{dev:e.dev,ino:e.ino,birthtime:Up(e)}}function Kc(e,t){let r=co(e),i=co(t);return Pt(r,i)?te(r,i):te(r,i)&&Up(e)===Up(t)&&my(e)===my(t)&&e.size===t.size}async function xn(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await _i.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new It("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new It("too-large",`${i} exceeds ${t} bytes`);let o=await _i.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:co(a)});let s=process.platform==="win32"?Uc.O_RDONLY:Uc.O_RDONLY|Uc.O_NOFOLLOW|Uc.O_NONBLOCK,c;try{c=await _i.open(e,s)}catch(l){throw l.code==="ELOOP"?new It("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,p]=await Promise.all([c.stat({bigint:n}),_i.lstat(e,{bigint:n}),_i.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||p!==o||!Kc(a,l)||!Kc(a,u))throw new It("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:p,identity:co(l)}),await r.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-f,{bytesRead:N}=await c.read(h,0,Math.min(h.length,w),null);if(N===0)break;if(f+=N,f>t)throw new It("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(h.subarray(0,N)))}await r.hooks?.beforeFinalCheck?.();let[m,v,g]=await Promise.all([c.stat({bigint:n}),_i.lstat(e,{bigint:n}),_i.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!Kc(a,m)||!Kc(a,v))throw new It("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:co(m)}),{bytes:Buffer.concat(d,f),stat:m,realPath:g}}finally{await c.close()}}var It,lo=T(()=>{"use strict";to();It=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as Yc}from"fs";import Zr from"path";function NA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Kp(e,t){let r=Zr.relative(e,t);return r===""||!Zr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Zr.sep}`)}async function vy(e,t){let r=Zr.resolve(e),i=await Yc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Yc.realpath(r)}async function gy(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Zr.join(n,r[a]);let o;try{o=await Yc.lstat(n)}catch(u){if(NA(u))return{exists:!1,kind:"missing"};throw u}let s=Zr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await Yc.realpath(n);if(!Kp(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Rn(e,t,r){let i=zc(t,r.label),n=Zr.resolve(e),a=await vy(n,r.label),o=i.split("/"),s=Zr.resolve(n,...o);if(!Kp(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await gy(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function nt(e,t,r,i){let n=await Rn(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await vy(n.projectRoot,i.label);return xn(n.target,r,{...i,verify:async(o,s)=>{if(!Kp(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await gy(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var br=T(()=>{"use strict";lo();Qr()});import{createHash as kA}from"crypto";function Yp(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function SA(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Xc(e,t={}){return(await po(e,t)).document}async function wy(e){try{return(await nt(e,uo,ao,{label:uo})).bytes}catch(t){if(SA(t))return null;throw t}}function yy(e){return e?{exists:!0,sha256:kA("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Qc(e){return yy(await wy(e))}async function po(e,t={}){let r=await wy(e);return{document:r?En(r.toString("utf8"),t):null,identity:yy(r)}}async function Xp(e){return(await Xc(e))?.config??null}var uo,Cn=T(()=>{"use strict";Qr();br();uo=".comet/config.yaml"});import{promises as Zp}from"node:fs";async function ef(e,t){let r;for(let i=0;i<=Qp.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===Qp.length||!EA.has(a??""))throw n;await new Promise(o=>setTimeout(o,Qp[i]))}throw r}async function tf(e,t){await ef(()=>Zp.rename(e,t),`rename ${t}`)}async function rf(e){await ef(()=>Zp.unlink(e),`unlink ${e}`)}async function nf(e,t){await ef(()=>Zp.link(e,t),`link ${t}`)}var EA,Qp,af=T(()=>{"use strict";EA=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Qp=[50,100,200]});var Pn=T(()=>{"use strict";af();to()});var dq,of=T(()=>{"use strict";Pn();Cn();br();dq=16*1024});async function sf(e,t){if(!t)return;let r=await Qc(e);if(!Yp(r,t))throw new Error("Project config changed before commit; rerun the operation")}var cf=T(()=>{"use strict";Pn();Qr();Cn();br();of()});import{randomUUID as PA}from"crypto";import{promises as je}from"fs";import Tt from"path";function Zc(e,t){let r=Tt.relative(e,t);return r===""||!Tt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Tt.sep}`)}function _A(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function el(e,t){return te({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function AA(e,t){return el(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function by(e){let t=await je.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await je.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function _n(e){for(let t of e){let r=await je.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!_A(t,r)||await je.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function IA(e,t,r){let[i,n]=await Promise.all([je.lstat(e),je.realpath(e),r?_n(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!el(i,t)||r&&!Zc(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function TA(e,t){let r=Tt.resolve(e),i=Tt.resolve(t);if(!Zc(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await by(r)],a=Tt.relative(r,i).split(Tt.sep).filter(Boolean),o=r;for(let s of a){await _n(n),o=Tt.join(o,s);try{await je.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await by(o);if(!Zc(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await _n(n),n}async function $A(e){let t;try{t=await je.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function jA(e,t,r={}){let i=Tt.dirname(e),n=r.containedRoot?await TA(r.containedRoot,i):null;n||await je.mkdir(i,{recursive:!0});let a=Tt.join(i,`.${Tt.basename(e)}.${PA()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await je.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([je.lstat(a),je.realpath(a)]);if(await _n(n),!l.isFile()||l.isSymbolicLink()||!el(s,l)||!Zc(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!el(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await IA(a,c,n),await r.beforeCommit?.(),n){await _n(n);let l=await je.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!AA(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await nf(a,e),await rf(a)):await tf(a,e),await $A(i)}catch(l){if(await o?.close(),!n)await je.rm(a,{force:!0});else try{await _n(n),await je.rm(a,{force:!0})}catch{}throw l}}async function mt(e,t,r={}){await jA(e,t,r)}async function he(e,t,r={}){await mt(e,JSON.stringify(t,null,2)+`
175
+ `,r)}var ne=T(()=>{"use strict";af();Jt()});import{existsSync as Ny,promises as Ai}from"fs";import K from"path";import OA from"os";async function lf(e){try{return await Ai.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function DA(e){try{let t=await Ai.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function In(e,t){let r=K.relative(e,t);return r===""||!K.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${K.sep}`)}async function An(e){let t=[],r=e;for(;!await lf(r);){let n=K.dirname(r);if(n===r)break;t.push(K.basename(r)),r=n}let i=await Ai.realpath(r);return K.resolve(i,...t.reverse())}async function uf(e){try{return(await Ai.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function tl(e){let t=K.resolve(e);try{(await Ai.stat(t)).isDirectory()||(t=K.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=K.resolve(OA.homedir());for(;;){if(!(t===i&&r!==i)){let o=K.join(t,...ho.split("/")),s=t===r||await DA(o);if(await lf(o)&&s)return t}if(await lf(K.join(t,".git")))return t;let a=K.dirname(t);if(a===t)return r;t=a}}function rl(e){return Pi(e)}async function BA(e,t){let r=rl(t),i=K.resolve(e,...r.split("/")),n=await Ai.realpath(e),a=await An(i);if(!In(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function ei(e,t){let r=rl(t),i=await BA(e,r),n=K.join(i,"comet");if(await uf(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([An(i),An(n)]);if(!In(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=K.resolve(e),c=K.join(s,".comet","runtime","native");if(await uf(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([Ai.realpath(s),An(c)]);if(!In(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:K.join(e,...ho.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:K.join(n,"specs"),changesDir:K.join(n,"changes"),archiveDir:K.join(n,"archive"),runtimeDir:c,changesRuntimeDir:K.join(c,"changes"),locksDir:K.join(c,"locks"),transactionsDir:K.join(c,"transactions")}}function ky(e){if(!HA.test(e))throw new Error(`Invalid Native change name: ${e}`)}function me(e,t){ky(t);let r=K.join(e.changesRuntimeDir,t);if(!Ee(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function df(e,t){ky(t);let r=K.join(e.changesDir,t,"runtime");if(!Ee(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function vt(e,t){let r=me(e,t);if(Ny(r))return r;let i=df(e,t);return Ny(i)?i:r}function pf(e,t){if(!t.startsWith("runtime/")||K.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=K.resolve(e,...t.slice(8).split("/"));if(!Ee(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function Ge(e,t){let r=K.resolve(t);if(Ee(e.runtimeDir,r))return e.runtimeDir;if(Ee(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function Ee(e,t){return In(K.resolve(e),K.resolve(t))}async function G(e,t){let r=K.resolve(e),i=K.resolve(t);if(!In(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await uf(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([An(r),An(i)]);if(!In(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var ho,HA,ie=T(()=>{"use strict";Qr();ho=".comet/config.yaml",HA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import LA from"path";function FA(e="docs",t="en"){return Jc(e,t)}async function Oe(e){let t=(await Xc(e))?.config??null;return t?.native?t:null}async function nl(e){let t=await Oe(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function al(e,t,r={}){let i=await po(e,{allowPartialProject:!0}),n=so(i.document?.value??{},t),a=LA.join(e,...ho.split("/"));await mt(a,oo(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await sf(e,i.identity)}})}async function Sy(e){let t=await tl(e.startPath),r=await Oe(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${ho} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?rl(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??FA(i??"docs"),a=await ei(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var il,gt=T(()=>{"use strict";Qr();Cn();cf();ne();ie();il=Gc});function ee(e,t,r,i=""){let n=Object.keys(e),a=t.filter(s=>!Object.hasOwn(e,s)),o=n.filter(s=>!t.includes(s));if(a.length||o.length)throw new mo({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var mo,vo=T(()=>{"use strict";mo=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});function ff(e,t){if(typeof e!="string"||!e.trim()||e.length>4e3||/^<[^>]+>$/u.test(e.trim()))throw new Error(`${t} must contain a concrete statement of at most 4000 characters`);return e.trim()}function $n(e){if(!Array.isArray(e))throw new Error("Native Builder acceptance_review must be an array");return e.map((t,r)=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native Builder acceptance review entry must be an object");let i=t,n=`Native Builder acceptance_review[${r}]`;ee(i,["id","status","evidence","note"],n,`/acceptance_review/${r}`);let a=i.status;if(!["implemented-with-evidence","implemented-no-evidence","not-implemented","known-fail"].includes(a))throw new Error(`${n}.status is invalid`);if(!Array.isArray(i.evidence))throw new Error(`${n}.evidence must be an array`);return{id:ff(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>ff(o,`${n}.evidence`)),note:ff(i.note,`${n}.note`)}})}function jn(e,t){if(!t)throw new Tn(e.map(({id:c})=>c),[]);let r=new Set(e.map(({id:c})=>c)),i=t.map(({id:c})=>c),n=new Set(i);if(n.size!==i.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let a=i.filter(c=>!r.has(c));if(a.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${a.join(", ")}`);let o=e.filter(({id:c})=>!n.has(c)).map(({id:c})=>c),s=t.filter(c=>c.status!=="implemented-with-evidence"||c.evidence.length===0).map(({id:c})=>c);if(o.length||s.length)throw new Tn(o,s)}var Tn,go=T(()=>{"use strict";vo();Tn=class extends Error{constructor(r,i){super(`Native Builder handoff is incomplete${r.length?`; missing: ${r.join(", ")}`:""}${i.length?`; not ready: ${i.join(", ")}`:""}. Complete acceptance_review for every requirement and its evidence before Verify`);this.missingIds=r;this.incompleteIds=i}missingIds;incompleteIds}});function sl(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Ii,wo,ol,On=T(()=>{"use strict";Ii="comet.native.v4",wo="comet.native.local-execution.v4",ol=["multi-session","single-session"]});var gf={};ed(gf,{NativePortableStateVersionConflictError:()=>yo,appendNativePortableHistory:()=>ke,compareAndSwapNativePortableState:()=>Bn,createNativePortableState:()=>xy,parseNativePortableState:()=>B,readNativePortableState:()=>yt,writeNativePortableState:()=>bo});import{promises as qA}from"node:fs";function He(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function De(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function xe(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function mf(e,t){return e===null?null:xe(e,t)}function vf(e,t){let r=xe(e,t);if(!zA.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Hn(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function se(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function JA(e,t){return e===null?null:se(e,t,Number.MIN_SAFE_INTEGER)}function ye(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ut(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function dl(e,t){return Ut(e,t,(r,i)=>xe(r,`${t}[${i}]`))}function Ti(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Dn(e,t){let r=xe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function ll(e,t,r=!1){let i=xe(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function wt(e,t){let r=He(e,t);return De(r,new Set(["text","truncated"]),t),{text:xe(r.text,`${t}.text`,{empty:!0}),truncated:Hn(r.truncated,`${t}.truncated`)}}function UA(e,t){let r=`Native spec_changes[${t}]`,i=He(e,r);De(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=xe(i.capability,`${r}.capability`);if(!VA.test(n))throw new Error(`${r}.capability is invalid`);let a=ye(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:ll(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:ll(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:vf(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function KA(e){let t="Native workspace",r=He(e,t);De(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=ye(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=mf(r.change_branch,`${t}.change_branch`),a=mf(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:ye(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function YA(e){let t="Native loop",r=He(e,t);De(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=dl(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Ti(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:ye(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ye(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:se(r.goal_cycle,`${t}.goal_cycle`,1),iteration:se(r.iteration,`${t}.iteration`),attempt:se(r.attempt,`${t}.attempt`),retry_epoch:se(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:se(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:se(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:se(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:mf(r.next_action,`${t}.next_action`)}}function XA(e,t){let r=`Native acceptance[${t}]`,i=He(e,r);De(i,new Set(["id","source","text","result","reason"]),r);let n=xe(i.id,`${r}.id`);if(!WA.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:ll(i.source,`${r}.source`),text:xe(i.text,`${r}.text`),result:ye(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:wt(i.reason,`${r}.reason`)}}function QA(e,t){let r=`Native builder_handoff.checks[${t}]`,i=He(e,r);return De(i,new Set(["name","result","note"]),r),{name:wt(i.name,`${r}.name`),result:ye(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:wt(i.note,`${r}.note`)}}function ZA(e){let t="Native builder_handoff",r=He(e,t);De(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","acceptance_review","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=dl(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Ti(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:He(r.review,`${t}.review`);return n&&De(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:xe(r.candidate_id,`${t}.candidate_id`),identity_provider:xe(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:xe(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:se(r.iteration,`${t}.iteration`,1),summary:wt(r.summary,`${t}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:$n(r.acceptance_review)},checks:Ut(r.checks,`${t}.checks`,QA),checks_truncated:Hn(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ut(r.known_limits,`${t}.known_limits`,(a,o)=>wt(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Hn(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ye(n.status,["passed"],`${t}.review.status`),summary:wt(n.summary,`${t}.review.summary`),reviewer_execution_ref:xe(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Dn(r.submitted_at,`${t}.submitted_at`)}}function eI(e,t){let r=`Native blockers[${t}]`,i=He(e,r);De(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=dl(i.acceptance_ids,`${r}.acceptance_ids`);return Ti(n,`${r}.acceptance_ids`),{owner:ye(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:wt(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:ye(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function tI(e,t){let r=`Native verification.checks[${t}]`,i=He(e,r);return De(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:xe(i.id,`${r}.id`),name:wt(i.name,`${r}.name`),argv_display:Ut(i.argv_display,`${r}.argv_display`,(n,a)=>wt(n,`${r}.argv_display[${a}]`)),argv_truncated:Hn(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:ll(i.cwd_ref,`${r}.cwd_ref`,!0),status:ye(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:JA(i.exit_code,`${r}.exit_code`),duration_ms:se(i.duration_ms,`${r}.duration_ms`)}}function rI(e){let t="Native verification",r=He(e,t);De(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ut(r.checks,`${t}.checks`,tI);Ti(i.map(a=>a.id),`${t}.checks IDs`);let n=xe(r.identity_provider,`${t}.identity_provider`);return{candidate_id:xe(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:xe(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:se(r.iteration,`${t}.iteration`,1),attempt:se(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":ye(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ye(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:wt(r.summary,`${t}.summary`),risks:Ut(r.risks,`${t}.risks`,(a,o)=>wt(a,`${t}.risks[${o}]`)),risks_truncated:Hn(r.risks_truncated,`${t}.risks_truncated`),completed_at:Dn(r.completed_at,`${t}.completed_at`)}}function Ey(e,t){let r=`Native history[${t}]`,i=He(e,r);De(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=dl(i.unresolved_ids,`${r}.unresolved_ids`);return Ti(n,`${r}.unresolved_ids`),{goal_cycle:se(i.goal_cycle,`${r}.goal_cycle`,1),iteration:se(i.iteration,`${r}.iteration`),attempt:se(i.attempt,`${r}.attempt`),outcome:ye(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:wt(i.summary,`${r}.summary`),completed_at:Dn(i.completed_at,`${r}.completed_at`)}}function iI(e){let t="Native history_overflow.outcome_counts",r=He(e,t),i=["pass","fail","blocked","execution-error","recovery"];return De(r,new Set(i),t),{pass:se(r.pass,`${t}.pass`),fail:se(r.fail,`${t}.fail`),blocked:se(r.blocked,`${t}.blocked`),"execution-error":se(r["execution-error"],`${t}.execution-error`),recovery:se(r.recovery,`${t}.recovery`)}}function nI(e){let t="Native history_overflow",r=He(e,t);De(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=se(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Dn(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Dn(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=iI(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function aI(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);e.builder_handoff?.acceptance_review&&jn(e.acceptance,e.builder_handoff.acceptance_review);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function oI(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function B(e){let t=He(e,"Native portable state");if(De(t,GA,"Native portable state"),t.schema!==Ii)throw new Error(`Native portable state schema must be ${Ii}`);let r=xe(t.name,"Native state name");if(!MA.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Ut(t.spec_changes,"Native spec_changes",UA);Ti(i.map(s=>s.capability),"Native spec change capabilities");let n=Ut(t.acceptance,"Native acceptance",XA);Ti(n.map(s=>s.id),"Native acceptance IDs");let a=Ut(t.history,"Native history",Ey);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Ii,name:r,language:ye(t.language,["en","zh-CN"],"Native state language"),phase:ye(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ye(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:se(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1||t.document_constraints_version===2||t.document_constraints_version===3?{document_constraints_version:t.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1, 2, or 3")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:vf(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:vf(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ye(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:KA(t.workspace),loop:YA(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:ZA(t.builder_handoff),blockers:Ut(t.blockers,"Native blockers",eI),verification:t.verification===null?null:rI(t.verification),history:a,history_overflow:nI(t.history_overflow),verification_result:ye(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ye(t.verification_report,["verification.md"],"Native verification_report"),archived:Hn(t.archived,"Native archived"),created_at:Dn(t.created_at,"Native created_at")};return aI(o),oI(o),o}function xy(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return B({schema:Ii,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:sl(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function ke(e,t){let r=B(e),i=Ey(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return B({...r,history:n,history_overflow:a})}function sI(e,t){let r=(0,ul.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function yt(e){let t=await qA.readFile(e,"utf8");return B(sI(t,"Native portable state"))}async function bo(e,t,r={}){let i=B(t);await mt(e,(0,ul.stringify)(i),r)}async function cI(e,t){let r=cl.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);cl.set(e,a),await r;try{return await t()}finally{i(),cl.get(e)===a&&cl.delete(e)}}async function Bn(e){return cI(e.file,async()=>{let t=se(e.expectedStateVersion,"Native expected state version",1),r=B(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await yt(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new yo(t,i.state_version);return await bo(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await yt(e.file);if(n.state_version!==t)throw new yo(t,n.state_version)}}),r})}var ul,MA,VA,WA,zA,GA,yo,cl,at=T(()=>{"use strict";go();ul=hr(Gt(),1);ne();On();MA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,VA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,WA=/^A[1-9][0-9]*$/u,zA=/^[a-f0-9]{64}$/u,GA=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),yo=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};cl=new Map});import{promises as lI}from"node:fs";import uI from"node:path";function fl(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function pl(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function Cy(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function vI(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function Py(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Ty(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===yf&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),p=e.acceptance_index[l];u&&p&&(p.source!==u.source||p.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!_y(e.children,l)),Ay(i)?i:null}if(e.schema===$i&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!_y(e.children,a)),Ay(i)?i:null}return null}function _y(e,t){return e.some(r=>r.covers.includes(t))}function Ay(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function bt(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function gI(e){let t=fl(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=fl(n,`Native children acceptance_index.${i}`);if(pl(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function wI(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let p=e[l];if(p.source!==u.source||p.text!==u.text){let d=["source","text"].filter(f=>p[f]!==u[f]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function $y(e,t,r={}){let i=(0,Iy.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=fl(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==$i&&a!==ti)throw pl(n,Ry,"Native children contract"),new Error(`Native children schema must be ${$i} or ${ti}`);let o=a===$i?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(pl(n,o==="indexed-v2"?pI:Ry,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((d,f)=>{let h=fl(d,`Native child ${f}`);if(pl(h,o==="indexed-v2"?mI:o==="summary-v2"?hI:fI,`Native ${s} child fields (child ${f})`),typeof h.name!="string"||!dI.test(h.name))throw new Error(`Native child ${f} name is invalid`);let m=o==="summary-v2";if(m){if(typeof h.summary!="string"||h.summary.trim().length===0)throw new Error(`Native child ${h.name} summary must be a non-empty string`);if(h.summary.length>2e3)throw new Error(`Native child ${h.name} summary exceeds 2000 characters`)}return{name:h.name,summary:m?h.summary:null,depends_on:Cy(h.depends_on,`Native child ${h.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Cy(h.covers,`Native child ${h.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let d of c){let f=d.depends_on.filter(h=>!u.has(h));if(f.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${f.join(", ")}`)}vI(c);let p=r.policy==="advisory";if(a===yf){if(o==="indexed-v2"){let d=gI(n.acceptance_index);p||wI(d,t,r);let f=Object.keys(d);return p||Py(c,f,f),{schema:ti,acceptance_index:d,children:c}}return{schema:ti,children:c}}return t&&!p&&Py(c,t),{schema:$i,children:c}}async function Je(e){let t=uI.join(e.changeDir,wf);try{await lI.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await Z({root:e.changeDir,ref:wf}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=$y(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Ty(a,e.acceptanceIds,e.validation??{}):null}}var Iy,wf,$i,ti,yf,dI,Ry,pI,fI,hI,mI,hl=T(()=>{"use strict";Iy=hr(Gt(),1);rt();wf="children.yaml",$i="comet.native.children.v1",ti="comet.native.children.v2",yf=ti,dI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ry=new Set(["schema","children"]),pI=new Set(["schema","acceptance_index","children"]),fI=new Set(["name","depends_on","covers"]),hI=new Set(["name","summary","depends_on"]),mI=new Set(["name","depends_on","covers"])});function bf(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function Nf(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){bf(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:Se,executionRef:bf(t.executionRef,"Native execution ref"),[jy]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:bf(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[Oy]:!0})}})}function ml(e){return typeof e=="object"&&e!==null&&e[Oy]===!0}function Hy(e){return typeof e=="object"&&e!==null&&e[jy]===!0}var jy,Oy,Se,ji=T(()=>{"use strict";jy=Symbol("comet.native.trusted-execution-identity"),Oy=Symbol("comet.native.trusted-verifier-envelope"),Se="skill-coordinated"});function vl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function No(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Oi(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function gl(e,t="/acceptance"){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((r,i)=>{let n=vl(r,`Native Verifier acceptance ${i}`);ee(n,["id","result","reason"],`Native Verifier acceptance ${i}`,`${t}/${i}`);let a=Oi(n.id,`Native Verifier acceptance ${i} ID`);if(!["passed","failed","blocked"].includes(String(n.result)))throw new Error(`Native Verifier acceptance ${a} result is invalid`);return{id:a,result:n.result,reason:Oi(n.reason,`Native Verifier acceptance ${a} reason`)}})}function yI(e,t){let r=vl(e,"Native Verifier final result");if(ee(r,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result",t),!["pass","fail","blocked"].includes(String(r.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(r.risks)||!r.risks.every(i=>typeof i=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:No(r.iteration,"Native Verifier iteration"),attempt:No(r.attempt,"Native Verifier attempt"),verdict:r.verdict,acceptance:gl(r.acceptance,`${t}/acceptance`),risks:r.risks,summary:Oi(r.summary,"Native Verifier summary")}}function bI(e,t,r){let i=vl(e,`Native Verifier check request ${t}`);if(ee(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`,`${r}/${t}`),!Array.isArray(i.argv)||!i.argv.every(a=>typeof a=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let n=No(i.timeoutMs,`Native Verifier check request ${t} timeout`);if(n<1)throw new Error("Native Verifier check timeout must be positive");return{id:Oi(i.id,`Native Verifier check request ${t} ID`),name:Oi(i.name,`Native Verifier check request ${t} name`),executable:Oi(i.executable,`Native Verifier check request ${t} executable`),argv:i.argv,cwdRef:Oi(i.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:n,repeatable:i.repeatable}}function ko(e,t=""){let r=vl(e,"Native Verifier response");if(r.kind==="final-result")return ee(r,["kind","result"],"Native Verifier response",t),{kind:"final-result",result:yI(r.result,`${t}/result`)};if(r.kind==="request-checks"){if(ee(r,["kind","iteration","attempt","checks"],"Native Verifier response",t),!Array.isArray(r.checks)||r.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:No(r.iteration,"Native Verifier iteration"),attempt:No(r.attempt,"Native Verifier attempt"),checks:r.checks.map((i,n)=>bI(i,n,`${t}/checks`))}}throw new Error("Native Verifier response kind is invalid")}function Dy(e){if(!ml(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=ko(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(i.kind==="request-checks")return i;let o=kf(i.result,r);return{...i,result:{...i.result,acceptance:o}}}function kf(e,t){gl(e.acceptance);let r=[...t.acceptanceIds],i=new Set(t.knownAcceptanceIds??r),n=new Set(t.previouslyPassedAcceptanceIds??[]),a=r.filter(m=>!i.has(m)),o=[...n].filter(m=>!i.has(m));if(a.length>0||o.length>0)throw new Error("Native Verifier acceptance binding is internally inconsistent");let s=new Set(r),c=e.acceptance.map(({id:m})=>m),l=c.filter((m,v)=>c.indexOf(m)!==v),u=c.filter(m=>!i.has(m)),p=r.filter(m=>!c.includes(m)),d=e.acceptance.filter(({id:m,result:v})=>s.has(m)||!i.has(m)?!1:!n.has(m)||v!=="passed").map(({id:m,result:v})=>`${m}=${v}`);if(l.length>0||u.length>0||p.length>0||d.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(l)].join(", ")||"none"}; unknown: ${u.join(", ")||"none"}; missing: ${p.join(", ")||"none"}; out-of-scope: ${d.join(", ")||"none"}). Return each required scope ID exactly once and no other acceptance IDs.`);let f=e.acceptance.filter(({id:m})=>s.has(m));if(!t.requiredChecksPassed&&e.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let h=f.map(({result:m})=>m);if(e.verdict==="pass"&&h.some(m=>m!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(e.verdict==="fail"&&!h.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(e.verdict==="blocked"&&!h.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return f}var So=T(()=>{"use strict";vo();ji()});function Nt(e,t){if(!NI.test(e))throw new Error(`${t} must be a Git commit`)}function Ue(e){return structuredClone(e)}function ot(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function kI(e,t){if(!Sf(t.dependsOn,e.children)){let r=t.dependsOn.filter(i=>e.children.find(({name:n})=>n===i)?.status!=="integrated");throw new Error(`Native Supervisor child ${t.name} dependency ${r[0]??"?"} is not integrated`)}}function Sf(e,t){let r=new Map(t.map(({name:i,status:n})=>[i,n]));return e.every(i=>r.get(i)==="integrated")}function By(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function Ro(e){Nt(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:Eo(e.contract,i.name),contractHash:$("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:xo,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function Eo(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}function Ef(e){let t=Ue(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on];let o=Eo(e.contract,n.name),s=$("comet.native.supervisor-contract.v1",e.contract);n.contractHash&&n.contractHash!==s&&n.status!=="integrated"&&n.status!=="archived"&&(n.task=null,n.verifiedCommit=null,n.verification=null,n.checks=[],n.candidateCommit?(n.status="needs-reverify",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."):Sf(n.dependsOn,t.children)?(n.status="ready",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."):(n.status="pending",n.blocker=null)),n.acceptanceScope=o,n.contractHash=s,n.builderFailureCount??=0}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:Eo(e.contract,n.name),contractHash:$("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0});return t.stateVersion+=1,t}function ri(e,t,r){let i={child:e.child,runId:e.runId},n=(e.checkExecution?.checkStates??[]).filter(({status:o})=>o==="interrupted").map(({id:o})=>o),a=e.role==="builder"?[{kind:"supervisor-builder-result",...i,candidateCommit:"<candidate-commit>"},{kind:"supervisor-builder-failure",...i,reason:"<failure-reason>"}]:[{kind:"supervisor-checks",...i,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],materials:[],...n.length>0?{retry_check_ids:n}:{}},{kind:"supervisor-verifier-result",...i,verdict:"blocked",evidence:{summary:"<verification-summary>",checks:[],acceptance:(e.acceptance??[]).map(({id:o})=>({id:o,result:"blocked",reason:"<evidence>"})),receiptRef:e.checkExecution?.receiptRef??null}}];return{...e,controlProjectRoot:r,returnAction:{cwd:r,commandArgs:["comet","native","next",t,"--runner-input","<temporary-json-file>","--json"],inputOptions:a.map(o=>({name:o.kind,exclusiveGroup:"runner-input",template:o}))}}}function Co(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=Ue(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);kI(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n,acceptance:i.acceptanceScope??[{id:`child:${i.name}`,source:"children.yaml",text:i.summary??i.name}],contractHash:i.contractHash,verificationBoundary:"child-scope-parent-reverifies-all",checksReason:"not-run"};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,ot(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function Ly(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function xf(e,t){let r=Ly(e,t),i=Ue(e);return ot(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function wl(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=Ue(e),i=r.children.find(({name:a})=>a===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);let n=i.task.role;return n==="builder"?(i.builderFailureCount=(i.builderFailureCount??0)+1,i.status=i.builderFailureCount>=Nr?"blocked":"ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=n==="builder"&&(i.builderFailureCount??0)>=Nr?`Builder failed ${i.builderFailureCount} times; explicit Builder retry is required. Last failure: ${t.reason}`:t.reason,ot(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Po(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,ot(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Rf(e,t){Nt(t.candidateCommit,"Native Supervisor candidate commit");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.builderFailureCount=0,i.task=null,i.blocker=null,ot(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function Cf(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return kf({verdict:t.verdict,acceptance:t.evidence.acceptance??[]},{acceptanceIds:i.task.acceptance?.map(({id:n})=>n)??i.acceptanceScope?.map(({id:n})=>n)??[`child:${i.name}`],requiredChecksPassed:t.evidence.checks.length>0}),i.verification={...structuredClone(t.evidence)},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(t.verdict==="fail"?(i.status="ready",i.candidateCommit=null,i.verifiedCommit=null,i.verification=null,i.checks=[]):i.status="needs-reverify",i.blocker=t.evidence.summary),ot(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function Pf(e,t){if(!Number.isSafeInteger(t.expectedStateVersion)||t.expectedStateVersion<1)throw new Error("Native Supervisor Builder retry state version is invalid");if(e.stateVersion!==t.expectedStateVersion)throw new Error("Native Supervisor Builder retry input is stale");let r=Ue(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.status!=="blocked"||i.task!==null||(i.builderFailureCount??0)<Nr)throw new Error(`Native Supervisor child ${t.child} is not waiting for an explicit Builder retry`);if(!Sf(i.dependsOn,r.children))throw new Error(`Native Supervisor child ${t.child} dependencies are not integrated`);return i.status="ready",i.candidateCommit=null,i.blocker=null,i.builderFailureCount=0,ot(r,{kind:"task-cancelled",child:i.name,runId:null,summary:"Explicit Builder retry authorized after the failure budget was exhausted"}),r.stateVersion+=1,r}function yl(e,t){Nt(t.integrationCommit,"Native Supervisor integration commit");let r=Ue(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,ot(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}function bl(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:(i.status==="ready"||i.status==="active")&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing",builderFailureCount:i.builderFailureCount??0}));return{contractHash:null,supervisorStateVersion:e.stateVersion,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var NI,xo,Nr,Hi=T(()=>{"use strict";pe();So();NI=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;xo="comet.native.supervisor.v2",Nr=3});import _o from"node:path";import{promises as qy}from"node:fs";function _f(e,t){return _o.join(me(e,t),"supervisor")}function Di(e,t){return _o.join(_f(e,t),"state.json")}function My(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==xo)throw new Error(`Native Supervisor state schema must be ${xo}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(Nt(t.integration.targetCommit,"Native Supervisor target commit"),Nt(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");Nt(n.candidateCommit,"Native Supervisor integration candidate commit"),Nt(n.integrationCommit,"Native Supervisor integration check commit"),Fy(n.checkStates,"Native Supervisor integration")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.builderFailureCount!==void 0&&(!Number.isSafeInteger(n.builderFailureCount)||n.builderFailureCount<0))throw new Error(`Native Supervisor child ${n.name} Builder failure count is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Nt(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(Nt(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.checkExecution&&Fy(n.task.checkExecution.checkStates,`Native Supervisor child ${n.name}`),n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function D(e,t,r={}){try{let i=await qy.readFile(Di(e,t),"utf8"),n=JSON.parse(i);if(My(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(at(),gf)),c=await s(_o.join(o.changesDir,t,"comet-state.yaml")),l=await Je({changeDir:_o.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:bt(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of n.children)l.contract.children.some(({name:p})=>p===u.name)&&(u.acceptanceScope=Eo(l.contract,u.name),u.contractHash=$("comet.native.supervisor-contract.v1",l.contract),u.task&&(u.task.acceptance=structuredClone(u.acceptanceScope),u.task.contractHash=u.contractHash,u.task.verificationBoundary="child-scope-parent-reverifies-all",u.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(at(),gf)),s=await o(_o.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Nl(e,t){let r=await SI(e,t);if(r.length>0)throw new Error(`Native Supervisor Git binding cannot change while active child tasks exist: ${r.join(", ")}`)}async function SI(e,t){return(await D(e,t,{diagnostics:!0}))?.children.filter(({task:i})=>i!==null).map(({name:i})=>i)??[]}async function q(e,t){My(t),await qy.mkdir(e.changesRuntimeDir,{recursive:!0}),await he(Di(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Fy(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw new Error(`${t} check states are invalid`);let r=new Set;for(let i of e){if(!i||typeof i.id!="string"||!i.id||r.has(i.id)||typeof i.name!="string"||!["planned","running","passed","failed","interrupted"].includes(i.status)||typeof i.repeatable!="boolean"||!Number.isSafeInteger(i.executionCount)||i.executionCount<0||!Array.isArray(i.argvDisplay)||!i.argvDisplay.every(n=>typeof n=="string")||typeof i.cwdRef!="string"||!Number.isSafeInteger(i.durationMs)||i.durationMs<0||i.exitCode!==null&&!Number.isSafeInteger(i.exitCode)||i.signal!==null&&typeof i.signal!="string"||typeof i.timedOut!="boolean"||i.startedAt!==null&&typeof i.startedAt!="string"||i.completedAt!==null&&typeof i.completedAt!="string"||i.logRef!==null&&typeof i.logRef!="string")throw new Error(`${t} check state is invalid`);r.add(i.id)}}var kr=T(()=>{"use strict";ne();pe();hl();ie();Hi()});import{createHash as If,randomUUID as EI}from"node:crypto";import{promises as st}from"node:fs";import xI from"node:os";import Ke from"node:path";async function Af(e,t){let r=await st.lstat(e,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(t))throw new Error("Invalid process probe cache");let i=await st.readFile(e),n=await st.lstat(e,{bigint:!0});if(r.ino!==n.ino||r.ctimeNs!==n.ctimeNs||r.size!==n.size)throw new Error("Process probe cache changed");return i}async function zy(e){try{let t=JSON.parse((await Af(Ke.join(e,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(t.file??""))return null;let r=Ke.join(e,t.file),i=await Af(r,65536);return If("sha256").update(i).digest("hex")===t.hash?r:null}catch{return null}}async function PI(e,t){let r,i=EI(),n=Ke.join(e,`probe-${i}.cs`),a=Ke.join(e,`probe-${i}.exe`),o=Ke.join(e,`probe-${i}.json`);try{if(await st.mkdir(e,{recursive:!0,mode:448}),(await st.lstat(e)).isSymbolicLink())return null;r=await st.open(Ke.join(e,"prepare.lock"),"wx",384);let s=await zy(e);if(s)return s;await st.writeFile(n,Wy,{flag:"wx",mode:384});let c;for(let u of["Framework64","Framework"]){let p=Ke.join(t,"Microsoft.NET",u,"v4.0.30319","csc.exe");try{await st.access(p),c=p;break}catch{}}if(!c)return null;await Gr(c,["/nologo","/target:exe","/platform:anycpu",`/out:${a}`,n],{timeoutMs:1500,maxBufferBytes:4096});let l=If("sha256").update(await Af(a,65536)).digest("hex");return await st.writeFile(o,JSON.stringify({file:Ke.basename(a),hash:l}),{flag:"wx",mode:384}),await st.rename(o,Ke.join(e,"probe.json")),a}catch{return null}finally{await st.unlink(n).catch(()=>{}),await st.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await st.unlink(Ke.join(e,"prepare.lock")).catch(()=>{}))}}async function Vy(e,t,r){try{let i=await Gr(Ke.join(t,"System32","wbem","WMIC.exe"),["process","where",`processid=${e}`,"get","creationdate","/value"],{timeoutMs:300,maxBufferBytes:4096,signal:r}),n=/^CreationDate=(\S+)/mu.exec(i);if(n)return`win32-wmic:${n[1]}`}catch{}if(r.aborted)return null;try{let n=(await Gr(Ke.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:1e3,maxBufferBytes:4096,signal:r})).trim();return/^\d+$/u.test(n)?`win32-ps:${n}`:null}catch{return null}}function _I(e,t){let r=kl.get(e);if(r&&performance.now()<r.retryAfter)return r.promise;let i={promise:PI(e,t),retryAfter:1/0};return kl.set(e,i),i.promise.then(n=>{kl.get(e)===i&&(n?kl.delete(e):i.retryAfter=performance.now()+CI)}),i.promise}async function Gy(e,t={}){if(!Number.isSafeInteger(e)||e<=0)return null;let r=t.systemRoot??process.env.SystemRoot??"C:\\Windows",i=Ke.join(t.cacheRoot??Ke.join(xI.tmpdir(),"comet-process-identity"),RI),n=async l=>{if(!l)return null;try{let p=(await Gr(l,[String(e)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(p)?`win32-ps:${p}`:null}catch{return null}},a=await zy(i);if(a){let l=await n(a);return l||Vy(e,r,new AbortController().signal)}let o=_I(i,r),s=new AbortController,c=l=>{if(!l)throw new Error("Probe unavailable");return l};try{return await Promise.any([o.then(n).then(c),Vy(e,r,s.signal).then(c)])}catch{return null}finally{s.abort()}}var Wy,RI,CI,kl,Jy=T(()=>{"use strict";bn();Wy=`using System;
176
+ using System.Runtime.InteropServices;
177
+ class CometProcessIdentity {
178
+ [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
179
+ [DllImport("kernel32.dll")] static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
180
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
181
+ static int Main(string[] args) {
182
+ int pid; if(args.Length != 1 || !int.TryParse(args[0], out pid) || pid <= 0) return 1;
183
+ IntPtr handle=OpenProcess(0x1000, false, pid); if(handle == IntPtr.Zero) return 1;
184
+ try { long creation, exit, kernel, user; if(!GetProcessTimes(handle,out creation,out exit,out kernel,out user)) return 1;
185
+ Console.WriteLine(DateTime.FromFileTimeUtc(creation).Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture)); return 0;
186
+ } finally { CloseHandle(handle); }
187
+ }
188
+ }`,RI=If("sha256").update(Wy).digest("hex"),CI=1e4,kl=new Map});import{promises as Uy}from"node:fs";function II(e){let t=$f.get(e);if(t){if(Date.now()-t.at>AI){$f.delete(e);return}return t.value}}async function ct(e){if(e===process.pid&&Tf!==null)return Tf;let t=II(e);if(t!==void 0)return t;let r=Sl.get(e);r||(r=TI(e),Sl.set(e,r));let i=await r;return Sl.get(e)===r&&Sl.delete(e),e===process.pid&&i!==null&&(Tf=i),i===null&&$f.set(e,{value:null,at:Date.now()}),i}async function TI(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Uy.readFile(`/proc/${e}/stat`,"utf8"),Uy.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32")return await Gy(e);if(process.platform==="darwin"){let t=(await Gr("/bin/ps",["-p",String(e),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}})).trim();return t?`darwin:${t}`:null}}catch{}return null}function El(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function Ln(e,t){if(!Number.isSafeInteger(e)||e<=0)return"alive";try{process.kill(e,0)}catch(i){if(i.code==="ESRCH")return"dead"}if(!t)return"unknown";let r=await ct(e);return r===t?"alive":r===null||El(r)!==El(t)&&Ky.has(El(r))&&Ky.has(El(t))?"unknown":"dead"}async function Fn(e,t){return await Ln(e,t)!=="dead"}var Tf,AI,$f,Sl,Ky,Ao=T(()=>{"use strict";bn();Jy();Tf=null,AI=1e4,$f=new Map,Sl=new Map;Ky=new Set(["win32-wmic","win32-ps"])});import{spawn as $I}from"node:child_process";import jf from"node:path";async function Io(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&jf.win32.isAbsolute(r)?jf.win32.resolve(r):"C:\\Windows",n=jf.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(p,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(p))};try{c=$I(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",p=>u(p===0)),l=setTimeout(()=>u(!1,!0),jI)}catch{u(!1)}});for(let o=0;o<OI;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var jI,OI,Of=T(()=>{"use strict";jI=1e3,OI=2});function Ye(e){return e.replace(HI,"$1 [REDACTED]").replace(DI,"[REDACTED PRIVATE KEY]").replace(BI,"$1[REDACTED]@").replace(LI,"[REDACTED TOKEN]").replace(FI,'$1"[REDACTED]"').replace(qI,"$1$2$1$3$4[REDACTED]$4").replace(MI,"$1$2[REDACTED]")}var HI,DI,BI,LI,FI,qI,MI,ii=T(()=>{"use strict";HI=/\b(Bearer|Basic)\s+[^\s"']+/giu,DI=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,BI=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,LI=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,FI=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,qI=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,MI=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu});import{accessSync as VI,constants as WI,createWriteStream as zI,existsSync as Hf,promises as GI,statSync as JI}from"node:fs";import be from"node:path";function Xy(e,t){let r=be.relative(e,t);return r===""||!be.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${be.sep}`)}function Qy(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function To(e,t){if(t.length===0||t.includes("\\")||be.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||be.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=be.resolve(e),i=be.resolve(r,...t.split("/"));if(!Xy(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=JI(i)}catch(a){throw new Error(`Native check cwd does not exist: ${t}`,{cause:a})}if(!n.isDirectory())throw new Error(`Native check cwd is not a directory: ${t}`);return i}function qn(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}function Yy(e,t){return be.isAbsolute(e)||/[\\/]/u.test(e)?[be.resolve(t,e)]:(process.env.PATH??"").split(be.delimiter).map(r=>r.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean).map(r=>be.join(r,e))}function UI(e,t){if(process.platform==="win32"){let i=xi(e,process.env,t),n=be.win32.isAbsolute(i)?i:Yy(e,t).find(a=>Hf(a));if(!n||!Hf(n))throw new Error(`executable is not available: ${e}`);return[".bat",".cmd"].includes(be.win32.extname(n).toLowerCase()),void 0}let r=Yy(e,t).find(i=>Hf(i));if(!r)throw new Error(`executable is not available: ${e}`);try{VI(r,WI.X_OK)}catch(i){throw new Error(`executable is not executable: ${e}`,{cause:i})}}function lt(e,t){let r=new Set;t.forEach((i,n)=>{if(r.has(i.id))throw new Error(`Native check plan duplicate ID ${i.id} at /checks/${n}/id`);r.add(i.id);let a;try{if(a=jo(e,i),process.platform==="win32"){let o=xi(i.executable,process.env,a),s=be.win32.extname(o).toLowerCase();(s===".bat"||s===".cmd")&&Ya(i.argv)}UI(i.executable,a)}catch(o){throw new Error(`Native check ${i.id} is invalid at /checks/${n}: ${o.message}`,{cause:o})}})}function $o(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=Ye(r);return KI.test(r)&&(t=!0),i})}function jo(e,t){if(Qy(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return To(e,t.cwdRef)}async function Bi(e){let{plan:t}=e;Qy(e.operationId,"Native check operation ID");let r=jo(e.projectRoot,t),i=be.join(e.runtimeDir,"logs","checks"),n=be.join(i,`${e.operationId}-${t.id}.log`);if(!Xy(be.resolve(e.runtimeDir),be.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await GI.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=zI(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=Lp(t.executable,t.argv,{cwd:r,env:process.env})}catch(v){o.destroy(),c(v);return}let u=!1,p=null,d=null,f=Promise.resolve(),h=!1,m=setTimeout(()=>{u=!0,Io(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);if(m.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",v=>{p=v,o.write(`
189
+ [comet] failed to start check: ${Ye(v.message)}
190
+ `)}),l.once("close",(v,g)=>{h=!0,clearTimeout(m);let w=(e.now??(()=>new Date))();f.then(()=>{if(d!==null){o.destroy(),c(d);return}o.end(()=>{let N=u||p!==null||g!==null;s({id:t.id,name:t.name,argvDisplay:$o(t.argv),cwdRef:t.cwdRef,status:N?"interrupted":v===0?"passed":"failed",exitCode:v,signal:g,timedOut:u,durationMs:Math.max(0,w.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:w.toISOString(),repeatable:t.repeatable,logRef:be.relative(e.runtimeDir,n).split(be.sep).join("/")})})})}),o.once("error",v=>{clearTimeout(m),d??=v,h?f.then(()=>c(d)):Io(l).catch(()=>l.kill("SIGKILL"))}),l.pid!==void 0&&e.onSpawn){let v=l.pid;f=Promise.resolve().then(()=>e.onSpawn({pid:v})).catch(async g=>{d=g,l.exitCode===null&&l.signalCode===null&&await Io(l).catch(()=>l.kill("SIGKILL"))})}})}var KI,Mn=T(()=>{"use strict";Xa();Of();ii();KI=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu});import{AsyncLocalStorage as YI}from"async_hooks";import{randomUUID as tb}from"crypto";import{promises as kt}from"fs";import rb from"os";import ce from"path";function ZI(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function eT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0||r.processIdentity!==void 0&&(typeof r.processIdentity!="string"||r.processIdentity.length===0))throw new Error(`Invalid Native lock metadata: ${t}`);return r}function ib(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function Rl(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Pt(r,i)?te(r,i):te(r,i)&&e.size===t.size}function Oo(e,t){return Rl(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function tT(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&Oo(e.identity,t.identity)}async function St(e){let t,r;try{let i=await xn(e,Zy,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof It?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Zy} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:eT(JSON.parse(t.toString("utf8")),e),identity:ib(r)}}async function rT(e){return(await St(e))?.owner??null}async function Bf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==rb.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await Ln(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function iT(e,t){try{await kt.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await kt.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Cl(e,t){let r=await St(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Oo(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await kt.mkdir(t,{recursive:!0});let i=ce.join(t,`${ce.basename(e.file)}.${e.owner.id}.${tb()}.removed`);try{await kt.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await St(i);if(!n||n.owner.id!==e.owner.id||!Rl(n.identity,e.identity))throw await iT(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await kt.rm(i,{force:!0}),"removed"}async function nb(e){let t=await ct(process.pid);return{id:tb(),pid:process.pid,hostname:rb.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function ab(e,t){let r;try{r=await kt.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await rT(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
191
+ `,"utf8"),await r.sync(),i=ib(await r.stat({bigint:!0}))}finally{await r.close()}let n=await St(e);if(!i||!n||n.owner.id!==t.id||!Rl(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function nT(e,t){let r=await G(e.runtimeDir,e.locksDir);await kt.mkdir(r,{recursive:!0});let i=await G(e.runtimeDir,ce.join(r,Df));await kt.mkdir(i,{recursive:!0});let n=await nb(t),a=ce.join(i,`.${n.id}.tmp`),o=ce.join(i,`${n.id}.claim`);try{let s=await ab(a,n);await kt.rename(a,o);let c=await St(o);if(!c||!Rl(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await kt.rm(a,{force:!0})}}async function aT(e){let t=ce.dirname(e.file),r=!1,i=ce.basename(e.file);for(let n of await kt.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=ce.join(t,n.name);if(ce.resolve(a)!==ce.resolve(e.file))try{let o=await St(a),s=await Bf(o);if(s.status==="missing")continue;let c=await St(a);if(!c)continue;if(!o||c.owner.id!==o.owner.id||!Oo(c.identity,o.identity)){n.name<i&&(r=!0);continue}if(s.status==="stale"&&o){await Cl(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function ob(e){let t=await St(e.file);if(t){if(t.owner.id!==e.owner.id||!Oo(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Cl(t,ce.dirname(e.file))}}async function oT(e,t){let r=Date.now()+XI;for(;;){let i=await nT(e,t);if(!await aT(i))return i;if(await ob(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function sT(e){let t=xl.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return xl.set(e,n),await t,()=>{r(),xl.get(e)===n&&xl.delete(e)}}async function Pl(e,t,r){let i=ce.resolve(e.locksDir),n=eb.getStore();if(n?.has(i))return r();let a=await sT(i);try{let o=await oT(e,t),s=new Map(n??[]);return s.set(i,o),await eb.run(s,async()=>{try{return await r()}finally{await ob(o)}})}finally{a()}}async function sb(e,t,r){let i=[...new Map(e.map(a=>[ce.resolve(a.locksDir),a])).values()].sort((a,o)=>ce.resolve(a.locksDir).localeCompare(ce.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Pl(o,t,()=>n(a+1)):r()};return n(0)}async function _l(e,t,r){return Pl(e,`acquire ${t}`,async()=>{let i=await G(e.runtimeDir,e.locksDir);await kt.mkdir(i,{recursive:!0});let n=await G(e.runtimeDir,ce.join(i,ZI(t))),a=await nb(r),o=await ab(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Al(e){await St(e.file)&&await Pl({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${ce.basename(e.file)}`,async()=>{let t=await St(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Oo(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=ce.join(e.locksDir,Df);await Cl(t,r)})}function cT(e,t=Date.now()){if(!e)return 0;let r=Date.parse(e.createdAt);return Number.isFinite(r)?Math.max(0,t-r):Number.POSITIVE_INFINITY}async function cb(e){return Bf(await St(e))}async function lb(e,t,r,i={}){return Pl(e,`take over ${ce.basename(t)}`,async()=>{let n=await G(e.runtimeDir,e.locksDir),a=await G(e.runtimeDir,t);if(ce.resolve(ce.dirname(a))!==ce.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let o=await St(a),s=await Bf(o);if(s.status==="missing")return{status:"missing"};if(r&&!tT(r,s))return{status:"changed",diagnosis:s};let c=i.allowAgedUnknown===!0&&s.status==="unknown"&&cT(o?.owner??null)>=QI;if(s.status!=="stale"&&!c||!o)return{status:"changed",diagnosis:s};let l=ce.join(n,Df);return await Cl(o,l)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var Zy,Df,XI,QI,eb,xl,Ho=T(()=>{"use strict";lo();Ao();ie();Jt();Zy=16*1024,Df=".coordinator",XI=5e3,QI=900*1e3,eb=new YI,xl=new Map});import{createHash as lT}from"node:crypto";function qi(e){return e.replaceAll(`\r
179
192
  `,`
180
193
  `).replaceAll("\r",`
181
- `)}function wn(e){return Z_("sha256").update(Si(e)).digest("hex")}function Yf(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new M(`${t} must be an object`);return e}function Jw(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new M(`${r} has unknown field(s): ${i.join(", ")}`)}function Xf(e,t){if(typeof e!="string"||e.trim().length===0)throw new M(`${t} must be a non-empty string`);return e.trim()}function Vw(e,t){if(e!==void 0){if(typeof e!="string")throw new M(`${t} must be text`);return Si(e).replace(/^\n+|\n+$/gu,"")}}function Gc(e,t){let r=Xf(e,t).toLowerCase();if(!tA.test(r))throw new M(`${t} must be a SHA-256 hash`);return r}function Mw(e,t,r){let i=Yf(e,t),n=Object.entries(i);if(n.length>Fw)throw new M(`${t} must contain at most ${Fw} entries`);let a={};for(let[o,s]of n){if(Uf(o,`${t} ID`)!==o)throw new M(`${t} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=Gc(s,`${t}.${o}`)}return a}function Uf(e,t){let r=Xf(e,t);if(!zw.test(r))throw new M(`${t} is not a valid stable requirement ID`);return r}function rA(e,t){let r=Xf(e,t);if(!eA.test(r))throw new M(`${t} is not a valid capability ID`);return r}function iA(e,t){let r=`Native delta operations[${t}]`,i=Yf(e,r);Jw(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=Uf(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new M(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:Uf(i.to_id,`${r}.to_id`),c=Vw(i.title,`${r}.title`),l=Vw(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:Gc(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!l?.trim())throw new M(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!l?.trim())throw new M(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||c!==void 0||l!==void 0||!u)throw new M(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||l==="")throw new M(`${r} rename requires a different to_id and expected_hash`);return{id:n,operation:o,...s===void 0?{}:{to_id:s},...c===void 0?{}:{title:c},...l===void 0?{}:{body:l},...u===void 0?{}:{expected_hash:u}}}function nA(e){let t=Yf(e,"Native delta");if(Jw(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==Jf)throw new M(`Native delta schema must be ${Jf}`);let r=rA(t.capability,"Native delta capability"),i=Gc(t.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(t.base_version)||Number(t.base_version)<1)throw new M("Native delta base_version must be a positive integer");let n=t.legacy_hash===void 0?void 0:Gc(t.legacy_hash,"Native delta legacy_hash"),a;t.base_requirements!==void 0&&(a=Mw(t.base_requirements,"Native delta base_requirements",!1));let o=t.independent_requirements===void 0?void 0:Mw(t.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(t.operations))throw new M("Native delta operations must be an array");let s=t.operations.map(iA),c=new Set;for(let[l,u]of s.entries()){let f=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let d of f){if(c.has(d))throw new M(`Native delta operations contain duplicate or overlapping requirement ID ${d} at ${l}`);c.add(d)}}if(o!==void 0){if(a===void 0)throw new M("Native delta independent_requirements requires base_requirements");for(let[l,u]of Object.entries(o)){if(c.has(l))throw new M(`Native delta requirement ${l} cannot be both addressed and independent`);let f=a[l];if(u===null?f!==void 0:f!==u)throw new M(`Native delta independent_requirements does not match baseline ${l}`)}}return{schema:Jf,capability:r,base_hash:i,base_version:Number(t.base_version),...n===void 0?{}:{legacy_hash:n},...a===void 0?{}:{base_requirements:a},...o===void 0?{}:{independent_requirements:o},operations:s}}function aA(e){let t=(0,Kf.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new M(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function io(e){return nA(typeof e=="string"?aA(e):e)}function oA(e){let t=/^\s{0,3}(#{1,6})\s+/u.exec(e);return t?t[1].length:null}function sA(e){let t=[],r=null;for(let[i,n]of e.entries()){let a=/^\s{0,3}(`{3,}|~{3,})(.*)$/u.exec(n.trimEnd());if(a){r?a[1][0]===r.marker&&a[1].length>=r.length&&a[2].trim().length===0&&(r=null):r={marker:a[1][0],length:a[1].length};continue}if(r)continue;let o=/^(\s{0,3})(#{2,6})\s+Requirement:\s*([^\s]+)(?:\s+(.*?))?\s*$/u.exec(n);if(!o)continue;let s=o[3];if(!zw.test(s))throw new M(`Native total Spec requirement ID is invalid: ${s}`);t.push({line:i,level:o[2].length,id:s,title:o[4]?.trim()??""})}return t}function ki(e){let t=Si(e),r=t.split(`
182
- `),i=sA(r),n=[],a=new Set;for(let l of i){if(a.has(l.id))throw new M(`Native total Spec contains duplicate requirement ID ${l.id}`);a.add(l.id);let u=r.length;for(let f=l.line+1;f<r.length;f+=1){if(i.some(p=>p.line===f)){u=f;break}let d=oA(r[f]);if(d!==null&&d<=l.level){u=f;break}}n.push({start:l.line,end:u,marker:l})}let o=new Map;for(let l of n){let u=`${r.slice(l.start,l.end).join(`
194
+ `)}function Vn(e){return lT("sha256").update(qi(e)).digest("hex")}function Vf(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new z(`${t} must be an object`);return e}function mb(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new z(`${r} has unknown field(s): ${i.join(", ")}`)}function Wf(e,t){if(typeof e!="string"||e.trim().length===0)throw new z(`${t} must be a non-empty string`);return e.trim()}function db(e,t){if(e!==void 0){if(typeof e!="string")throw new z(`${t} must be text`);return qi(e).replace(/^\n+|\n+$/gu,"")}}function Il(e,t){let r=Wf(e,t).toLowerCase();if(!dT.test(r))throw new z(`${t} must be a SHA-256 hash`);return r}function pb(e,t,r){let i=Vf(e,t),n=Object.entries(i);if(n.length>ub)throw new z(`${t} must contain at most ${ub} entries`);let a={};for(let[o,s]of n){if(qf(o,`${t} ID`)!==o)throw new z(`${t} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=Il(s,`${t}.${o}`)}return a}function qf(e,t){let r=Wf(e,t);if(!hb.test(r))throw new z(`${t} is not a valid stable requirement ID`);return r}function pT(e,t){let r=Wf(e,t);if(!uT.test(r))throw new z(`${t} is not a valid capability ID`);return r}function fT(e,t){let r=`Native delta operations[${t}]`,i=Vf(e,r);mb(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=qf(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new z(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:qf(i.to_id,`${r}.to_id`),c=db(i.title,`${r}.title`),l=db(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:Il(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!l?.trim())throw new z(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!l?.trim())throw new z(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||c!==void 0||l!==void 0||!u)throw new z(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||l==="")throw new z(`${r} rename requires a different to_id and expected_hash`);return{id:n,operation:o,...s===void 0?{}:{to_id:s},...c===void 0?{}:{title:c},...l===void 0?{}:{body:l},...u===void 0?{}:{expected_hash:u}}}function hT(e){let t=Vf(e,"Native delta");if(mb(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==Lf)throw new z(`Native delta schema must be ${Lf}`);let r=pT(t.capability,"Native delta capability"),i=Il(t.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(t.base_version)||Number(t.base_version)<1)throw new z("Native delta base_version must be a positive integer");let n=t.legacy_hash===void 0?void 0:Il(t.legacy_hash,"Native delta legacy_hash"),a;t.base_requirements!==void 0&&(a=pb(t.base_requirements,"Native delta base_requirements",!1));let o=t.independent_requirements===void 0?void 0:pb(t.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(t.operations))throw new z("Native delta operations must be an array");let s=t.operations.map(fT),c=new Set;for(let[l,u]of s.entries()){let p=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let d of p){if(c.has(d))throw new z(`Native delta operations contain duplicate or overlapping requirement ID ${d} at ${l}`);c.add(d)}}if(o!==void 0){if(a===void 0)throw new z("Native delta independent_requirements requires base_requirements");for(let[l,u]of Object.entries(o)){if(c.has(l))throw new z(`Native delta requirement ${l} cannot be both addressed and independent`);let p=a[l];if(u===null?p!==void 0:p!==u)throw new z(`Native delta independent_requirements does not match baseline ${l}`)}}return{schema:Lf,capability:r,base_hash:i,base_version:Number(t.base_version),...n===void 0?{}:{legacy_hash:n},...a===void 0?{}:{base_requirements:a},...o===void 0?{}:{independent_requirements:o},operations:s}}function mT(e){let t=(0,Mf.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new z(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function Do(e){return hT(typeof e=="string"?mT(e):e)}function vT(e){let t=/^\s{0,3}(#{1,6})\s+/u.exec(e);return t?t[1].length:null}function gT(e){let t=[],r=null;for(let[i,n]of e.entries()){let a=/^\s{0,3}(`{3,}|~{3,})(.*)$/u.exec(n.trimEnd());if(a){r?a[1][0]===r.marker&&a[1].length>=r.length&&a[2].trim().length===0&&(r=null):r={marker:a[1][0],length:a[1].length};continue}if(r)continue;let o=/^(\s{0,3})(#{2,6})\s+Requirement:\s*([^\s]+)(?:\s+(.*?))?\s*$/u.exec(n);if(!o)continue;let s=o[3];if(!hb.test(s))throw new z(`Native total Spec requirement ID is invalid: ${s}`);t.push({line:i,level:o[2].length,id:s,title:o[4]?.trim()??""})}return t}function Fi(e){let t=qi(e),r=t.split(`
195
+ `),i=gT(r),n=[],a=new Set;for(let l of i){if(a.has(l.id))throw new z(`Native total Spec contains duplicate requirement ID ${l.id}`);a.add(l.id);let u=r.length;for(let p=l.line+1;p<r.length;p+=1){if(i.some(f=>f.line===p)){u=p;break}let d=vT(r[p]);if(d!==null&&d<=l.level){u=p;break}}n.push({start:l.line,end:u,marker:l})}let o=new Map;for(let l of n){let u=`${r.slice(l.start,l.end).join(`
183
196
  `)}${l.end<r.length?`
184
- `:""}`,f=r.slice(l.start+1,l.end).join(`
185
- `).replace(/^\n/u,"").replace(/\n+$/u,"");o.set(l.marker.id,{id:l.marker.id,level:l.marker.level,title:l.marker.title,body:f,raw:u,startLine:l.start,endLine:l.end})}let s=[],c=0;for(let l of n)s.push(r.slice(c,l.start).join(`
197
+ `:""}`,p=r.slice(l.start+1,l.end).join(`
198
+ `).replace(/^\n/u,"").replace(/\n+$/u,"");o.set(l.marker.id,{id:l.marker.id,level:l.marker.level,title:l.marker.title,body:p,raw:u,startLine:l.start,endLine:l.end})}let s=[],c=0;for(let l of n)s.push(r.slice(c,l.start).join(`
186
199
  `)),c=l.end;return s.push(r.slice(c).join(`
187
200
  `)),{text:t,lines:r,requirements:o,legacyText:s.join(`
188
- `)}}function Qf(e){return wn(e)}function ur(e){return wn(e)}function Gw(e){let t=ki(e).legacyText;return wn(t.split(`
201
+ `)}}function zf(e){return Vn(e)}function Sr(e){return Vn(e)}function vb(e){let t=Fi(e).legacyText;return Vn(t.split(`
189
202
  `).filter(r=>r.trim().length>0).join(`
190
- `).trim())}function Uw(e,t){let r=ki(e),i=[];for(let n of t.operations){if(n.operation==="remove")continue;let a=n.operation==="rename"?n.to_id:n.id,o=r.requirements.get(a);if(!o)throw new M(`Native delta target Spec is missing requirement ${a} for ${n.operation}`);i.push(o.raw.trimEnd())}return i.length===0?"":`${i.join(`
203
+ `).trim())}function gb(e,t){let r=Fi(e),i=[];for(let n of t.operations){if(n.operation==="remove")continue;let a=n.operation==="rename"?n.to_id:n.id,o=r.requirements.get(a);if(!o)throw new z(`Native delta target Spec is missing requirement ${a} for ${n.operation}`);i.push(o.raw.trimEnd())}return i.length===0?"":`${i.join(`
191
204
 
192
205
  `)}
193
- `}function Uc(e,t,r,i){let n=`${"#".repeat(e)} Requirement: ${t}${r?.trim()?` ${r.trim()}`:""}`,a=Si(i).replace(/\n+$/u,"");return[n,"",...a.split(`
206
+ `}function Tl(e,t,r,i){let n=`${"#".repeat(e)} Requirement: ${t}${r?.trim()?` ${r.trim()}`:""}`,a=qi(i).replace(/\n+$/u,"");return[n,"",...a.split(`
194
207
  `),"",""].join(`
195
- `)}function Gf(e){return e.operation==="rename"?[e.id,e.to_id]:[e.id]}function Kc(e,t){if(e.operation==="rename"){if(!t)throw new M(`Rename target does not exist: ${e.id}`);return{id:e.to_id,level:t.level,title:e.title??t.title,body:e.body??t.body}}return{id:e.id,level:t?.level??2,title:e.title??t?.title,body:e.body??t?.body??""}}function cA(e,t,r){let i=ki(e),n=[...i.lines],a=i.requirements.get(t.id);if(!a)throw new M(`Requirement target disappeared: ${t.id}`);return n.splice(a.startLine,a.endLine-a.startLine,...r.split(`
208
+ `)}function Ff(e){return e.operation==="rename"?[e.id,e.to_id]:[e.id]}function $l(e,t){if(e.operation==="rename"){if(!t)throw new z(`Rename target does not exist: ${e.id}`);return{id:e.to_id,level:t.level,title:e.title??t.title,body:e.body??t.body}}return{id:e.id,level:t?.level??2,title:e.title??t?.title,body:e.body??t?.body??""}}function wT(e,t,r){let i=Fi(e),n=[...i.lines],a=i.requirements.get(t.id);if(!a)throw new z(`Requirement target disappeared: ${t.id}`);return n.splice(a.startLine,a.endLine-a.startLine,...r.split(`
196
209
  `)),n.join(`
197
- `)}function lA(e,t){let r=Si(e),i=r.length===0||r.endsWith(`
210
+ `)}function yT(e,t){let r=qi(e),i=r.length===0||r.endsWith(`
198
211
 
199
212
  `)?"":`
200
213
  `,n=`${r}${i}`;return`${n.endsWith(`
201
214
  `)||n.length===0?n:`${n}
202
- `}${t}`}function Kw(e,t){if(e.operation==="add"||e.operation==="modify"){let a=t.requirements.get(e.id);if(!a)return!1;let o=Kc(e,e.operation==="modify"?a:void 0);return a.raw===Uc(o.level,o.id,o.title,o.body)}if(e.operation==="remove")return!1;let r=t.requirements.get(e.to_id),i=t.requirements.get(e.id);if(!r||i)return!1;let n=Kc(e,{id:e.id,level:r.level,title:r.title,body:r.body,raw:r.raw,startLine:r.startLine,endLine:r.endLine});return r.raw===Uc(n.level,n.id,n.title,n.body)}function uA(e,t){let r=t.requirements.get(e.id);if(e.operation==="add"){if(r)throw new M(`Add target already exists: ${e.id}`);return}if(!r)throw new M(`Native delta target does not exist: ${e.id}`);if(e.expected_hash!==Qf(r.raw))throw new M(`Native delta ${e.operation} expected_hash does not match ${e.id}`);if(e.operation==="rename"&&t.requirements.has(e.to_id))throw new M(`Rename destination already exists: ${e.to_id}`)}function dA(e,t){if(e.base_requirements===void 0)return;let r=e.base_requirements,i=t.requirements;if(Object.keys(r).length!==i.size)throw new M("Native delta base_requirements must describe the complete total Spec baseline");for(let[n,a]of i)if(r[n]!==Qf(a.raw))throw new M(`Native delta base_requirements does not match requirement ${n}`)}function fA(e,t){let r=Gw(t.text);if(r!==wn("")&&e.legacy_hash!==r)throw new M("Native delta modifying a legacy total Spec requires a matching legacy_hash")}function pA(e){let t=Si(e.baselineMarkdown),r=[],i=[];for(let a of e.delta.operations){let o=ki(t),s=o.requirements.get(a.id);if(e.allowAlreadyApplied&&Kw(a,o)){i.push({id:a.id,operation:a.operation,status:"already-applied",targetIds:Gf(a)});continue}if(a.operation==="add"){if(s)throw new bi([a.id],`Native delta add conflicts with existing requirement ${a.id}`);let c=Kc(a,void 0);t=lA(t,Uc(c.level,c.id,c.title,c.body))}else{if(!s)throw new bi([a.id],`Native delta ${a.operation} target does not exist: ${a.id}`);if(a.expected_hash!==Qf(s.raw))throw new bi([a.id],`Native delta ${a.operation} conflicts with concurrent requirement ${a.id}`);let c=Kc(a,s);if(a.operation==="rename"&&ki(t).requirements.has(a.to_id))throw new bi([a.id,a.to_id],`Native delta rename destination already exists: ${a.to_id}`);if(a.operation==="remove"){let l=[...ki(t).lines];l.splice(s.startLine,s.endLine-s.startLine),t=l.join(`
203
- `)}else t=cA(t,s,Uc(c.level,c.id,c.title,c.body))}r.push(...Gf(a)),i.push({id:a.id,operation:a.operation,status:"changed",targetIds:Gf(a)})}let n=Si(t);return{markdown:n,base_hash:e.delta.base_hash,result_hash:wn(n),rebased:e.rebased,changedRequirementIds:[...new Set(r)],operationResults:i}}function Yw(e){let t=ki(e.baselineMarkdown);if(wn(t.text)!==e.delta.base_hash)throw new bi([e.delta.capability],`Native delta base hash does not match the current total Spec for ${e.delta.capability}`);fA(e.delta,t),dA(e.delta,t);for(let r of e.delta.operations)e.allowAlreadyApplied&&Kw(r,t)||uA(r,t);return pA({baselineMarkdown:t.text,delta:e.delta,allowAlreadyApplied:e.allowAlreadyApplied??!1,rebased:!1})}var Kf,Jf,Ww,eA,zw,tA,Fw,M,bi,Zf=A(()=>{"use strict";Kf=br(rr(),1),Jf="comet.native.delta.v1",Ww="delta.yaml",eA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zw=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,tA=/^[a-f0-9]{64}$/iu,Fw=512,M=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}},bi=class extends Error{code="native-delta-conflict";conflictIds;constructor(t,r){super(r),this.name="NativeDeltaConflictError",this.conflictIds=[...new Set(t)]}}});var Lt,qt,Ft,no=A(()=>{"use strict";Lt="comet.native.v3",qt="comet.native.v2",Ft="comet.native.v1"});import hA from"node:path";function so(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function ey(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function co(e){if(!Zw.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ty(e){if(!Zw.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function ry(e,t){if(e.length===0||hA.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function kA(e,t){let r=so(e,`spec_changes[${t}]`);if(ey(r,gA,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(ty(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&ry(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!tp.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!tp.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function SA(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function rp(e,t){if(ey(e,t,fr),typeof e.name!="string")throw new Error("Native change name is required");if(co(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!wA.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!yA.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(kA),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!NA.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&ry(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!SA(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function yn(e){let t=so(e,fr);if(t.schema!==Ft)throw new Error(`Expected ${Ft}`);return{schema:Ft,...rp(t,mA)}}function oo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ep(e,t,r){if(e===null)return null;let i=typeof e=="string"?bA.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function EA(e){if(e==null)return null;if(typeof e!="string"||!tp.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function xA(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Nn(e){let t=so(e,fr);if(t.schema!==qt)throw new Error(`Expected ${qt}`);if(oo(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${qt} minimum_runtime_version must be 2`);return{schema:qt,minimum_runtime_version:2,revision:oo(t.revision,"Native v2 revision"),...rp(t,Qw)}}function Ei(e){let t=so(e,fr);if(t.schema!==Lt){if(t.schema===Ft||t.schema===qt){let o=t.schema===Ft?yn(t):Nn(t);throw new ao(o.name,o.schema)}throw new Vt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=oo(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Vt(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=oo(t.revision,"Native revision"),n=rp(t,vA),a=EA(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Lt,minimum_runtime_version:3,revision:i,verification_protocol:xA(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:ep(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:ep(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:ep(t.partial_allowance,"Native partial_allowance","allowances")}}function ip(e){let t=so(e,fr);if(t.schema===Ft){let n=yn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Lt}`}}if(t.schema===qt){let n=Nn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Lt}`}}if(t.schema!==Lt){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Vt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=oo(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Vt(t.schema,r).message};let i=Ei(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var Xw,mA,Qw,vA,gA,wA,yA,NA,fr,tp,Zw,bA,ao,Vt,Yc=A(()=>{"use strict";no();Xw=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],mA=new Set(Xw),Qw=new Set([...Xw,"minimum_runtime_version","revision"]),vA=new Set([...Qw,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),gA=new Set(["capability","operation","source","base_hash"]),wA=new Set(["shape","build","verify","archive"]),yA=new Set(["implicit","confirmed"]),NA=new Set(["pending","pass","fail"]),fr="comet-state.yaml",tp=/^[a-f0-9]{64}$/u,Zw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bA=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,ao=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Vt=class extends Error{constructor(r,i){super(r!==Lt||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});function CA(e,t){return np[e][t]}function ap(e,t){return ny[e][t]??ay[e][t]}function Xc(e){return oy.get(e.trim().toLocaleLowerCase("en-US"))??null}function Qc(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${CA(e,r)}
204
- `).join(`
205
- `)}function We(e,t,r){return e==="zh-CN"?r:t}var np,ny,ay,oy,iy,xi=A(()=>{"use strict";np={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},ny={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},ay={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},oy=new Map,iy=new Map;for(let e of Object.keys(np)){for(let[t,r]of Object.entries(np[e]))oy.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(ny[e]))iy.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(ay[e]))iy.set(r.toLocaleLowerCase("en-US"),t)}});function ly(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function sy(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function cy(e){return e.includes("-->")||e.includes("--!>")}function*Zc(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
215
+ `}${t}`}function wb(e,t){if(e.operation==="add"||e.operation==="modify"){let a=t.requirements.get(e.id);if(!a)return!1;let o=$l(e,e.operation==="modify"?a:void 0);return a.raw===Tl(o.level,o.id,o.title,o.body)}if(e.operation==="remove")return!1;let r=t.requirements.get(e.to_id),i=t.requirements.get(e.id);if(!r||i)return!1;let n=$l(e,{id:e.id,level:r.level,title:r.title,body:r.body,raw:r.raw,startLine:r.startLine,endLine:r.endLine});return r.raw===Tl(n.level,n.id,n.title,n.body)}function bT(e,t){let r=t.requirements.get(e.id);if(e.operation==="add"){if(r)throw new z(`Add target already exists: ${e.id}`);return}if(!r)throw new z(`Native delta target does not exist: ${e.id}`);if(e.expected_hash!==zf(r.raw))throw new z(`Native delta ${e.operation} expected_hash does not match ${e.id}`);if(e.operation==="rename"&&t.requirements.has(e.to_id))throw new z(`Rename destination already exists: ${e.to_id}`)}function NT(e,t){if(e.base_requirements===void 0)return;let r=e.base_requirements,i=t.requirements;if(Object.keys(r).length!==i.size)throw new z("Native delta base_requirements must describe the complete total Spec baseline");for(let[n,a]of i)if(r[n]!==zf(a.raw))throw new z(`Native delta base_requirements does not match requirement ${n}`)}function kT(e,t){let r=vb(t.text);if(r!==Vn("")&&e.legacy_hash!==r)throw new z("Native delta modifying a legacy total Spec requires a matching legacy_hash")}function ST(e){let t=qi(e.baselineMarkdown),r=[],i=[];for(let a of e.delta.operations){let o=Fi(t),s=o.requirements.get(a.id);if(e.allowAlreadyApplied&&wb(a,o)){i.push({id:a.id,operation:a.operation,status:"already-applied",targetIds:Ff(a)});continue}if(a.operation==="add"){if(s)throw new Li([a.id],`Native delta add conflicts with existing requirement ${a.id}`);let c=$l(a,void 0);t=yT(t,Tl(c.level,c.id,c.title,c.body))}else{if(!s)throw new Li([a.id],`Native delta ${a.operation} target does not exist: ${a.id}`);if(a.expected_hash!==zf(s.raw))throw new Li([a.id],`Native delta ${a.operation} conflicts with concurrent requirement ${a.id}`);let c=$l(a,s);if(a.operation==="rename"&&Fi(t).requirements.has(a.to_id))throw new Li([a.id,a.to_id],`Native delta rename destination already exists: ${a.to_id}`);if(a.operation==="remove"){let l=[...Fi(t).lines];l.splice(s.startLine,s.endLine-s.startLine),t=l.join(`
216
+ `)}else t=wT(t,s,Tl(c.level,c.id,c.title,c.body))}r.push(...Ff(a)),i.push({id:a.id,operation:a.operation,status:"changed",targetIds:Ff(a)})}let n=qi(t);return{markdown:n,base_hash:e.delta.base_hash,result_hash:Vn(n),rebased:e.rebased,changedRequirementIds:[...new Set(r)],operationResults:i}}function yb(e){let t=Fi(e.baselineMarkdown);if(Vn(t.text)!==e.delta.base_hash)throw new Li([e.delta.capability],`Native delta base hash does not match the current total Spec for ${e.delta.capability}`);kT(e.delta,t),NT(e.delta,t);for(let r of e.delta.operations)e.allowAlreadyApplied&&wb(r,t)||bT(r,t);return ST({baselineMarkdown:t.text,delta:e.delta,allowAlreadyApplied:e.allowAlreadyApplied??!1,rebased:!1})}var Mf,Lf,fb,uT,hb,dT,ub,z,Li,Gf=T(()=>{"use strict";Mf=hr(Gt(),1),Lf="comet.native.delta.v1",fb="delta.yaml",uT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hb=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,dT=/^[a-f0-9]{64}$/iu,ub=512,z=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}},Li=class extends Error{code="native-delta-conflict";conflictIds;constructor(t,r){super(r),this.name="NativeDeltaConflictError",this.conflictIds=[...new Set(t)]}}});var Kt,Yt,Xt,Bo=T(()=>{"use strict";Kt="comet.native.v3",Yt="comet.native.v2",Xt="comet.native.v1"});import ET from"node:path";function qo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Sb(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Mo(e){if(!kb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Eb(e){if(!kb.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function xb(e,t){if(e.length===0||ET.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function TT(e,t){let r=qo(e,`spec_changes[${t}]`);if(Sb(r,CT,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Eb(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&xb(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Uf.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Uf.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function $T(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Kf(e,t){if(Sb(e,t,xr),typeof e.name!="string")throw new Error("Native change name is required");if(Mo(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!PT.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!_T.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(TT),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!AT.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&xb(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!$T(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Wn(e){let t=qo(e,xr);if(t.schema!==Xt)throw new Error(`Expected ${Xt}`);return{schema:Xt,...Kf(t,xT)}}function Fo(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Jf(e,t,r){if(e===null)return null;let i=typeof e=="string"?IT.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function jT(e){if(e==null)return null;if(typeof e!="string"||!Uf.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function OT(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function zn(e){let t=qo(e,xr);if(t.schema!==Yt)throw new Error(`Expected ${Yt}`);if(Fo(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Yt} minimum_runtime_version must be 2`);return{schema:Yt,minimum_runtime_version:2,revision:Fo(t.revision,"Native v2 revision"),...Kf(t,Nb)}}function Mi(e){let t=qo(e,xr);if(t.schema!==Kt){if(t.schema===Xt||t.schema===Yt){let o=t.schema===Xt?Wn(t):zn(t);throw new Lo(o.name,o.schema)}throw new Qt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Fo(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Qt(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Fo(t.revision,"Native revision"),n=Kf(t,RT),a=jT(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Kt,minimum_runtime_version:3,revision:i,verification_protocol:OT(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Jf(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Jf(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Jf(t.partial_allowance,"Native partial_allowance","allowances")}}function Yf(e){let t=qo(e,xr);if(t.schema===Xt){let n=Wn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Kt}`}}if(t.schema===Yt){let n=zn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Kt}`}}if(t.schema!==Kt){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Qt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Fo(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Qt(t.schema,r).message};let i=Mi(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var bb,xT,Nb,RT,CT,PT,_T,AT,xr,Uf,kb,IT,Lo,Qt,jl=T(()=>{"use strict";Bo();bb=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],xT=new Set(bb),Nb=new Set([...bb,"minimum_runtime_version","revision"]),RT=new Set([...Nb,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),CT=new Set(["capability","operation","source","base_hash"]),PT=new Set(["shape","build","verify","archive"]),_T=new Set(["implicit","confirmed"]),AT=new Set(["pending","pass","fail"]),xr="comet-state.yaml",Uf=/^[a-f0-9]{64}$/u,kb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,IT=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Lo=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Qt=class extends Error{constructor(r,i){super(r!==Kt||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});function Cb(e,t){return Xf[e][t]}function Zf(e,t){return Pb[e][t]??_b[e][t]}function Ol(e){return Ab.get(e.trim().toLocaleLowerCase("en-US"))??null}function HT(e){return Vi[e].section}function DT(e,t){return Vi[e].subsections[t]}function $b(e){return`${Vi.en.subsections[e]}/${Vi["zh-CN"].subsections[e]}`}function jb(e){return Ib.has(e.trim().toLocaleLowerCase("en-US"))}function Ob(e){return Tb.get(e.trim().toLocaleLowerCase("en-US"))??null}function Hl(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>{if(i!=="scope")return`# ${Cb(e,i)}
217
+ `;let n=[`# ${Cb(e,i)}
218
+ `];n.push(`## ${HT(e)}
219
+ `);for(let a of Qf)n.push(`### ${DT(e,a)}
220
+ `);return n.join(`
221
+ `)}).join(`
222
+ `)}function Xe(e,t,r){return e==="zh-CN"?r:t}var Qf,Xf,Pb,_b,Ab,Rb,Ib,Tb,Vi,Wi=T(()=>{"use strict";Qf=["created","modified","deleted","notCreated"],Xf={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},Pb={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},_b={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},Ab=new Map,Rb=new Map,Ib=new Set,Tb=new Map,Vi={en:{section:"Directory structure",subsections:{created:"Created",modified:"Modified",deleted:"Deleted",notCreated:"Not created"}},"zh-CN":{section:"目录结构",subsections:{created:"新建",modified:"修改",deleted:"删除",notCreated:"明确不建"}}};for(let e of Object.keys(Xf)){for(let[t,r]of Object.entries(Xf[e]))Ab.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Pb[e]))Rb.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(_b[e]))Rb.set(r.toLocaleLowerCase("en-US"),t)}for(let e of Object.keys(Vi)){Ib.add(Vi[e].section.toLocaleLowerCase("en-US"));for(let[t,r]of Object.entries(Vi[e].subsections))Tb.set(r.toLocaleLowerCase("en-US"),t)}});function Bb(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function Hb(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function Db(e){return e.includes("-->")||e.includes("--!>")}function*Dl(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
206
223
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
207
- `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=sy(l,t);else if(r)cy(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let f=sy(l,null);if(f!==null)t=f;else{let d=l.trimStart();if(d.startsWith("<!--")&&!cy(d))r=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);p&&n.has(p[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(d)&&(i=p[1])}}}if(c===-1)break;o=c+1}}function lo(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function uy(e,t,r,i=[],n="content-hash"){let a=lo(r),o=t.replaceAll("\\","/").trim(),s=i.map(lo);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${T(RA,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function dy(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function PA(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Zc(e)){n=s+1;let c=o?ly(a):null;c?.level===1&&(Xc(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function op(e,t="brief.md",r=el.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=PA(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:f}of Zc(e)){if(f<n.start||f>=n.end)continue;let d=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(d===null)continue;let p=d[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:f}of Zc(e)){if(f<n.start||f>=n.end)continue;let d=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;d&&d[1].length===a?(c(),s=[d[2]]):s!==null&&s.push(l)}return c(),dy(o.map(l=>uy("brief-example",t,l.join(`
208
- `),[],i)),"Brief",i)}function sp(e,t="spec.md",r=el.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(uy("spec-scenario",t,[o.title,...o.body].join(`
209
- `),o.context,i)),o=null}};for(let{line:c,body:l}of Zc(e)){let u=l?ly(c):null,f=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(f){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let d=lo(f[1]);if(d.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:d,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),dy(n,"Specification",i)}var RA,wL,el,tl=A(()=>{"use strict";xi();fe();RA="comet.native.acceptance.v1",wL=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),el=Object.freeze({maxCriteria:1024})});import fy from"node:path";function py(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||fy.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||fy.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function AA(e,t){return e.localeCompare(t,"en")}function rl(e){let t=py(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>AA(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=op(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=py(a.source,`Native spec source for ${a.capability}`);i.push(...sp(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=lo(a.text);let o=a.text;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function hy(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!_A.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function my(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var _A,il=A(()=>{"use strict";tl();_A=/^A[1-9]\d*$/u});function IA(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function J(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(IA(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var Fr=A(()=>{"use strict"});import TA from"node:path";function BA(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function LA(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function qA(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function FA(e){return e.schema===Ft?yn(e):e.schema===qt?Nn(e):Ei(e)}function VA(e){return TA.posix.normalize(e.replaceAll("\\","/"))}function MA(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:VA(t.source)})}function WA(e){return e==="shape"?"shape":"build"}function zA(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function JA(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function vy(e){let t=FA(e.state);hy(e.acceptance);let r=WA(t.phase),i=r==="shape"?0:1,n=LA(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return B({schema:fi,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:MA(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:zA(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:J(JA(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:bc(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function cp(e){let t=BA(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!jA.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==nl)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!OA.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!$A.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!DA.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!HA.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:nl,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:qA(t.createdAt,"Native portable migration transaction createdAt")}}function gy(e){switch(cp(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var nl,jA,$A,OA,HA,DA,lp=A(()=>{"use strict";Yc();il();ut();Fr();cn();no();nl="comet.native.portable-migration.v1",jA=new Set(["schema","id","change","fromSchema","status","createdAt"]),$A=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,OA=/^[a-z0-9][a-z0-9-]{7,127}$/u,HA=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),DA=new Set([Ft,qt,Lt])});import dp from"node:path";function ky(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Sy(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function up(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function yy(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function eI(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=ky(e,r);if(Sy(i,ZA,r),typeof i.capability!="string"||!by.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation,a=i.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(d=>d==="."||d==="..")))throw new Error(`${r}.delta_source is invalid`);let o=up(i.base_hash,`${r}.base_hash`),s=yy(i.delta_content,`${r}.delta_content`),c=yy(i.source_content,`${r}.source_content`),l=up(i.expected_target_hash,`${r}.expected_target_hash`),u=up(i.result_hash,`${r}.result_hash`),f=a!==void 0;if(f&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(f&&(s==null||c===void 0||c===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!f&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(f){let d=io(s);if(d.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(d.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(ur(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(ur(c)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...l===void 0?{}:{expected_target_hash:l}}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(d=>d==="."||d===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||ur(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function tI(e){let t=ky(e,"Native portable Archive transaction");if(Sy(t,QA,"Native portable Archive transaction"),t.schema!==wy)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!KA.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!by.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!YA.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!XA.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(eI);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:wy,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function al(e){let t=GA.exec(e);if(t)return{kind:"archive",change:t[1]};let r=UA.exec(e);return r?{kind:"migration",change:r[1]}:null}function ol(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=al(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return dp.join(e.transactionsDir,r)}async function fp(e,t){let r=al(t);if(!r)return null;let i=await Q({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=dp.join(e.transactionsDir,t);if(r.kind==="archive"){let s=tI(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=cp(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function sl(e,t){let r=ol(e,t);try{return await fp(e,dp.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Ey(e){return e.kind==="archive"||e.journal.status!=="committed"}var wy,Ny,GA,UA,KA,YA,XA,QA,ZA,by,cl=A(()=>{"use strict";nt();Zf();lp();wy="comet.native.archive-transaction.v4",Ny="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",GA=new RegExp(`^portable-archive-(${Ny})\\.json$`,"u"),UA=new RegExp(`^portable-migration-(${Ny})\\.json$`,"u"),KA=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,YA=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,XA=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),QA=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),ZA=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),by=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as rI}from"node:crypto";import{constants as ll,promises as Et}from"node:fs";import xt from"node:path";function dl(e,t){let r=xt.relative(e,t);return r===""||!xt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${xt.sep}`)}function iI(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function nI(e,t){return Z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function aI(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ul(e,t){return Z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function pp(e,t){let r=await Et.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Et.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function oI(e,t,r){let i=xt.resolve(e),n=xt.resolve(t);if(!dl(i,n))throw new Error(`${r} is outside its managed root`);let a=[await pp(i,r)],o=i;for(let s of xt.relative(i,n).split(xt.sep).filter(Boolean)){await Ci(a,r),o=xt.join(o,s);let c=await pp(o,r);if(!dl(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ci(a,r),a}async function Ci(e,t){for(let r of e){let i=await Et.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!nI(r,i)||await Et.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function sI(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let o=t===null?a.length:t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,t!==null&&n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function uo(e){let t=e.maxBytes===null?null:iI(e.maxBytes),r=xt.resolve(e.file),i=await oI(e.root,xt.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>pp(xt.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Ci(i,e.label);let a=await Et.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=aI(a),s=await Et.realpath(r);if(!dl(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>dl(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?ll.O_RDONLY:ll.O_RDONLY|ll.O_NOFOLLOW|ll.O_NONBLOCK,l=await Et.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[f,d]=await Promise.all([Et.lstat(r),Et.realpath(r)]);if(await Ci(i,e.label),await Ci(n,e.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!ul(o,u)||!ul(o,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await sI(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([l.stat(),Et.lstat(r),Et.realpath(r)]);if(await Ci(i,e.label),await Ci(n,e.label),!h.isFile()||h.isSymbolicLink()||g!==s||!ul(o,m)||!ul(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:rI("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var Mt=A(()=>{"use strict";ne();Dt()});import pr from"path";import{TextDecoder as lI}from"util";function pl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hl(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Py(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function hp(e,t){if(typeof e!="string"||e.length===0||pr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function fl(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function xy(e,t){if(hp(e,t),e.includes("\\")||e!==pr.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function mI(e,t){let r=pl(e,`transaction operations[${t}]`);if(hl(r,dI,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);hp(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&hp(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function _y(e){let t=pl(e,"Native Archive transaction journal");if(hl(t,fI,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Ry.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Py(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(fl(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=pl(s,`Archive transaction operations[${c}]`);if(hl(l,pI,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);xy(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&xy(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&fl(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(fl(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);fl(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function vI(e){let t=pl(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return _y(t);if(hl(t,uI,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Ry.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!pr.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!pr.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Py(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(mI),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function gI(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return pr.join(e.transactionsDir,t)}function Ay(e,t){let r=gI(e,t);return{directory:r,journal:pr.join(r,"transaction.json"),events:pr.join(r,"events.jsonl"),staged:pr.join(r,"staged"),backups:pr.join(r,"backups")}}async function vp(e,t){let r=Ay(e,t);return await Promise.all(Object.values(r).map(i=>z(e.runtimeDir,i))),r}async function gp(e,t,r={}){let i=await vp(e,t),n=await uo({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(hI.decode(n.bytes)),o=vI(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var uI,dI,fI,pI,Ry,hI,ml=A(()=>{"use strict";ne();te();Mt();uI=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),dI=new Set(["id","type","source","target","staged","backup"]),fI=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),pI=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Ry=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),hI=new lI("utf-8",{fatal:!0})});import{promises as wI}from"fs";import yI from"path";async function NI(e,t,r){let i;try{i=await wI.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await gp(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(al(n.name))try{let a=await fp(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Ey(a))return!0}catch{return!0}return!1}async function bI(e,t){let r=Date.now()+5e3,i=yI.join(e.locksDir,"root-move.lock");for(;;)try{return await zc(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Lw(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await qw(e,i,o);if(s.status==="removed"||s.status==="missing")continue;throw n}if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function _(e,t,r,i){let n=await bI(e,t);try{if(await wc(e.projectRoot),await NI(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Jc(n)}catch(a){process.stderr.write(`[comet] warning: could not release Native mutation lock ${n.file} (${a.message}); run comet native doctor --repair if commands start failing
210
- `)}}}var le=A(()=>{"use strict";st();ro();cl();ml()});import{createHash as kI}from"node:crypto";import{promises as wp}from"node:fs";import Iy from"node:os";import Ct from"node:path";function bn(e){return{id:e.id,name:e.name,status:"planned",repeatable:e.repeatable,executionCount:0,argvDisplay:eo(e.argv),cwdRef:e.cwdRef,exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}}function vl(e,t){return{...e,name:t.name,status:t.status,argvDisplay:[...t.argvDisplay],cwdRef:t.cwdRef,exitCode:t.exitCode,signal:t.signal,timedOut:t.timedOut,durationMs:t.durationMs,startedAt:t.startedAt,completedAt:t.completedAt,logRef:t.logRef}}function gl(e){if(e.status!=="passed"&&e.status!=="failed"&&e.status!=="interrupted"||e.startedAt===null||e.completedAt===null||e.logRef===null)throw new Error(`Native Supervisor check ${e.id} has incomplete Runtime evidence`);return{id:e.id,name:e.name,argvDisplay:[...e.argvDisplay],cwdRef:e.cwdRef,status:e.status,exitCode:e.exitCode,signal:e.signal,timedOut:e.timedOut,durationMs:e.durationMs,startedAt:e.startedAt,completedAt:e.completedAt,repeatable:e.repeatable,logRef:e.logRef}}function SI(e,t){let r=Ct.relative(Ct.resolve(e),Ct.resolve(t));return r===""||!Ct.isAbsolute(r)&&!r.startsWith(`..${Ct.sep}`)}function Wt(e,t){try{return I(e,t)}catch(r){return`unavailable:${r instanceof Error?r.message:String(r)}`}}async function Ty(e){let t=Wt(e,["ls-files","--others","--exclude-standard","-z"]);return t===null||t.startsWith("unavailable:")?[{error:t}]:Promise.all(t.split("\0").filter(Boolean).sort().map(async r=>{let i=r.replaceAll("\\","/"),n=Ct.resolve(e,...i.split("/"));if(!SI(e,n))return{path:i,error:"escaped"};try{let a=await wp.lstat(n);if(a.isSymbolicLink())return{path:i,kind:"symlink",target:await wp.readlink(n)};if(!a.isFile())return{path:i,kind:"other",size:a.size};let o=await wp.readFile(n);return{path:i,kind:"file",size:a.size,digest:kI("sha256").update(o).digest("hex")}}catch(a){return{path:i,error:a instanceof Error?a.message:String(a)}}}))}async function EI(e){let t=Wt(e,["ls-files","--stage","-z"]);if(t===null||t.startsWith("unavailable:"))return[{error:t}];let r=t.split("\0").map(i=>/^160000\s+[^\s]+\s+\d+\t(.+)$/u.exec(i)?.[1]).filter(i=>i!==void 0).sort();return Promise.all(r.map(async i=>({path:i.replaceAll("\\","/"),head:Wt(Ct.resolve(e,i),["rev-parse","HEAD"]),status:Wt(Ct.resolve(e,i),["status","--porcelain=v1","-z","--untracked-files=all"]),diff:Wt(Ct.resolve(e,i),["diff","--binary","HEAD","--submodule=diff"]),untracked:await Ty(Ct.resolve(e,i))})))}async function wl(e){let t=Object.entries(process.env).map(([r,i])=>[r,i??null]).sort(([r],[i])=>r.localeCompare(i));return T("comet.native.supervisor-check-input.v2",{kind:e.kind,parent:e.parent,child:e.child,runId:e.runId,projectRoot:Ct.resolve(e.projectRoot),candidateCommit:e.candidateCommit,integrationCommit:e.integrationCommit??null,contractHash:e.contractHash??null,plans:e.plans,materials:e.materials,machineId:Iy.hostname(),runtime:{execPath:process.execPath,version:process.version,platform:process.platform,arch:process.arch,environment:t},git:{head:Wt(e.projectRoot,["rev-parse","HEAD"]),branch:Wt(e.projectRoot,["branch","--show-current"]),status:Wt(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none"]),diff:Wt(e.projectRoot,["diff","--binary","HEAD","--submodule=diff"]),stagedDiff:Wt(e.projectRoot,["diff","--cached","--binary","--submodule=diff"]),submodules:await EI(e.projectRoot),untracked:await Ty(e.projectRoot)}})}function yl(){return Iy.hostname()}var yp=A(()=>{"use strict";rt();gn();fe()});import{createHash as xI}from"node:crypto";import{lstatSync as CI,readFileSync as jy,promises as $y}from"node:fs";import Nl from"node:path";function Dy(e){try{if(I(e,["ls-files","--",bl]))return!1;let t=Nl.join(e,bl),r=CI(t);return!r.isFile()||r.isSymbolicLink()?!1:JSON.parse(jy(Oy(e),"utf8")).hash===Hy(jy(t))}catch{return!1}}async function By(e){let t=Nl.join(e,bl),r;try{r=await $y.readFile(t)}catch(n){if(n.code==="ENOENT")return;throw n}let i=Oy(e);await $y.mkdir(Nl.dirname(i),{recursive:!0}),await we(i,{hash:Hy(r)},{containedRoot:e})}function zt(e,t=[]){return ka(e).every(r=>t.some(i=>r===i||r.startsWith(`${i}/`))||r===bl&&Dy(e))}var bl,Oy,Hy,kn=A(()=>{"use strict";rt();ne();bl=".comet/config.yaml",Oy=e=>Nl.join(e,".comet","runtime","native","workspace-config.json"),Hy=e=>xI("sha256").update(e).digest("hex")});import{createHash as AI}from"crypto";function Xe(e){return AI("sha256").update(e).digest("hex")}var Jt=A(()=>{"use strict"});import Vy from"path";function Sl(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function KI(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function YI(e,t){return Xe(`comet.native.snapshot-policy.v1
211
- ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function bp(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function XI(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function My(e){let t=gc(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?XI(n):void 0;if(a&&!a())return!1;let o=bp(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=bp(r,c,a),o===null||o.size===0)return!1}return bp(r,o,a)?.has(r.length)??!1}}function QI(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>gc(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>gc(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let i=YI(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(My),excludeMatchers:r.map(My),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function ht(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mt(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function En(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Gt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Jy(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=Vy.posix.normalize(e);if(r!==e||Vy.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function ZI(e,t){let r=ht(e,`Native snapshot entry ${t}`);mt(r,VI,`Native snapshot entry ${t}`);let i=Jy(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!El.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:Gt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!UI.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function eT(e,t){let r=ht(e,`Native snapshot omission ${t}`);if(mt(r,MI,`Native snapshot omission ${t}`),!JI.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!GI.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Jy(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Gt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function tT(e){let t=ht(e,"Native snapshot omission overflow");if(mt(t,WI,"Native snapshot omission overflow"),typeof t.hash!="string"||!El.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:En(t.count,"Native snapshot omission overflow count")}}function Sn(e,t){let r=ht(e,t);if(mt(r,LI,t),typeof r.hash!="string"||!El.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=Gt(r.recordCount,`${t} recordCount`),n=Gt(r.storedRecordCount,`${t} storedRecordCount`),a=Gt(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Wy(e){let t=ht(e,"Native Git selection evidence");if(mt(t,BI,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=Sn(t.stageBefore,"Native Git selection stageBefore"),i=Sn(t.combined,"Native Git selection combined"),n=Sn(t.stageAfter,"Native Git selection stageAfter"),a=Sn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Sn(t.finalCombined,"Native Git selection finalCombined"),s=Sn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(f=>f.overflow),l=!Sl(r,n)||!Sl(n,a)||!Sl(i,o)||!Sl(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function zy(e,t){let r=ht(e,t);if(mt(r,FI,t),typeof r.hash!="string"||!El.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=Gt(r.visitedNodeCount,`${t} visitedNodeCount`),n=Gt(r.recordCount,`${t} recordCount`),a=Gt(r.storedRecordCount,`${t} storedRecordCount`),o=Gt(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function rT(e){let t=ht(e,"Native physical selection evidence");if(mt(t,qI,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=zy(t.before,"Native physical selection before"),i=zy(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!KI(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function kp(e){let t=ht(e,"Native content snapshot manifest");if(mt(t,jI,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!zI.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let N=ht(t.capture,"Native content snapshot capture");if(mt(N,HI,"Native content snapshot capture"),N.provider!=="git"&&N.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=N.gitSelection===void 0?void 0:Wy(N.gitSelection),k=N.physicalSelection===void 0?void 0:rT(N.physicalSelection),E=null;if(N.projection!==void 0){let C=ht(N.projection,"Native content snapshot projection");if(mt(C,DI,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",...C.selection===void 0?{}:{selection:Wy(C.selection)}}}if(N.provider==="git"){if(k||E)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(k&&E)throw new Error("Native physical-tree capture cannot combine selection and projection");r=E?{provider:"physical-tree",projection:E}:{provider:"physical-tree",...k?{physicalSelection:k}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=ht(t.limits,"Native content snapshot limits");mt(i,$I,"Native content snapshot limits");let n={maxFiles:En(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:En(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:En(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:En(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:En(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let N=ht(t.policy,"Native snapshot policy");if(mt(N,OI,"Native snapshot policy"),N.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(N.include)||!Array.isArray(N.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=QI({include:N.include,exclude:N.exclude,hash:N.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(ZI),s=t.omitted.map(eT),c=Gt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:tT(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(N=>N.size>n.maxFileBytes)||o.reduce((N,x)=>N+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(N=>N.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>TI||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let f=s.filter(N=>N.reason==="git-enumeration-limit"),d=s.filter(N=>N.reason==="git-selection-changed");for(let N of[...f,...d])if(N.path!=="."||N.size!==null||N.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(f.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(m!==(f.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let g=s.filter(N=>N.reason==="physical-enumeration-limit"),v=s.filter(N=>N.reason==="physical-selection-changed");for(let N of[...g,...v])if(N.path!=="."||N.size!==null||N.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(g.length>1||v.length>1)throw new Error("Native physical selection omissions must not be duplicated");let w=r?.physicalSelection,y=w?.status==="overflow"||w?.status==="overflow-and-changed",b=w?.status==="changed"||w?.status==="overflow-and-changed";if(y!==(g.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(b!==(v.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}var Lq,TI,jI,$I,OI,HI,DI,BI,LI,qI,FI,VI,MI,WI,zI,JI,GI,El,UI,qq,Fq,Vq,Mq,Wq,po=A(()=>{"use strict";ne();st();Jt();Dt();te();Mt();Sa();Lq={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},TI=1e3,jI=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),$I=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),OI=new Set(["schema","include","exclude","hash"]),HI=new Set(["provider","gitSelection","physicalSelection","projection"]),DI=new Set(["provider","selection"]),BI=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),LI=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),qI=new Set(["schema","status","before","after"]),FI=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),VI=new Set(["path","hash","size","type","gitObjectId"]),MI=new Set(["path","size","type","reason"]),WI=new Set(["ref","hash","count"]),zI=new Set(["change-created","legacy-migration","explicit"]),JI=new Set(["file","directory","other"]),GI=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),El=/^[a-f0-9]{64}$/u,UI=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,qq=64*1024,Fq=64*1024,Vq={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Mq={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};Wq=(1n<<256n)-1n});import{createHash as eN}from"node:crypto";import Gy from"path";function Re(e,t){return e<t?-1:e>t?1:0}function Ep(e){if(!Cp.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function cT(e,t){return e===t?0:e===null?-1:t===null?1:Re(e,t)}function Wr(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let r=Gy.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||Gy.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function iN(e,t){return e==="."?e:Wr(e,t)}function xn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function lT(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:Wr(e.path,`${t} path`),hash:e.hash,size:xn(e.size,`${t} size`),type:"file"}}function uT(e,t){return{path:iN(e.path,`${t} path`),size:e.size===null?null:xn(e.size,`${t} size`),type:e.type,reason:e.reason}}function dT(e,t){return Re(e.path,t.path)||Re(e.hash,t.hash)||e.size-t.size}function fT(e,t){return Re(e.path,t.path)||Re(e.reason,t.reason)||Re(e.type,t.type)||(e.size??-1)-(t.size??-1)}function vo(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
212
- `,"utf8")}function Mr(e,t,r){let i=`${t}
213
- ${tc(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function pT(e){if(vo(e)<=Pi)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=eN("sha256");a.update(`${aT}
214
- `),e.omissionOverflow&&Mr(a,"existing-overflow",e.omissionOverflow);let o=(d,p)=>{p||(i+=1),n+=1,Mr(a,"omission",d)},s=d=>{i+=1,n+=1,Mr(a,"entry",d)},c=()=>{for(let d=r.length-1;d>=0;d-=1){let p=r[d];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return r.splice(d,1),p}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;vo(u)>Pi;){if(r.filter(p=>p.reason!=="git-enumeration-limit"&&p.reason!=="git-selection-changed"&&p.reason!=="physical-enumeration-limit"&&p.reason!=="physical-selection-changed").length>0){let p=Math.max(1,Math.ceil(r.length/4));for(let m=0;m<p;m+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-p))s(m)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let f=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${f}`,hash:f,count:n}}}function hT(e){let t=kp(e),r=t.entries.map((n,a)=>lT(n,`Snapshot entry ${a}`));if(r.sort(dT),new Set(r.map(n=>n.path)).size!==r.length)throw new Error("Snapshot entries must not contain duplicate paths");let i=t.omitted.map((n,a)=>uT(n,`Snapshot omission ${a}`));return i.sort(fT),pT({schema:tN,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:r,omitted:i,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function Cl(e){let t=new Map;for(let[r,i]of e.entries()){if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${r} kind is invalid`);let n={path:Wr(i.path,`Declared artifact ${r} path`),kind:i.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((r,i)=>Re(r.path,i.path)||Re(r.kind,i.kind))}function go(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Uy(e){return e?{hash:e.hash,size:e.size}:null}function nN(e,t,r){let i=0,n=0;for(;i<e.entries.length||n<t.entries.length;){let a=e.entries[i],o=t.entries[n],s=a===void 0?1:o===void 0?-1:Re(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(i+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&r({path:u,kind:c?l?"modified":"removed":"added",before:Uy(c),after:Uy(l)})}}function mT(e,t){return{...e,attributedTo:t.filter(r=>go(r,e.path))}}function hr(e,t){return{id:`scope:${T(iT,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function vT(e,t){let r=t.omitted.map(i=>hr({kind:"snapshot-omission",source:e,path:i.path,evidence:{reason:i.reason,size:i.size,type:i.type}},`${e} snapshot omitted ${i.path}: ${i.reason}`));return t.complete||r.push(hr({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(hr({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),r}function Ky(e,t){return vT(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function xp(e,t){return Re(e.kind,t.kind)||Re(e.source,t.source)||cT(e.path,t.path)||Re(e.id,t.id)}function gT(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(xp)}function aN(e){return[...new Set(e.map((t,r)=>Wr(t,`Git path ${r}`)))].sort(Re)}function Yy(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function wT(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function oN(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=aN(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Yy(e.baseCommit,"Native external drift base commit"),targetBranch:wT(e.targetBranch,"Native external drift target branch"),targetCommit:Yy(e.targetCommit,"Native external drift target commit"),paths:t}}function yT(e){if(typeof e.contractHash!="string"||!Cp.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Cl(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:aN(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:oN(e.externalDrift)}}}function NT(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,u=!1,f=0,d=0;return nN(e,t,p=>{let m=r.some(h=>go(h,p.path));if(f+=1,c.push(p.path),!m&&!n?.has(p.path)&&(d+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length<oT){let h=mT(p,r),g=vo(h);l+g<=Pi?(a.push(h),l+=g):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:f,totalUnattributed:d}}function sN(e,t){return hr({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function bT(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let r={changes:xn(Number(t[1]),"Scope overflow change count"),unresolved:xn(Number(t[2]),"Scope overflow unresolved count"),unattributed:xn(Number(t[3]),"Scope overflow unattributed count")},i=Ri(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(sN(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function kT(e){let t=eN("sha256");t.update(`${nT}
215
- `);let r=0;nN(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){Mr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)go(o,n.path)&&(a+=1,Mr(t,"change-attribution",o));Mr(t,"change-end",{attributionCount:a}),a===0&&Mr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&Mr(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function ST(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=NT(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let x=new Set(r.externalDrift.paths),k=new Set(o.changePaths),E=r.externalDrift.paths.filter(C=>!k.has(C)||n.some(H=>go(H,C)));if(E.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${E.slice(0,8).join(", ")}`);if(x.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=T(ho,e),c=T(ho,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[x,k]of[["baseline",e],["current",t]])for(let E of k.omitted){if(l.length>=sT)break;l.push(hr({kind:"snapshot-omission",source:x,path:E.path,evidence:{reason:E.reason,size:E.size,type:E.type}},`${x} snapshot omitted ${E.path}: ${E.reason}`))}let f=e.omitted.length+t.omitted.length,d=[...Ky("baseline",e),...Ky("current",t),...o.totalChanges===0&&a===null?[hr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],p=()=>{if(r.gitChangedPaths===void 0)return;let x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(k=>x.has(k)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(k=>!x.has(k))}},m=x=>{let k=o.candidates.slice(0,x.detailedChangeCount),E=k.filter(Ce=>Ce.attributedTo.length===0&&!u.has(Ce.path)),C=o.totalChanges-k.length,H=o.totalUnattributed-E.length,P=f-x.detailedOmissionCount,W=H+P,ue=[...E.map(Ce=>hr({kind:"unattributed-change",source:"implementation-scope",path:Ce.path,evidence:{after:Ce.after,before:Ce.before,changeKind:Ce.kind}},`Changed path is not covered by a declared artifact: ${Ce.path}`)),...l.slice(0,x.detailedOmissionCount),...d,...W>0?[sN(x.overflowHash,{changes:C,unattributed:H,unresolved:W})]:[]],$t=gT(ue),ri=x.includeGitAdvisory?p():void 0;return{schema:Sp,contractHash:i,baselineProjectionRef:Ep(s),baselineProjectionHash:s,currentProjectionRef:Ep(c),currentProjectionHash:c,complete:$t.length===0,declaredArtifacts:n,changes:k,unattributed:E,unresolvedScopes:$t,noCodeReason:a,...ri?{gitAdvisory:ri}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,g=l.length,v=r.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let x=m({detailedChangeCount:h,detailedOmissionCount:g,includeGitAdvisory:v,overflowHash:w});if(vo({...x,scopeHash:w})<=Pi)break;if(v){v=!1;continue}if(g>0){g-=Math.max(1,Math.ceil(g/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let b=o.totalChanges>h||f>g?kT({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:g}):w,S=m({detailedChangeCount:h,detailedOmissionCount:g,includeGitAdvisory:v,overflowHash:b}),N={...S,scopeHash:T(rN,S)};if(vo(N)>Pi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return N}function Ut(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Kt(e,t,r,i){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Ri(e,t){if(typeof e!="string"||!Cp.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Xy(e,t,r){let i=Ep(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function xl(e,t){let r=Ut(e,"Native snapshot projection");if(Kt(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==tN)throw new Error("Native snapshot projection schema is invalid");let i=kp({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=hT(i);if(T(ho,r)!==T(ho,n))throw new Error("Native snapshot projection is not canonical");let a=T(ho,n);if(t!==void 0&&Ri(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Rp(e,t){let r=Ut(e,`Declared artifact ${t}`);if(Kt(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Wr(r.path,`Declared artifact ${t} path`),kind:r.kind}}function Qy(e,t){if(e===null)return null;let r=Ut(e,t);return Kt(r,["hash","size"],[],t),{hash:Ri(r.hash,`${t} hash`),size:xn(r.size,`${t} size`)}}function Zy(e,t){let r=Ut(e,`Implementation change ${t}`);if(Kt(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(Rp),n=Cl(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Qy(r.before,`Implementation change ${t} before`),o=Qy(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:Wr(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function xT(e,t){let r=Ut(e,`Unresolved scope ${t}`);Kt(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?iN(r.path,`Unresolved scope ${t} path`):Wr(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function mo(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>Wr(n,`${t} ${a}`)),i=[...new Set(r)].sort(Re);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function cN(e){let t=Ut(e,"Native implementation external drift");if(Kt(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=mo(t.paths,"Native external drift paths");return oN({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function Rl(e){let t=Ut(e,"Native implementation scope"),r=[...ET].filter(E=>E!=="gitAdvisory"&&E!=="externalDrift");if(Kt(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Sp)throw new Error("Native implementation scope schema is invalid");let i=Ri(t.contractHash,"Implementation scope contractHash"),n=Ri(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Xy(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Ri(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Xy(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(Rp);if(JSON.stringify(c)!==JSON.stringify(Cl(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Zy),u=[...l].sort((E,C)=>Re(E.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(E=>E.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let f=new Set(c.map(E=>`${E.kind}:${E.path}`));if(l.some(E=>E.attributedTo.some(C=>!f.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(E=>JSON.stringify(E.attributedTo)!==JSON.stringify(c.filter(C=>go(C,E.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=t.unattributed.map(Zy),p=t.externalDrift===void 0?void 0:cN(t.externalDrift),m=new Set(p?.paths??[]),h=l.filter(E=>E.attributedTo.length===0&&!m.has(E.path));if(JSON.stringify(d)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let g=t.unresolvedScopes.map(xT),v=g.filter(E=>E.kind==="scope-detail-overflow");if(v.length>1)throw new Error("Implementation scope has multiple detail overflow records");let w=v[0]===void 0?null:bT(v[0]);if(w&&(w.changes+w.unresolved===0||w.unattributed>w.changes||w.unattributed>w.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let y=t.noCodeReason,b=[...h.map(E=>hr({kind:"unattributed-change",source:"implementation-scope",path:E.path,evidence:{after:E.after,before:E.before,changeKind:E.kind}},`Changed path is not covered by a declared artifact: ${E.path}`)),...l.length+(w?.changes??0)===0&&y===null?[hr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],S=g.filter(E=>E.kind==="unattributed-change"||E.kind==="missing-no-code-reason");if(JSON.stringify(g)!==JSON.stringify([...g].sort(xp))||new Set(g.map(E=>E.id)).size!==g.length||JSON.stringify(S)!==JSON.stringify(b.sort(xp))||t.complete!==(g.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let N;if(t.gitAdvisory!==void 0){let E=Ut(t.gitAdvisory,"Implementation scope Git advisory");if(Kt(E,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),E.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=mo(E.changedPaths,"Git changed paths"),H=mo(E.pathsPresentInSnapshotChanges,"Git present paths"),P=mo(E.pathsAbsentFromSnapshotChanges,"Git absent paths"),W=[...H,...P].sort(Re);if(JSON.stringify(W)!==JSON.stringify(C)||P.some(ue=>l.some($t=>$t.path===ue)))throw new Error("Implementation scope Git advisory partition is invalid");N={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:H,pathsAbsentFromSnapshotChanges:P}}let x={schema:Sp,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:g,noCodeReason:y,...N?{gitAdvisory:N}:{},...p?{externalDrift:p}:{}},k=Ri(t.scopeHash,"Implementation scope scopeHash");if(T(rN,x)!==k)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:k}}function CT(e){let t=Ut(e,"Native implementation scope authority");if(Kt(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let r=t.declaredArtifacts.map(Rp);if(JSON.stringify(r)!==JSON.stringify(Cl(r)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let i;t.gitChangedPaths!==void 0&&(i=mo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:cN(t.externalDrift),a=yT({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function wo(e){let t=Ut(e,"Native implementation scope bundle");Kt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=CT(t.authority),i=xl(t.baseline),n=xl(t.current),a=Rl(t.scope),o=ST(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function lN(e){let t=Rl(e.scope);return wo({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var Sp,tN,ho,rN,iT,nT,aT,Cp,Pi,oT,sT,ET,Cn=A(()=>{"use strict";fe();po();Sp="comet.native.implementation-scope.v2",tN="comet.native.content-snapshot-projection.v1",ho="comet.native.content-snapshot-projection.v1",rN="comet.native.implementation-scope.v2",iT="comet.native.unresolved-scope-id.v1",nT="comet.native.scope-detail-overflow.v1",aT="comet.native.snapshot-projection-overflow.v2",Cp=/^[a-f0-9]{64}$/u,Pi=1024*1024,oT=128,sT=128;ET=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import uN from"node:path";function mr(e,t){if(!fN.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function pN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function hN(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Pp(e,t,r=2e3){let i=Me(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function yo(e,t){let r=uN.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||uN.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function AT(e,t,r){let i=yo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Xi(i),a=i.toLowerCase(),o=r?yo(r,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${i}`);return i}function _p(e){let t=yo(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function Rn(e,t){return e<t?-1:e>t?1:0}function Pl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _l(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function mN(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function dN(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function IT(e){let t=Pl(e,"Native acceptance trace");if(_l(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!fN.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let r=yo(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=Pl(o,`Native acceptance trace entry ${s}`);if(_l(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(f=>typeof f!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(f=>_p(f)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Rn))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:yo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Pp(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Rn(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=mr(t.traceHash,"Native acceptance trace hash");if(T(RT,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function vN(e){let t=Pl(e,"Native partial allowance");if(_l(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(Rn))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:hN(t.change),scopeHash:mr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Pp(t.reason,"Partial allowance reason"),confirmedSummary:Pp(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:pN(t.sourceRevision),confirmedAt:mN(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=mr(t.allowanceHash,"Native partial allowance hash");if(T(PT,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Ap(e){let t=Pl(e,"Native verification evidence");if(_l(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let r=mr(t.implementationScopeHash,"Native verification implementation scope hash"),i=IT(t.acceptanceTrace),n=mr(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:mr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(d=>_p(d));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Rn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(d=>d.evidenceRefs))].sort(Rn);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(d=>_p(d));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Rn)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:hN(t.change),sourceRevision:pN(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:mr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:dN(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:AT(t.reportRef,"Native verification report ref"),reportHash:mr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:dN(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:mN(t.createdAt,"Native verification timestamp")},f=mr(t.envelopeHash,"Native verification envelope hash");if(T(_T,u)!==f)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:f}}var fN,RT,PT,_T,Al=A(()=>{"use strict";fe();qr();Sa();Cn();fN=/^[a-f0-9]{64}$/u,RT="comet.native.acceptance-trace.v2",PT="comet.native.partial-allowance.v1",_T="comet.native.verification-evidence.v2"});var Il,TT,jT,$T,nF,OT,aF,Ip=A(()=>{"use strict";fe();Il="scoped-text-safety",TT=1,jT=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),$T="comet.native.checker-policy.v1",nF=T($T,{policy:Il,version:TT,limits:jT,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),OT=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],aF=new Set(OT)});function Pn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function zr(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function vr(e,t){if(typeof e!="string"||!DT.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Rt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=Me(e).trim();if(!r||r.length>FT||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Tp(e,t){let r=Rt(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function No(e,t,r=Rt,i=!1,n=VT){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function WT(e,t){if(typeof e!="string"||!BT.test(e))throw new Error(`${t} is invalid`);return e}function zT(e){let t=Pn(e,"Native verification receipt bindings");if(zr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!LT.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:vr(t.contractHash,"Native verification receipt contract hash"),scopeHash:vr(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:vr(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:vr(t.artifactHash,"Native verification receipt artifact hash")}}function JT(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=qT.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function GT(e,t,r,i){let n=Pn(t,`Native ${e} evidence`);if(e==="automated-check"){if(zr(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=Tp(n.startedAt,"Native automated-check start time"),o=Tp(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=Pn(n.worktree,"Native automated-check worktree");if(zr(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=Pn(n.afterFence,"Native automated-check after fence");if(zr(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Rt(n.executable,"Native automated-check executable"),args:No(n.args,"Native automated-check arguments",Rt,!0),cwd:Rt(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:Rt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:vr(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:vr(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:vr(n.outputHash,"Native automated-check output hash"),outputSummary:Rt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){zr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=JT(n.checkReceiptRef);if(vr(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:No(n.subjects,"Native static inspection subjects",Rt,i==="required-check"),rule:Rt(n.rule,"Native static inspection rule"),resultSummary:Rt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return zr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:No(n.steps,"Native manual evidence steps"),observations:No(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function UT(e){let t=Pn(e,"Native verification receipt");if(zr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let r=t.kind,i=t.role,n=t.status,a=Rt(t.actor,"Native verification receipt actor"),o=No(t.acceptanceIds,"Native receipt acceptance IDs",WT,i==="required-check",MT).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:jp,kind:r,role:i,status:n,bindings:zT(t.bindings),acceptanceIds:o,actor:a,issuedAt:Tp(t.issuedAt,"Native verification receipt issue time"),evidence:GT(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Il||s.actor!==`native-runtime:${Il}`))throw new Error("Native required check policy identity is invalid");return s}function $p(e){let t=Pn(e,"Native verification receipt");if(zr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==jp)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=UT(i),a=vr(t.receiptHash,"Native verification receipt hash");if(T(HT,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}var jp,HT,DT,BT,LT,qT,FT,VT,MT,Tl=A(()=>{"use strict";fe();Ip();qr();jp="comet.native.verification-receipt.v3",HT=jp,DT=/^[a-f0-9]{64}$/u,BT=/^acceptance-[a-f0-9]{64}$/u,LT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,qT=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,FT=4096,VT=256,MT=1024});var RN={};du(RN,{MAX_NATIVE_EVIDENCE_DOCUMENT_BYTES:()=>Yt,MAX_NATIVE_IMPLEMENTATION_SCOPE_BUNDLE_BYTES:()=>KT,listNativeVerificationReceiptRefs:()=>xN,nativeEvidenceRef:()=>Jr,nativeReportEvidenceRef:()=>ZT,readArchivedNativeVerificationAcceptanceCounts:()=>oj,readNativeImplementationScope:()=>Eo,readNativeImplementationScopeBundle:()=>$l,readNativePartialAllowance:()=>Lp,readNativeVerificationEvidence:()=>qp,readNativeVerificationReceipt:()=>Ol,readNativeVerificationReportSnapshot:()=>So,removeNativeVerificationReportSnapshot:()=>kN,writeNativeImplementationScope:()=>nj,writeNativePartialAllowance:()=>aj,writeNativeVerificationEvidence:()=>CN,writeNativeVerificationReceipt:()=>EN,writeNativeVerificationReportSnapshot:()=>ko});import{createHash as NN}from"node:crypto";import{promises as Te}from"node:fs";import Pt from"node:path";function Op(e,t){let r=Pt.relative(e,t);return r===""||!Pt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Pt.sep}`)}function YT(e,t){return Z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function bo(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return wt(r,i)?Z(r,i):Z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function gN(e){let t=await Te.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Te.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function XT(e,t){let r=Pt.resolve(e),i=Pt.resolve(t);if(!Op(r,i))throw new Error("Native evidence path is outside its change");let n=[await gN(r)],a=r;for(let o of Pt.relative(r,i).split(Pt.sep).filter(Boolean)){a=Pt.join(a,o);let s=await gN(a);if(!Op(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function wN(e){for(let t of e){let r=await Te.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!YT(t,r)||await Te.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function QT(e,t,r={}){let i=await XT(t,Pt.dirname(e));await r.afterParentChainCaptured?.();let n=await Te.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Te.realpath(e);if(!Op(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Te.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Te.lstat(e),Te.realpath(e)]);if(await wN(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!bo(s,n)||!bo(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Yt)throw new Error(`Native evidence document exceeds ${Yt} bytes`);await r.afterOpen?.();let u=[],f=0,d=Buffer.allocUnsafe(64*1024);for(;;){let g=Yt+1-f,v=await o.read(d,0,Math.min(d.length,g),null);if(v.bytesRead===0)break;if(f+=v.bytesRead,f>Yt)throw new Error(`Native evidence document exceeds ${Yt} bytes`);u.push(Buffer.from(d.subarray(0,v.bytesRead)))}await r.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Te.lstat(e),Te.realpath(e)]);if(await wN(i),!m.isFile()||m.isSymbolicLink()||h!==a||!bo(s,p)||!bo(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,f).toString("utf8"))}finally{await o.close()}}function Jr(e,t){if(!bN.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function ZT(e){return Jr("reports",e)}async function ko(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>Yt||NN("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return Ai({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,onCreated:e.onCreated,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function kN(e){let t=Hp(e.paths,e.name,"reports",e.hash),r=qe(e.paths,t);await z(r,t);let i=await Te.lstat(t);if(await So(e.paths,e.name,e.hash),await z(r,t),!bo(i,await Te.lstat(t)))throw new Error("Native report evidence changed before rollback");await Te.unlink(t)}async function So(e,t,r,i,n){if(!bN.test(r))throw new Error("Native report evidence hash is invalid");let a=await Xt({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==r||typeof o.content!="string"||NN("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function _i(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function Hp(e,t,r,i,n){let a=Jr(r,i);return n?Pt.join(n,...a.split("/")):wf(ot(e,t),a)}async function Xt(e){let t=Hp(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??qe(e.paths,t);return await z(r,t),QT(t,r,e.hooks)}async function Ai(e){jl(e.value);let t=Hp(e.paths,e.name,e.kind,e.hash),r=qe(e.paths,t);await z(r,t);try{let n=await Xt(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return Jr(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await we(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await Xt(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return Jr(e.kind,e.hash)}function jl(e){if(ej(e)>Yt)throw new Error(`Native evidence document exceeds ${Yt} bytes`)}function ej(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
216
- `,"utf8")}function yN(e,t){return xl(e,t)}function tj(e,t){let r=Rl(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function SN(e,t,r){let i=vN(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function Dp(e,t,r){let i=Ap(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}function rj(e){return{total:e.total,evidenced:e.evidenced,skipped:e.skipped}}function ij(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;let i=e;if(i.schema!=="comet.native.verification-evidence.v1")return null;if(i.change!==t||i.envelopeHash!==r)throw new Error("Legacy Native verification evidence ref/hash/change mismatch");let n=i.acceptanceTrace;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Legacy Native acceptance trace is invalid");let a=n,{total:o,evidenced:s,skipped:c}=a,l=typeof o=="number"?o:Number.NaN,u=typeof s=="number"?s:Number.NaN,f=typeof c=="number"?c:Number.NaN;if(a.schema!=="comet.native.acceptance-trace.v1"||!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||!Number.isSafeInteger(f)||l<0||u<0||f<0||u+f>l)throw new Error("Legacy Native acceptance trace is invalid");return{total:l,evidenced:u,skipped:f}}async function Bp(e,t,r,i=!1,n){let a=await Eo(e,t,r.implementationScopeRef,void 0,n);if(i&&await So(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await Lp(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function nj(e){let t=wo(e.bundle),{baseline:r,current:i,scope:n}=t;return jl(r),jl(i),jl(n),await Ai({paths:e.paths,name:e.name,kind:"snapshots",hash:n.baselineProjectionHash,value:r}),await Ai({paths:e.paths,name:e.name,kind:"snapshots",hash:n.currentProjectionHash,value:i}),Ai({paths:e.paths,name:e.name,kind:"scopes",hash:n.scopeHash,value:n})}async function $l(e,t,r,i,n){let a=_i(r,"scopes"),o=tj(await Xt({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=_i(o.baselineProjectionRef,"snapshots"),c=_i(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Xt({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(f=>yN(f,s)),Xt({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(f=>yN(f,c))]);return lN({baseline:l,current:u,scope:o})}async function Eo(e,t,r,i,n){return(await $l(e,t,r,i,n)).scope}async function aj(e){let t=SN(e.allowance,e.name,e.allowance.allowanceHash),r=await Eo(e.paths,e.name,Jr("scopes",t.scopeHash)),i=r.unresolvedScopes.map(n=>n.id).sort();if(r.complete||JSON.stringify(i)!==JSON.stringify(t.scopeIds))throw new Error("Native partial allowance does not match a persisted partial scope");return Ai({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function Lp(e,t,r,i,n){let a=_i(r,"allowances");return SN(await Xt({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function EN(e){let t=$p(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return Ai({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function Ol(e,t,r,i,n){let a=_i(r,"receipts"),o=$p(await Xt({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function xN(e,t){let r=Pt.join(ot(e,t),"evidence","receipts");await z(qe(e,r),r);let i;try{i=await Te.readdir(r,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}return i.filter(n=>n.isFile()).map(n=>/^([a-f0-9]{64})\.json$/u.exec(n.name)?.[1]).filter(n=>n!==void 0).sort().map(n=>Jr("receipts",n))}async function CN(e){let t=Dp(e.evidence,e.name,e.evidence.envelopeHash);if(t.schema!=="comet.native.verification-evidence.v2")throw new Error("Native active verification evidence must use v2");return await Bp(e.paths,e.name,t,!0),Ai({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function qp(e,t,r,i,n){let a=_i(r,"verifications"),o=Dp(await Xt({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await Bp(e,t,o,!1,n),o}async function oj(e,t,r,i){let n=_i(r,"verifications"),a=await Xt({paths:e,name:t,kind:"verifications",hash:n,changeDir:i}),o=ij(a,t,n);if(o)return o;let s=Dp(a,t,n);return await Bp(e,t,s,!1,i),rj(s.acceptanceTrace)}var bN,Yt,KT,Gr=A(()=>{"use strict";ne();te();Dt();Cn();Al();Tl();bN=/^[a-f0-9]{64}$/u,Yt=Pi,KT=3*Yt});var _N={};du(_N,{executeNativeSupervisorChecks:()=>Mp,readNativeSupervisorCheckEvidence:()=>_n});import{createHash as sj,randomUUID as cj}from"node:crypto";import{promises as PN}from"node:fs";import Vp from"node:path";function Co(e){return sj("sha256").update(e).digest("hex")}function Fp(e,t){if(I(t.projectRoot,["branch","--show-current"])!==`comet/supervisor/${e}/${t.child}`||I(t.projectRoot,["rev-parse","HEAD"])!==t.baseCommit||!zt(t.projectRoot))throw new Error("Native Supervisor checks require the clean current candidate in its bound worktree")}function xo(e,t,r){let i=e?.children.find(n=>n.name===t)?.task;if(!i||i.role!=="verifier"||i.runId!==r)throw new Error("Native Supervisor check runId is not current");return i}async function lj(e,t){return Promise.all(t.map(async r=>{let i=gl(r),n=await z(e,Vp.resolve(e,...i.logRef.split(/[\\/]/u))),a=await PN.readFile(n,"utf8"),o=Me(a);return{...i,logContent:o.slice(0,128*1024),logDigest:Co(o)}}))}function uj(e,t){return typeof e.logContent=="string"&&typeof e.logDigest=="string"&&e.logDigest.length>0&&t.status===e.status&&t.id===e.id&&t.name===e.name&&JSON.stringify(t.argvDisplay)===JSON.stringify(e.argvDisplay)&&t.cwdRef===e.cwdRef&&t.exitCode===e.exitCode&&t.signal===e.signal&&t.timedOut===e.timedOut&&t.durationMs===e.durationMs&&t.startedAt===e.startedAt&&t.completedAt===e.completedAt&&t.repeatable===e.repeatable&&t.logRef===e.logRef}async function dj(e){try{let t=pe(e.paths,e.parent);return(await Promise.all(e.checks.map(async i=>{if(typeof i.logContent!="string"||typeof i.logDigest!="string")return!1;let n=await z(t,Vp.resolve(t,...i.logRef.split(/[\\/]/u))),a=Me(await PN.readFile(n,"utf8"));return Co(a)===i.logDigest&&a.slice(0,128*1024)===i.logContent}))).every(Boolean)}catch{return!1}}function fj(e){if(e===void 0)return null;let t=new Set(e);if(t.size===0||t.size!==e.length)throw new Error("Native Supervisor retry IDs must be non-empty and unique");return t}function pj(e,t,r){if(!e)throw new Error("Native Supervisor check retry requires per-check Runtime state");let i=new Map(t.map(n=>[n.id,n]));for(let n of r){let a=e.find(s=>s.id===n),o=i.get(n);if(!a||!o||a.status!=="interrupted")throw new Error(`Native Supervisor retry ID is not an interrupted current check: ${n}`);if(!a.repeatable||!o.repeatable)throw new Error(`Native Supervisor check ${n} is not repeatable and cannot be retried`);if(a.executionCount>=3)throw new Error(`Native Supervisor check retry limit (3) reached: ${n}`)}}async function Mp(e){if(e.plans.length===0||new Set(e.plans.map(({id:l})=>l)).size!==e.plans.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(e.plans.some(({repeatable:l})=>!l))throw new Error("Native Supervisor checks must be repeatable for safe recovery");if(e.materials.some(({name:l,content:u})=>!l.trim()||Buffer.byteLength(u)>1024*1024))throw new Error("Native Supervisor external material name or size is invalid");let t=fj(e.retryCheckIds),r=await _(e.paths,"reserve Supervisor checks",async()=>{let l=await O(e.paths,e.parent),u=xo(l,e.child,e.runId);Fp(e.parent,u),Ye(u.projectRoot,e.plans);let f=yl(),d=await wl({kind:"child",parent:e.parent,child:e.child,runId:e.runId,projectRoot:u.projectRoot,candidateCommit:u.baseCommit,contractHash:u.contractHash??null,plans:e.plans,materials:e.materials}),p=T("comet.native.supervisor-check-plan.v2",{machineId:f,inputFingerprint:d}),m=u.checkExecution;if(m?.status==="running"){let w=await mn(m.ownerPid,m.ownerIdentity),y=Date.parse(m.expiresAt??"")||Date.parse(m.startedAt)+3e4;if(w){if(!(Date.now()<y))throw new Error("Native Supervisor check lease expired while owner PID is alive; inspect the original execution before retrying");if(m.key!==p)throw new Error("Native Supervisor check plan is already running with different inputs");return{task:structuredClone(u),execute:!1}}let b=m.activeProcess;if(b===void 0||b?.status==="starting")throw new Error(`Native Supervisor check process registration is incomplete. Check logs in ${Vp.join(pe(e.paths,e.parent),"logs","checks")} for operation ${m.operationId}; stop any remaining check process in ${u.projectRoot}, then submit supervisor-cancel for child ${e.child} and runId ${u.runId}, and dispatch a new Verifier for the preserved candidate.`);if(b&&await mn(b.pid,b.identity)){if(!(Date.now()<y))throw new Error(`Native Supervisor check ${b.checkId} is still running as PID ${b.pid} after its owner exited and lease expired; stop that original check process, then retry supervisor-checks for ${e.child}.`);return{task:structuredClone(u),execute:!1}}if(m.checkStates?.length&&m.checkStates.every(({status:N})=>N==="passed"||N==="failed")&&m.receiptRef){m.status="completed";try{return await _n({...e,task:u,receiptRef:m.receiptRef}),l.stateVersion+=1,await q(e.paths,l),{task:structuredClone(u),execute:!1,key:m.key}}catch{m.status="interrupted"}}m.status="interrupted";for(let N of m.checkStates??[])(N.status==="planned"||N.status==="running")&&(N.status="interrupted")}let h=m?.key===p&&m.machineId===f&&m.inputFingerprint===d;if(t){if(!h||m?.status!=="interrupted")throw new Error("Native Supervisor check retry requires the interrupted current plan on the same candidate, machine and workspace");pj(m.checkStates,e.plans,t)}else if(m?.status==="interrupted"&&h)return{task:structuredClone(u),execute:!1,key:p};if(m?.status==="completed"&&h&&m.receiptRef)try{return await _n({...e,task:u,receiptRef:m.receiptRef}),{task:structuredClone(u),execute:!1,key:p}}catch{}let g=t&&m?.checkStates?m.checkStates.map(w=>t.has(w.id)?{...w,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{...w}):e.plans.map(bn),v=e.plans.map(w=>g.find(y=>y.id===w.id)??bn(w));return u.checkExecution={operationId:cj(),key:p,status:"running",ownerPid:process.pid,ownerIdentity:await Ke(process.pid)??void 0,activeProcess:null,startedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+e.plans.reduce((w,y)=>w+y.timeoutMs,0)+3e4).toISOString(),machineId:f,inputFingerprint:d,checkStates:v},u.checksReason="running",l.stateVersion+=1,await q(e.paths,l),{task:structuredClone(u),execute:!0,key:p,plansToExecute:e.plans.filter(w=>!t||t.has(w.id))}}),{task:i}=r,n=i.checkExecution.operationId;if(!r.execute)return i.checkExecution.status==="completed"&&i.checkExecution.receiptRef&&await _n({...e,task:i,receiptRef:i.checkExecution.receiptRef}),{status:i.checkExecution.status==="completed"?"completed":i.checkExecution.status==="interrupted"?"interrupted":"running",operationId:n,...i.checkExecution.receiptRef?{receiptRef:i.checkExecution.receiptRef}:{}};let a=pe(e.paths,e.parent),o=r.plansToExecute,s=async l=>{await _(e.paths,"register Supervisor check process",async()=>{let u=await O(e.paths,e.parent),f=xo(u,e.child,e.runId);if(f.checkExecution?.operationId!==n||f.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");if(l?.status==="starting"){let d=f.checkExecution.checkStates?.find(({id:p})=>p===l.checkId);if(!d||d.status!=="planned")throw new Error(`Native Supervisor check ${l.checkId} is not planned`);d.status="running",d.executionCount+=1,d.startedAt=new Date().toISOString(),d.completedAt=null,d.logRef=null}f.checkExecution.activeProcess=l,u.stateVersion+=1,await q(e.paths,u)})},c=async l=>_(e.paths,"record Supervisor check result",async()=>{let u=await O(e.paths,e.parent),f=xo(u,e.child,e.runId);if(f.checkExecution?.operationId!==n||f.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");let d=f.checkExecution.checkStates?.find(({id:p})=>p===l.id);if(!d)throw new Error(`Native Supervisor check state is missing: ${l.id}`);Object.assign(d,vl(d,l)),f.checkExecution.activeProcess=null,u.stateVersion+=1,await q(e.paths,u)});try{for(let g of o){await s({status:"starting",checkId:g.id});let v=await Ni({projectRoot:i.projectRoot,runtimeDir:a,operationId:n,plan:g,onSpawn:async({pid:w})=>{await s({status:"running",checkId:g.id,pid:w,identity:await Ke(w)??void 0})}});if(await c(v),v.status==="interrupted")throw new Error(`Native Supervisor check ${v.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let l=await O(e.paths,e.parent),u=xo(l,e.child,e.runId);Fp(e.parent,u);let f=u.checkExecution?.checkStates;if(!f||f.some(({status:g})=>!["passed","failed"].includes(g)))throw new Error("Native Supervisor check plan remains incomplete; retry each interrupted check explicitly");let d=await lj(a,f),p={schema:"comet.native.supervisor-checks.v1",parent:e.parent,child:e.child,runId:e.runId,candidateCommit:i.baseCommit,contractHash:i.contractHash??null,operationId:n,planHash:r.key,machineId:u.checkExecution.machineId,inputFingerprint:u.checkExecution.inputFingerprint,checks:d,materials:e.materials.map(({name:g,content:v})=>{let w=Me(v);return{name:g,content:w,hash:Co(w)}})},m=JSON.stringify(p),h=await ko({paths:e.paths,name:e.parent,hash:Co(m),text:m});return await _(e.paths,"complete Supervisor checks",async()=>{let g=await O(e.paths,e.parent),v=xo(g,e.child,e.runId);if(v.checkExecution?.operationId!==n)throw new Error("Native Supervisor check operation is stale");Fp(e.parent,v),v.checkExecution.status="completed",v.checkExecution.receiptRef=h,v.checkExecution.activeProcess=null,v.checksReason="completed",g.stateVersion+=1,await q(e.paths,g)}),{status:"completed",operationId:n,receiptRef:h}}catch(l){throw await _(e.paths,"interrupt Supervisor checks",async()=>{let u=await O(e.paths,e.parent),f=u?.children.find(({name:d})=>d===e.child)?.task;if(f?.runId===e.runId&&f.checkExecution?.operationId===n){f.checkExecution.status="interrupted",f.checkExecution.activeProcess=null;for(let d of f.checkExecution.checkStates??[])(d.status==="planned"||d.status==="running")&&(d.status="interrupted");f.checksReason="not-run",u.stateVersion+=1,await q(e.paths,u)}}),l}}async function _n(e){let t=/^runtime\/evidence\/reports\/([a-f0-9]{64})\.json$/u.exec(e.receiptRef);if(!t)throw new Error("Native Supervisor receipt ref is invalid");let r=JSON.parse(await So(e.paths,e.parent,t[1])),i=e.task,n=i.checkExecution?.checkStates,a=n!==void 0&&Array.isArray(r.checks)&&r.checks.length===n.length&&r.checks.every((s,c)=>uj(s,n[c])),o=Array.isArray(r.checks)&&await dj({paths:e.paths,parent:e.parent,checks:r.checks});if(r.schema!=="comet.native.supervisor-checks.v1"||r.parent!==e.parent||r.child!==i.child||r.runId!==i.runId||r.candidateCommit!==i.baseCommit||r.contractHash!==(i.contractHash??null)||r.operationId!==i.checkExecution?.operationId||r.planHash!==i.checkExecution.key||r.machineId!==i.checkExecution.machineId||r.inputFingerprint!==i.checkExecution.inputFingerprint||i.checkExecution.status!=="completed"||i.checkExecution.receiptRef!==e.receiptRef||!Array.isArray(r.checks)||r.checks.length===0||!a||!o||!Array.isArray(r.materials)||r.materials.some(({content:s,hash:c})=>Co(s)!==c))throw new Error("Native Supervisor receipt does not match the current candidate, runId, contract or execution");return r}var Wp=A(()=>{"use strict";kn();rt();Xa();fe();gn();yp();Gr();le();te();qr();lr()});var $N=br(rr(),1);import{promises as Nj}from"node:fs";import _t from"node:path";import{execFileSync as wR}from"child_process";import yR from"fs";import Xs from"path";function ir(e,t){return wR("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Ki(e,t){return Ig(e)===Ig(t)}function Ig(e){let t=Xs.resolve(e);try{let r=yR.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function ie(e){try{let t=Xs.resolve(ir(e,["rev-parse","--show-toplevel"])),i=ir(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?Xs.resolve(i.slice(9)):t,a=null;try{a=ir(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Ki(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Qs(e){try{ir(e,["rev-parse","--is-inside-work-tree"]);let t=ir(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:Xs.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function nr(e){return Qs(e).map(t=>t.root)}function Tg(e){try{return ir(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function Yi(e,t){try{return ir(e,["check-ref-format","--branch",t]),ir(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function ar(e,t){try{let r=ir(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}rt();nt();fe();st();te();ut();Pc();Pc();gi();lr();import{randomUUID as mj}from"node:crypto";import Hl from"node:path";rt();Xa();ne();fe();gn();le();te();yp();gi();lr();kn();rt();import{promises as fo}from"node:fs";import ze from"node:path";st();kn();ro();te();var Vr=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function Fy(e,t){let r=ze.relative(e,t);return r===""||!ze.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ze.sep}`)}function Ly(e){return JSON.stringify(e.native)}async function kl(e,t){let r=await _e(e);if(r&&t){if(Ly(r)!==Ly(t))throw new Error(`Native worktree configuration differs from the source project: ${ze.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await yc(e,t),await By(e),!0):!1}async function RI(e,t){if(!Fy(e,t))return!1;let i=`/${ze.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=I(e,["rev-parse","--git-common-dir"]),a=ze.resolve(e,n),o=ze.join(a,"info","exclude"),s="";try{s=await fo.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await fo.mkdir(ze.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
224
+ `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=Hb(l,t);else if(r)Db(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let p=Hb(l,null);if(p!==null)t=p;else{let d=l.trimStart();if(d.startsWith("<!--")&&!Db(d))r=!0;else{let f=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);f&&n.has(f[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${f[1]}\\s*>`,"iu").test(d)&&(i=f[1])}}}if(c===-1)break;o=c+1}}function Vo(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function Lb(e,t,r,i=[],n="content-hash"){let a=Vo(r),o=t.replaceAll("\\","/").trim(),s=i.map(Vo);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${$(BT,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Fb(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function LT(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Dl(e)){n=s+1;let c=o?Bb(a):null;c?.level===1&&(Ol(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function th(e,t="brief.md",r=Bl.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=LT(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:p}of Dl(e)){if(p<n.start||p>=n.end)continue;let d=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(d===null)continue;let f=d[1].length;a=a===null?f:Math.min(a,f)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:p}of Dl(e)){if(p<n.start||p>=n.end)continue;let d=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;d&&d[1].length===a?(c(),s=[d[2]]):s!==null&&s.push(l)}return c(),Fb(o.map(l=>Lb("brief-example",t,l.join(`
225
+ `),[],i)),"Brief",i)}function rh(e,t="spec.md",r=Bl.maxCriteria,i="content-hash",n={}){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let a=[],o=[],s=null,c=()=>{if(s===null)return;if(a.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let l=(n.resolveBriefReferences?s.body:[]).map(u=>/^\s*(?:Acceptance|验收)\s*[::]\s*(.*)$/iu.exec(u)?.[1]).filter(u=>u!==void 0);if(l.some(u=>!/^A[1-9]\d*$/u.test(u)))throw new Error("A Spec acceptance reference must be one brief ID such as A1");if(l.length>1)throw new Error("A Spec scenario may reference only one brief acceptance criterion");a.push({...Lb("spec-scenario",t,[s.title,...s.body].join(`
226
+ `),s.context,i),...l[0]===void 0?{}:{briefAcceptanceRef:l[0]}}),s=null};for(let{line:l,body:u}of Dl(e)){let p=u?Bb(l):null,d=p?/^Scenario\s*:\s*(.*)$/iu.exec(p.text):null;if(d){for(c();o.at(-1)&&o.at(-1).level>=p.level;)o.pop();let f=Vo(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");s={level:p.level,title:f,body:[],context:o.map(h=>h.text)}}else if(p){for(s!==null&&p.level<=s.level?c():s!==null&&s.body.push(l);o.at(-1)&&o.at(-1).level>=p.level;)o.pop();o.push(p)}else s!==null&&u&&s.body.push(l)}return c(),Fb(a,"Specification",i)}var BT,eh,Bl,Wo=T(()=>{"use strict";Wi();pe();BT="comet.native.acceptance.v1",eh=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Bl=Object.freeze({maxCriteria:1024})});import qb from"node:path";function Mb(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||qb.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||qb.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function qT(e,t){return e.localeCompare(t,"en")}function Ll(e){let t=Mb(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((o,s)=>qT(o.capability,s.capability));if(new Set(r.map(o=>o.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=th(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:o,text:s})=>({source:o,text:s})),n=i.length;for(let o of r){let s=Mb(o.source,`Native spec source for ${o.capability}`);for(let c of rh(o.markdown,s,Number.MAX_SAFE_INTEGER,"none",{resolveBriefReferences:e.resolveBriefReferences===!0})){if(c.briefAcceptanceRef!==void 0){let l=Number(c.briefAcceptanceRef.slice(1))-1;if(!Number.isSafeInteger(l)||l<0||l>=n)throw new Error(`Native Spec references unknown brief acceptance ${c.briefAcceptanceRef}: ${s}`);continue}i.push({source:s,text:c.text})}}let a=new Set;for(let o of i){o.text=Vo(o.text);let s=o.text;if(a.has(s))throw new Error(`Native acceptance contains a duplicate criterion: ${o.text}`);a.add(s)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((o,s)=>({id:`A${s+1}`,source:o.source,text:o.text}))}function Vb(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!FT.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Wb(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var FT,Fl=T(()=>{"use strict";Wo();FT=/^A[1-9]\d*$/u});function MT(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function J(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(MT(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var ni=T(()=>{"use strict"});import VT from"node:path";function KT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function YT(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function XT(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function QT(e){return e.schema===Xt?Wn(e):e.schema===Yt?zn(e):Mi(e)}function ZT(e){return VT.posix.normalize(e.replaceAll("\\","/"))}function e$(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:ZT(t.source)})}function t$(e){return e==="shape"?"shape":"build"}function r$(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function i$(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function zb(e){let t=QT(e.state);Vb(e.acceptance);let r=t$(t.phase),i=r==="shape"?0:1,n=YT(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return B({schema:Ii,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:e$(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:r$(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:J(i$(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:sl(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function ih(e){let t=KT(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!WT.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==ql)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!GT.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!zT.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!UT.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!JT.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:ql,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:XT(t.createdAt,"Native portable migration transaction createdAt")}}function Gb(e){switch(ih(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var ql,WT,zT,GT,JT,UT,nh=T(()=>{"use strict";jl();Fl();at();ni();On();Bo();ql="comet.native.portable-migration.v1",WT=new Set(["schema","id","change","fromSchema","status","createdAt"]),zT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GT=/^[a-z0-9][a-z0-9-]{7,127}$/u,JT=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),UT=new Set([Xt,Yt,Kt])});import oh from"node:path";function Xb(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qb(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function ah(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function Ub(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function d$(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Xb(e,r);if(Qb(i,u$,r),typeof i.capability!="string"||!Yb.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation,a=i.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(d=>d==="."||d==="..")))throw new Error(`${r}.delta_source is invalid`);let o=ah(i.base_hash,`${r}.base_hash`),s=Ub(i.delta_content,`${r}.delta_content`),c=Ub(i.source_content,`${r}.source_content`),l=ah(i.expected_target_hash,`${r}.expected_target_hash`),u=ah(i.result_hash,`${r}.result_hash`),p=a!==void 0;if(p&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(p&&(s==null||c===void 0||c===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!p&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(p){let d=Do(s);if(d.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(d.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(Sr(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(Sr(c)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...l===void 0?{}:{expected_target_hash:l}}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(d=>d==="."||d===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||Sr(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function p$(e){let t=Xb(e,"Native portable Archive transaction");if(Qb(t,l$,"Native portable Archive transaction"),t.schema!==Jb)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!o$.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Yb.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!s$.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!c$.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(d$);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Jb,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function Ml(e){let t=n$.exec(e);if(t)return{kind:"archive",change:t[1]};let r=a$.exec(e);return r?{kind:"migration",change:r[1]}:null}function Vl(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Ml(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return oh.join(e.transactionsDir,r)}async function sh(e,t){let r=Ml(t);if(!r)return null;let i=await Z({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=oh.join(e.transactionsDir,t);if(r.kind==="archive"){let s=p$(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=ih(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Wl(e,t){let r=Vl(e,t);try{return await sh(e,oh.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Zb(e){return e.kind==="archive"||e.journal.status!=="committed"}var Jb,Kb,n$,a$,o$,s$,c$,l$,u$,Yb,zl=T(()=>{"use strict";rt();Gf();nh();Jb="comet.native.archive-transaction.v4",Kb="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",n$=new RegExp(`^portable-archive-(${Kb})\\.json$`,"u"),a$=new RegExp(`^portable-migration-(${Kb})\\.json$`,"u"),o$=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,s$=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,c$=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),l$=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),u$=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),Yb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as f$}from"node:crypto";import{constants as Gl,promises as $t}from"node:fs";import jt from"node:path";function Ul(e,t){let r=jt.relative(e,t);return r===""||!jt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${jt.sep}`)}function h$(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function m$(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function v$(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Jl(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ch(e,t){let r=await $t.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await $t.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function g$(e,t,r){let i=jt.resolve(e),n=jt.resolve(t);if(!Ul(i,n))throw new Error(`${r} is outside its managed root`);let a=[await ch(i,r)],o=i;for(let s of jt.relative(i,n).split(jt.sep).filter(Boolean)){await zi(a,r),o=jt.join(o,s);let c=await ch(o,r);if(!Ul(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await zi(a,r),a}async function zi(e,t){for(let r of e){let i=await $t.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!m$(r,i)||await $t.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function w$(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let o=t===null?a.length:t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,t!==null&&n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function zo(e){let t=e.maxBytes===null?null:h$(e.maxBytes),r=jt.resolve(e.file),i=await g$(e.root,jt.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>ch(jt.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await zi(i,e.label);let a=await $t.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=v$(a),s=await $t.realpath(r);if(!Ul(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>Ul(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?Gl.O_RDONLY:Gl.O_RDONLY|Gl.O_NOFOLLOW|Gl.O_NONBLOCK,l=await $t.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[p,d]=await Promise.all([$t.lstat(r),$t.realpath(r)]);if(await zi(i,e.label),await zi(n,e.label),!u.isFile()||!p.isFile()||p.isSymbolicLink()||d!==s||!Jl(o,u)||!Jl(o,p))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let f=await w$(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[h,m,v]=await Promise.all([l.stat(),$t.lstat(r),$t.realpath(r)]);if(await zi(i,e.label),await zi(n,e.label),!m.isFile()||m.isSymbolicLink()||v!==s||!Jl(o,h)||!Jl(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:f,hash:f$("sha256").update(f).digest("hex"),size:f.length}}finally{await l.close()}}var Zt=T(()=>{"use strict";ne();Jt()});import Rr from"path";import{TextDecoder as b$}from"util";function Yl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Xl(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function iN(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function lh(e,t){if(typeof e!="string"||e.length===0||Rr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Kl(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function eN(e,t){if(lh(e,t),e.includes("\\")||e!==Rr.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function R$(e,t){let r=Yl(e,`transaction operations[${t}]`);if(Xl(r,k$,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);lh(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&lh(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function nN(e){let t=Yl(e,"Native Archive transaction journal");if(Xl(t,S$,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!rN.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!iN(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Kl(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=Yl(s,`Archive transaction operations[${c}]`);if(Xl(l,E$,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);eN(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&eN(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Kl(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Kl(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Kl(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function C$(e){let t=Yl(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return nN(t);if(Xl(t,N$,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!rN.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Rr.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Rr.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!iN(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(R$),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function P$(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Rr.join(e.transactionsDir,t)}function aN(e,t){let r=P$(e,t);return{directory:r,journal:Rr.join(r,"transaction.json"),events:Rr.join(r,"events.jsonl"),staged:Rr.join(r,"staged"),backups:Rr.join(r,"backups")}}async function dh(e,t){let r=aN(e,t);return await Promise.all(Object.values(r).map(i=>G(e.runtimeDir,i))),r}async function ph(e,t,r={}){let i=await dh(e,t),n=await zo({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(x$.decode(n.bytes)),o=C$(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var N$,k$,S$,E$,rN,x$,Ql=T(()=>{"use strict";ne();ie();Zt();N$=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),k$=new Set(["id","type","source","target","staged","backup"]),S$=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),E$=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),rN=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),x$=new b$("utf-8",{fatal:!0})});import{promises as _$}from"fs";import A$ from"path";async function I$(e,t,r){let i;try{i=await _$.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await ph(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(Ml(n.name))try{let a=await sh(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Zb(a))return!0}catch{return!0}return!1}async function T$(e,t){let r=Date.now()+5e3,i=A$.join(e.locksDir,"root-move.lock");for(;;)try{return await _l(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await cb(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await lb(e,i,o);if(s.status==="removed"||s.status==="missing")continue;throw n}if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function A(e,t,r,i){let n=await T$(e,t);try{if(await nl(e.projectRoot),await I$(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Al(n)}catch(a){process.stderr.write(`[comet] warning: could not release Native mutation lock ${n.file} (${a.message}); run comet native doctor --repair if commands start failing
227
+ `)}}}var ve=T(()=>{"use strict";gt();Ho();zl();Ql()});import{createHash as $$}from"node:crypto";import{promises as fh}from"node:fs";import oN from"node:os";import Ot from"node:path";function Gn(e){return{id:e.id,name:e.name,status:"planned",repeatable:e.repeatable,executionCount:0,argvDisplay:$o(e.argv),cwdRef:e.cwdRef,exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}}function Zl(e,t){return{...e,name:t.name,status:t.status,argvDisplay:[...t.argvDisplay],cwdRef:t.cwdRef,exitCode:t.exitCode,signal:t.signal,timedOut:t.timedOut,durationMs:t.durationMs,startedAt:t.startedAt,completedAt:t.completedAt,logRef:t.logRef}}function eu(e){if(e.status!=="passed"&&e.status!=="failed"&&e.status!=="interrupted"||e.startedAt===null||e.completedAt===null||e.logRef===null)throw new Error(`Native Supervisor check ${e.id} has incomplete Runtime evidence`);return{id:e.id,name:e.name,argvDisplay:[...e.argvDisplay],cwdRef:e.cwdRef,status:e.status,exitCode:e.exitCode,signal:e.signal,timedOut:e.timedOut,durationMs:e.durationMs,startedAt:e.startedAt,completedAt:e.completedAt,repeatable:e.repeatable,logRef:e.logRef}}function j$(e,t){let r=Ot.relative(Ot.resolve(e),Ot.resolve(t));return r===""||!Ot.isAbsolute(r)&&!r.startsWith(`..${Ot.sep}`)}function er(e,t){try{return I(e,t)}catch(r){return`unavailable:${r instanceof Error?r.message:String(r)}`}}async function sN(e){let t=er(e,["ls-files","--others","--exclude-standard","-z"]);return t===null||t.startsWith("unavailable:")?[{error:t}]:Promise.all(t.split("\0").filter(Boolean).sort().map(async r=>{let i=r.replaceAll("\\","/"),n=Ot.resolve(e,...i.split("/"));if(!j$(e,n))return{path:i,error:"escaped"};try{let a=await fh.lstat(n);if(a.isSymbolicLink())return{path:i,kind:"symlink",target:await fh.readlink(n)};if(!a.isFile())return{path:i,kind:"other",size:a.size};let o=await fh.readFile(n);return{path:i,kind:"file",size:a.size,digest:$$("sha256").update(o).digest("hex")}}catch(a){return{path:i,error:a instanceof Error?a.message:String(a)}}}))}async function O$(e){let t=er(e,["ls-files","--stage","-z"]);if(t===null||t.startsWith("unavailable:"))return[{error:t}];let r=t.split("\0").map(i=>/^160000\s+[^\s]+\s+\d+\t(.+)$/u.exec(i)?.[1]).filter(i=>i!==void 0).sort();return Promise.all(r.map(async i=>({path:i.replaceAll("\\","/"),head:er(Ot.resolve(e,i),["rev-parse","HEAD"]),status:er(Ot.resolve(e,i),["status","--porcelain=v1","-z","--untracked-files=all"]),diff:er(Ot.resolve(e,i),["diff","--binary","HEAD","--submodule=diff"]),untracked:await sN(Ot.resolve(e,i))})))}async function tu(e){let t=Object.entries(process.env).map(([r,i])=>[r,i??null]).sort(([r],[i])=>r.localeCompare(i));return $("comet.native.supervisor-check-input.v2",{kind:e.kind,parent:e.parent,child:e.child,runId:e.runId,projectRoot:Ot.resolve(e.projectRoot),candidateCommit:e.candidateCommit,integrationCommit:e.integrationCommit??null,contractHash:e.contractHash??null,plans:e.plans,materials:e.materials,machineId:oN.hostname(),runtime:{execPath:process.execPath,version:process.version,platform:process.platform,arch:process.arch,environment:t},git:{head:er(e.projectRoot,["rev-parse","HEAD"]),branch:er(e.projectRoot,["branch","--show-current"]),status:er(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none"]),diff:er(e.projectRoot,["diff","--binary","HEAD","--submodule=diff"]),stagedDiff:er(e.projectRoot,["diff","--cached","--binary","--submodule=diff"]),submodules:await O$(e.projectRoot),untracked:await sN(e.projectRoot)}})}function ru(){return oN.hostname()}var hh=T(()=>{"use strict";We();Mn();pe()});import{createHash as H$}from"node:crypto";import{lstatSync as D$,readFileSync as cN,promises as lN}from"node:fs";import iu from"node:path";function pN(e){try{if(I(e,["ls-files","--",nu]))return!1;let t=iu.join(e,nu),r=D$(t);return!r.isFile()||r.isSymbolicLink()?!1:JSON.parse(cN(uN(e),"utf8")).hash===dN(cN(t))}catch{return!1}}async function fN(e){let t=iu.join(e,nu),r;try{r=await lN.readFile(t)}catch(n){if(n.code==="ENOENT")return;throw n}let i=uN(e);await lN.mkdir(iu.dirname(i),{recursive:!0}),await he(i,{hash:dN(r)},{containedRoot:e})}function tr(e,t=[]){return Za(e).every(r=>t.some(i=>r===i||r.startsWith(`${i}/`))||r===nu&&pN(e))}var nu,uN,dN,Jn=T(()=>{"use strict";We();ne();nu=".comet/config.yaml",uN=e=>iu.join(e,".comet","runtime","native","workspace-config.json"),dN=e=>H$("sha256").update(e).digest("hex")});import{createHash as q$}from"crypto";function ut(e){return q$("sha256").update(e).digest("hex")}var rr=T(()=>{"use strict"});import gN from"path";function ou(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function oj(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function sj(e,t){return ut(`comet.native.snapshot-policy.v1
228
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function vh(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function cj(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function wN(e){let t=il(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?cj(n):void 0;if(a&&!a())return!1;let o=vh(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=vh(r,c,a),o===null||o.size===0)return!1}return vh(r,o,a)?.has(r.length)??!1}}function lj(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>il(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>il(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let i=sj(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(wN),excludeMatchers:r.map(wN),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function Et(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xt(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function Kn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function ir(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function NN(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=gN.posix.normalize(e);if(r!==e||gN.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function uj(e,t){let r=Et(e,`Native snapshot entry ${t}`);xt(r,Z$,`Native snapshot entry ${t}`);let i=NN(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!su.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:ir(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!aj.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function dj(e,t){let r=Et(e,`Native snapshot omission ${t}`);if(xt(r,ej,`Native snapshot omission ${t}`),!ij.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!nj.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:NN(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:ir(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function pj(e){let t=Et(e,"Native snapshot omission overflow");if(xt(t,tj,"Native snapshot omission overflow"),typeof t.hash!="string"||!su.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:Kn(t.count,"Native snapshot omission overflow count")}}function Un(e,t){let r=Et(e,t);if(xt(r,Y$,t),typeof r.hash!="string"||!su.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=ir(r.recordCount,`${t} recordCount`),n=ir(r.storedRecordCount,`${t} storedRecordCount`),a=ir(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function yN(e){let t=Et(e,"Native Git selection evidence");if(xt(t,K$,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=Un(t.stageBefore,"Native Git selection stageBefore"),i=Un(t.combined,"Native Git selection combined"),n=Un(t.stageAfter,"Native Git selection stageAfter"),a=Un(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Un(t.finalCombined,"Native Git selection finalCombined"),s=Un(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(p=>p.overflow),l=!ou(r,n)||!ou(n,a)||!ou(i,o)||!ou(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function bN(e,t){let r=Et(e,t);if(xt(r,Q$,t),typeof r.hash!="string"||!su.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=ir(r.visitedNodeCount,`${t} visitedNodeCount`),n=ir(r.recordCount,`${t} recordCount`),a=ir(r.storedRecordCount,`${t} storedRecordCount`),o=ir(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function fj(e){let t=Et(e,"Native physical selection evidence");if(xt(t,X$,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=bN(t.before,"Native physical selection before"),i=bN(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!oj(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function gh(e){let t=Et(e,"Native content snapshot manifest");if(xt(t,W$,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!rj.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let b=Et(t.capture,"Native content snapshot capture");if(xt(b,J$,"Native content snapshot capture"),b.provider!=="git"&&b.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=b.gitSelection===void 0?void 0:yN(b.gitSelection),k=b.physicalSelection===void 0?void 0:fj(b.physicalSelection),S=null;if(b.projection!==void 0){let C=Et(b.projection,"Native content snapshot projection");if(xt(C,U$,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");S={provider:"git",...C.selection===void 0?{}:{selection:yN(C.selection)}}}if(b.provider==="git"){if(k||S)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(k&&S)throw new Error("Native physical-tree capture cannot combine selection and projection");r=S?{provider:"physical-tree",projection:S}:{provider:"physical-tree",...k?{physicalSelection:k}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=Et(t.limits,"Native content snapshot limits");xt(i,z$,"Native content snapshot limits");let n={maxFiles:Kn(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:Kn(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:Kn(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:Kn(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:Kn(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let b=Et(t.policy,"Native snapshot policy");if(xt(b,G$,"Native snapshot policy"),b.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(b.include)||!Array.isArray(b.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=lj({include:b.include,exclude:b.exclude,hash:b.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(uj),s=t.omitted.map(dj),c=ir(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:pj(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(b=>b.size>n.maxFileBytes)||o.reduce((b,x)=>b+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(b=>b.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>V$||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let p=s.filter(b=>b.reason==="git-enumeration-limit"),d=s.filter(b=>b.reason==="git-selection-changed");for(let b of[...p,...d])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(p.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let f=r?.provider==="git"?r.gitSelection:r?.projection?.selection,h=f?.status==="overflow"||f?.status==="overflow-and-changed",m=f?.status==="changed"||f?.status==="overflow-and-changed";if(h!==(p.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(m!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(b=>b.reason==="physical-enumeration-limit"),g=s.filter(b=>b.reason==="physical-selection-changed");for(let b of[...v,...g])if(b.path!=="."||b.size!==null||b.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let w=r?.physicalSelection,N=w?.status==="overflow"||w?.status==="overflow-and-changed",y=w?.status==="changed"||w?.status==="overflow-and-changed";if(N!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(y!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}var yV,V$,W$,z$,G$,J$,U$,K$,Y$,X$,Q$,Z$,ej,tj,rj,ij,nj,su,aj,bV,NV,kV,SV,EV,Jo=T(()=>{"use strict";yn();ne();gt();rr();Jt();ie();Zt();eo();yV={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},V$=1e3,W$=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),z$=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),G$=new Set(["schema","include","exclude","hash"]),J$=new Set(["provider","gitSelection","physicalSelection","projection"]),U$=new Set(["provider","selection"]),K$=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Y$=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),X$=new Set(["schema","status","before","after"]),Q$=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Z$=new Set(["path","hash","size","type","gitObjectId"]),ej=new Set(["path","size","type","reason"]),tj=new Set(["ref","hash","count"]),rj=new Set(["change-created","legacy-migration","explicit"]),ij=new Set(["file","directory","other"]),nj=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),su=/^[a-f0-9]{64}$/u,aj=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,bV=64*1024,NV=64*1024,kV={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},SV={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};EV=(1n<<256n)-1n});import{createHash as _N}from"node:crypto";import kN from"path";function Te(e,t){return e<t?-1:e>t?1:0}function yh(e){if(!Nh.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function yj(e,t){return e===t?0:e===null?-1:t===null?1:Te(e,t)}function si(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let r=kN.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||kN.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function TN(e,t){return e==="."?e:si(e,t)}function Yn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function bj(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:si(e.path,`${t} path`),hash:e.hash,size:Yn(e.size,`${t} size`),type:"file"}}function Nj(e,t){return{path:TN(e.path,`${t} path`),size:e.size===null?null:Yn(e.size,`${t} size`),type:e.type,reason:e.reason}}function kj(e,t){return Te(e.path,t.path)||Te(e.hash,t.hash)||e.size-t.size}function Sj(e,t){return Te(e.path,t.path)||Te(e.reason,t.reason)||Te(e.type,t.type)||(e.size??-1)-(t.size??-1)}function Yo(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
229
+ `,"utf8")}function oi(e,t,r){let i=`${t}
230
+ ${qc(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function Ej(e){if(Yo(e)<=Ji)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=_N("sha256");a.update(`${vj}
231
+ `),e.omissionOverflow&&oi(a,"existing-overflow",e.omissionOverflow);let o=(d,f)=>{f||(i+=1),n+=1,oi(a,"omission",d)},s=d=>{i+=1,n+=1,oi(a,"entry",d)},c=()=>{for(let d=r.length-1;d>=0;d-=1){let f=r[d];if(!(f.reason==="git-enumeration-limit"||f.reason==="git-selection-changed"||f.reason==="physical-enumeration-limit"||f.reason==="physical-selection-changed"))return r.splice(d,1),f}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;Yo(u)>Ji;){if(r.filter(f=>f.reason!=="git-enumeration-limit"&&f.reason!=="git-selection-changed"&&f.reason!=="physical-enumeration-limit"&&f.reason!=="physical-selection-changed").length>0){let f=Math.max(1,Math.ceil(r.length/4));for(let h=0;h<f;h+=1){let m=c();if(m===null)break;o(m,!0)}}else if(t.length>0){let f=Math.max(1,Math.ceil(t.length/4));for(let h of t.splice(-f))s(h)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let p=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${p}`,hash:p,count:n}}}function xj(e){let t=gh(e),r=t.entries.map((n,a)=>bj(n,`Snapshot entry ${a}`));if(r.sort(kj),new Set(r.map(n=>n.path)).size!==r.length)throw new Error("Snapshot entries must not contain duplicate paths");let i=t.omitted.map((n,a)=>Nj(n,`Snapshot omission ${a}`));return i.sort(Sj),Ej({schema:AN,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:r,omitted:i,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function lu(e){let t=new Map;for(let[r,i]of e.entries()){if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${r} kind is invalid`);let n={path:si(i.path,`Declared artifact ${r} path`),kind:i.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((r,i)=>Te(r.path,i.path)||Te(r.kind,i.kind))}function Xo(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function SN(e){return e?{hash:e.hash,size:e.size}:null}function $N(e,t,r){let i=0,n=0;for(;i<e.entries.length||n<t.entries.length;){let a=e.entries[i],o=t.entries[n],s=a===void 0?1:o===void 0?-1:Te(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(i+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&r({path:u,kind:c?l?"modified":"removed":"added",before:SN(c),after:SN(l)})}}function Rj(e,t){return{...e,attributedTo:t.filter(r=>Xo(r,e.path))}}function Cr(e,t){return{id:`scope:${$(hj,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function Cj(e,t){let r=t.omitted.map(i=>Cr({kind:"snapshot-omission",source:e,path:i.path,evidence:{reason:i.reason,size:i.size,type:i.type}},`${e} snapshot omitted ${i.path}: ${i.reason}`));return t.complete||r.push(Cr({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(Cr({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),r}function EN(e,t){return Cj(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function bh(e,t){return Te(e.kind,t.kind)||Te(e.source,t.source)||yj(e.path,t.path)||Te(e.id,t.id)}function Pj(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(bh)}function jN(e){return[...new Set(e.map((t,r)=>si(t,`Git path ${r}`)))].sort(Te)}function xN(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function _j(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function ON(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=jN(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:xN(e.baseCommit,"Native external drift base commit"),targetBranch:_j(e.targetBranch,"Native external drift target branch"),targetCommit:xN(e.targetCommit,"Native external drift target commit"),paths:t}}function Aj(e){if(typeof e.contractHash!="string"||!Nh.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:lu(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:jN(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:ON(e.externalDrift)}}}function Ij(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,u=!1,p=0,d=0;return $N(e,t,f=>{let h=r.some(m=>Xo(m,f.path));if(p+=1,c.push(f.path),!h&&!n?.has(f.path)&&(d+=1),o?.has(f.path)&&s.push(f.path),!u&&a.length<gj){let m=Rj(f,r),v=Yo(m);l+v<=Ji?(a.push(m),l+=v):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:p,totalUnattributed:d}}function HN(e,t){return Cr({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function Tj(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let r={changes:Yn(Number(t[1]),"Scope overflow change count"),unresolved:Yn(Number(t[2]),"Scope overflow unresolved count"),unattributed:Yn(Number(t[3]),"Scope overflow unattributed count")},i=Gi(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(HN(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function $j(e){let t=_N("sha256");t.update(`${mj}
232
+ `);let r=0;$N(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){oi(t,"change",n);let a=0;for(let o of e.declaredArtifacts)Xo(o,n.path)&&(a+=1,oi(t,"change-attribution",o));oi(t,"change-end",{attributionCount:a}),a===0&&oi(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&oi(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function jj(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=Ij(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let x=new Set(r.externalDrift.paths),k=new Set(o.changePaths),S=r.externalDrift.paths.filter(C=>!k.has(C)||n.some(P=>Xo(P,C)));if(S.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${S.slice(0,8).join(", ")}`);if(x.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=$(Uo,e),c=$(Uo,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[x,k]of[["baseline",e],["current",t]])for(let S of k.omitted){if(l.length>=wj)break;l.push(Cr({kind:"snapshot-omission",source:x,path:S.path,evidence:{reason:S.reason,size:S.size,type:S.type}},`${x} snapshot omitted ${S.path}: ${S.reason}`))}let p=e.omitted.length+t.omitted.length,d=[...EN("baseline",e),...EN("current",t),...o.totalChanges===0&&a===null?[Cr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],f=()=>{if(r.gitChangedPaths===void 0)return;let x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(k=>x.has(k)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(k=>!x.has(k))}},h=x=>{let k=o.candidates.slice(0,x.detailedChangeCount),S=k.filter(tt=>tt.attributedTo.length===0&&!u.has(tt.path)),C=o.totalChanges-k.length,P=o.totalUnattributed-S.length,_=p-x.detailedOmissionCount,j=P+_,ue=[...S.map(tt=>Cr({kind:"unattributed-change",source:"implementation-scope",path:tt.path,evidence:{after:tt.after,before:tt.before,changeKind:tt.kind}},`Changed path is not covered by a declared artifact: ${tt.path}`)),...l.slice(0,x.detailedOmissionCount),...d,...j>0?[HN(x.overflowHash,{changes:C,unattributed:P,unresolved:j})]:[]],de=Pj(ue),Or=x.includeGitAdvisory?f():void 0;return{schema:wh,contractHash:i,baselineProjectionRef:yh(s),baselineProjectionHash:s,currentProjectionRef:yh(c),currentProjectionHash:c,complete:de.length===0,declaredArtifacts:n,changes:k,unattributed:S,unresolvedScopes:de,noCodeReason:a,...Or?{gitAdvisory:Or}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},m=o.candidates.length,v=l.length,g=r.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let x=h({detailedChangeCount:m,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:w});if(Yo({...x,scopeHash:w})<=Ji)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let y=o.totalChanges>m||p>v?$j({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:m,detailedOmissionCount:v}):w,E=h({detailedChangeCount:m,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:y}),b={...E,scopeHash:$(IN,E)};if(Yo(b)>Ji)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return b}function nr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ar(e,t,r,i){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Gi(e,t){if(typeof e!="string"||!Nh.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function RN(e,t,r){let i=yh(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function cu(e,t){let r=nr(e,"Native snapshot projection");if(ar(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==AN)throw new Error("Native snapshot projection schema is invalid");let i=gh({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=xj(i);if($(Uo,r)!==$(Uo,n))throw new Error("Native snapshot projection is not canonical");let a=$(Uo,n);if(t!==void 0&&Gi(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function kh(e,t){let r=nr(e,`Declared artifact ${t}`);if(ar(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:si(r.path,`Declared artifact ${t} path`),kind:r.kind}}function CN(e,t){if(e===null)return null;let r=nr(e,t);return ar(r,["hash","size"],[],t),{hash:Gi(r.hash,`${t} hash`),size:Yn(r.size,`${t} size`)}}function PN(e,t){let r=nr(e,`Implementation change ${t}`);if(ar(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(kh),n=lu(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=CN(r.before,`Implementation change ${t} before`),o=CN(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:si(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function Hj(e,t){let r=nr(e,`Unresolved scope ${t}`);ar(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?TN(r.path,`Unresolved scope ${t} path`):si(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function Ko(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>si(n,`${t} ${a}`)),i=[...new Set(r)].sort(Te);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function DN(e){let t=nr(e,"Native implementation external drift");if(ar(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=Ko(t.paths,"Native external drift paths");return ON({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function uu(e){let t=nr(e,"Native implementation scope"),r=[...Oj].filter(S=>S!=="gitAdvisory"&&S!=="externalDrift");if(ar(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==wh)throw new Error("Native implementation scope schema is invalid");let i=Gi(t.contractHash,"Implementation scope contractHash"),n=Gi(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=RN(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Gi(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=RN(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(kh);if(JSON.stringify(c)!==JSON.stringify(lu(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(PN),u=[...l].sort((S,C)=>Te(S.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(S=>S.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let p=new Set(c.map(S=>`${S.kind}:${S.path}`));if(l.some(S=>S.attributedTo.some(C=>!p.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(S=>JSON.stringify(S.attributedTo)!==JSON.stringify(c.filter(C=>Xo(C,S.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=t.unattributed.map(PN),f=t.externalDrift===void 0?void 0:DN(t.externalDrift),h=new Set(f?.paths??[]),m=l.filter(S=>S.attributedTo.length===0&&!h.has(S.path));if(JSON.stringify(d)!==JSON.stringify(m))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(Hj),g=v.filter(S=>S.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let w=g[0]===void 0?null:Tj(g[0]);if(w&&(w.changes+w.unresolved===0||w.unattributed>w.changes||w.unattributed>w.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let N=t.noCodeReason,y=[...m.map(S=>Cr({kind:"unattributed-change",source:"implementation-scope",path:S.path,evidence:{after:S.after,before:S.before,changeKind:S.kind}},`Changed path is not covered by a declared artifact: ${S.path}`)),...l.length+(w?.changes??0)===0&&N===null?[Cr({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],E=v.filter(S=>S.kind==="unattributed-change"||S.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(bh))||new Set(v.map(S=>S.id)).size!==v.length||JSON.stringify(E)!==JSON.stringify(y.sort(bh))||t.complete!==(v.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let b;if(t.gitAdvisory!==void 0){let S=nr(t.gitAdvisory,"Implementation scope Git advisory");if(ar(S,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),S.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=Ko(S.changedPaths,"Git changed paths"),P=Ko(S.pathsPresentInSnapshotChanges,"Git present paths"),_=Ko(S.pathsAbsentFromSnapshotChanges,"Git absent paths"),j=[...P,..._].sort(Te);if(JSON.stringify(j)!==JSON.stringify(C)||_.some(ue=>l.some(de=>de.path===ue)))throw new Error("Implementation scope Git advisory partition is invalid");b={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:P,pathsAbsentFromSnapshotChanges:_}}let x={schema:wh,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:v,noCodeReason:N,...b?{gitAdvisory:b}:{},...f?{externalDrift:f}:{}},k=Gi(t.scopeHash,"Implementation scope scopeHash");if($(IN,x)!==k)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:k}}function Dj(e){let t=nr(e,"Native implementation scope authority");if(ar(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let r=t.declaredArtifacts.map(kh);if(JSON.stringify(r)!==JSON.stringify(lu(r)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let i;t.gitChangedPaths!==void 0&&(i=Ko(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:DN(t.externalDrift),a=Aj({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function Qo(e){let t=nr(e,"Native implementation scope bundle");ar(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=Dj(t.authority),i=cu(t.baseline),n=cu(t.current),a=uu(t.scope),o=jj(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function BN(e){let t=uu(e.scope);return Qo({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}var wh,AN,Uo,IN,hj,mj,vj,Nh,Ji,gj,wj,Oj,Xn=T(()=>{"use strict";pe();Jo();wh="comet.native.implementation-scope.v2",AN="comet.native.content-snapshot-projection.v1",Uo="comet.native.content-snapshot-projection.v1",IN="comet.native.implementation-scope.v2",hj="comet.native.unresolved-scope-id.v1",mj="comet.native.scope-detail-overflow.v1",vj="comet.native.snapshot-projection-overflow.v2",Nh=/^[a-f0-9]{64}$/u,Ji=1024*1024,gj=128,wj=128;Oj=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import LN from"node:path";function Pr(e,t){if(!qN.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function MN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function VN(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function Sh(e,t,r=2e3){let i=Ye(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function Zo(e,t){let r=LN.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||LN.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function qj(e,t,r){let i=Zo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=kn(i),a=i.toLowerCase(),o=r?Zo(r,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${i}`);return i}function Eh(e){let t=Zo(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function Qn(e,t){return e<t?-1:e>t?1:0}function du(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pu(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function WN(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function FN(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function Mj(e){let t=du(e,"Native acceptance trace");if(pu(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!qN.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let r=Zo(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=du(o,`Native acceptance trace entry ${s}`);if(pu(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(p=>typeof p!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(p=>Eh(p)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Qn))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:Zo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Sh(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Qn(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=Pr(t.traceHash,"Native acceptance trace hash");if($(Bj,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function zN(e){let t=du(e,"Native partial allowance");if(pu(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(Qn))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:VN(t.change),scopeHash:Pr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Sh(t.reason,"Partial allowance reason"),confirmedSummary:Sh(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:MN(t.sourceRevision),confirmedAt:WN(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=Pr(t.allowanceHash,"Native partial allowance hash");if($(Lj,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function xh(e){let t=du(e,"Native verification evidence");if(pu(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let r=Pr(t.implementationScopeHash,"Native verification implementation scope hash"),i=Mj(t.acceptanceTrace),n=Pr(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Pr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(d=>Eh(d));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Qn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(d=>d.evidenceRefs))].sort(Qn);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(d=>Eh(d));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Qn)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:VN(t.change),sourceRevision:MN(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Pr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:FN(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:qj(t.reportRef,"Native verification report ref"),reportHash:Pr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:FN(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:WN(t.createdAt,"Native verification timestamp")},p=Pr(t.envelopeHash,"Native verification envelope hash");if($(Fj,u)!==p)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:p}}var qN,Bj,Lj,Fj,fu=T(()=>{"use strict";pe();ii();eo();Xn();qN=/^[a-f0-9]{64}$/u,Bj="comet.native.acceptance-trace.v2",Lj="comet.native.partial-allowance.v1",Fj="comet.native.verification-evidence.v2"});var hu,Vj,Wj,zj,BV,Gj,LV,Rh=T(()=>{"use strict";pe();hu="scoped-text-safety",Vj=1,Wj=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),zj="comet.native.checker-policy.v1",BV=$(zj,{policy:hu,version:Vj,limits:Wj,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),Gj=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],LV=new Set(Gj)});function Zn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function ci(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function _r(e,t){if(typeof e!="string"||!Uj.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ht(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=Ye(e).trim();if(!r||r.length>Qj||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Ch(e,t){let r=Ht(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function es(e,t,r=Ht,i=!1,n=Zj){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function t0(e,t){if(typeof e!="string"||!Kj.test(e))throw new Error(`${t} is invalid`);return e}function r0(e){let t=Zn(e,"Native verification receipt bindings");if(ci(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!Yj.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:_r(t.contractHash,"Native verification receipt contract hash"),scopeHash:_r(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:_r(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:_r(t.artifactHash,"Native verification receipt artifact hash")}}function i0(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=Xj.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function n0(e,t,r,i){let n=Zn(t,`Native ${e} evidence`);if(e==="automated-check"){if(ci(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=Ch(n.startedAt,"Native automated-check start time"),o=Ch(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=Zn(n.worktree,"Native automated-check worktree");if(ci(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=Zn(n.afterFence,"Native automated-check after fence");if(ci(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:Ht(n.executable,"Native automated-check executable"),args:es(n.args,"Native automated-check arguments",Ht,!0),cwd:Ht(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:Ht(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:_r(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:_r(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:_r(n.outputHash,"Native automated-check output hash"),outputSummary:Ht(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){ci(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=i0(n.checkReceiptRef);if(_r(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:es(n.subjects,"Native static inspection subjects",Ht,i==="required-check"),rule:Ht(n.rule,"Native static inspection rule"),resultSummary:Ht(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return ci(n,["steps","observations"],"Native manual-evidence evidence"),{steps:es(n.steps,"Native manual evidence steps"),observations:es(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function a0(e){let t=Zn(e,"Native verification receipt");if(ci(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let r=t.kind,i=t.role,n=t.status,a=Ht(t.actor,"Native verification receipt actor"),o=es(t.acceptanceIds,"Native receipt acceptance IDs",t0,i==="required-check",e0).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:Ph,kind:r,role:i,status:n,bindings:r0(t.bindings),acceptanceIds:o,actor:a,issuedAt:Ch(t.issuedAt,"Native verification receipt issue time"),evidence:n0(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==hu||s.actor!==`native-runtime:${hu}`))throw new Error("Native required check policy identity is invalid");return s}function _h(e){let t=Zn(e,"Native verification receipt");if(ci(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==Ph)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=a0(i),a=_r(t.receiptHash,"Native verification receipt hash");if($(Jj,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}var Ph,Jj,Uj,Kj,Yj,Xj,Qj,Zj,e0,mu=T(()=>{"use strict";pe();Rh();ii();Ph="comet.native.verification-receipt.v3",Jj=Ph,Uj=/^[a-f0-9]{64}$/u,Kj=/^acceptance-[a-f0-9]{64}$/u,Yj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Xj=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Qj=4096,Zj=256,e0=1024});var rk={};ed(rk,{MAX_NATIVE_EVIDENCE_DOCUMENT_BYTES:()=>or,MAX_NATIVE_IMPLEMENTATION_SCOPE_BUNDLE_BYTES:()=>o0,listNativeVerificationReceiptRefs:()=>ek,nativeEvidenceRef:()=>li,nativeReportEvidenceRef:()=>u0,readArchivedNativeVerificationAcceptanceCounts:()=>g0,readNativeImplementationScope:()=>ns,readNativeImplementationScopeBundle:()=>gu,readNativePartialAllowance:()=>jh,readNativeVerificationEvidence:()=>Oh,readNativeVerificationReceipt:()=>wu,readNativeVerificationReportSnapshot:()=>is,removeNativeVerificationReportSnapshot:()=>XN,writeNativeImplementationScope:()=>m0,writeNativePartialAllowance:()=>v0,writeNativeVerificationEvidence:()=>tk,writeNativeVerificationReceipt:()=>ZN,writeNativeVerificationReportSnapshot:()=>rs});import{createHash as KN}from"node:crypto";import{promises as Be}from"node:fs";import Dt from"node:path";function Ah(e,t){let r=Dt.relative(e,t);return r===""||!Dt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Dt.sep}`)}function s0(e,t){return te({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ts(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Pt(r,i)?te(r,i):te(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function GN(e){let t=await Be.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Be.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function c0(e,t){let r=Dt.resolve(e),i=Dt.resolve(t);if(!Ah(r,i))throw new Error("Native evidence path is outside its change");let n=[await GN(r)],a=r;for(let o of Dt.relative(r,i).split(Dt.sep).filter(Boolean)){a=Dt.join(a,o);let s=await GN(a);if(!Ah(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function JN(e){for(let t of e){let r=await Be.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!s0(t,r)||await Be.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function l0(e,t,r={}){let i=await c0(t,Dt.dirname(e));await r.afterParentChainCaptured?.();let n=await Be.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Be.realpath(e);if(!Ah(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Be.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Be.lstat(e),Be.realpath(e)]);if(await JN(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!ts(s,n)||!ts(s,c))throw new Error("Native evidence document changed while opening");if(s.size>or)throw new Error(`Native evidence document exceeds ${or} bytes`);await r.afterOpen?.();let u=[],p=0,d=Buffer.allocUnsafe(64*1024);for(;;){let v=or+1-p,g=await o.read(d,0,Math.min(d.length,v),null);if(g.bytesRead===0)break;if(p+=g.bytesRead,p>or)throw new Error(`Native evidence document exceeds ${or} bytes`);u.push(Buffer.from(d.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[f,h,m]=await Promise.all([o.stat(),Be.lstat(e),Be.realpath(e)]);if(await JN(i),!h.isFile()||h.isSymbolicLink()||m!==a||!ts(s,f)||!ts(s,h))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,p).toString("utf8"))}finally{await o.close()}}function li(e,t){if(!YN.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function u0(e){return li("reports",e)}async function rs(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>or||KN("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return Ki({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,onCreated:e.onCreated,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function XN(e){let t=Ih(e.paths,e.name,"reports",e.hash),r=Ge(e.paths,t);await G(r,t);let i=await Be.lstat(t);if(await is(e.paths,e.name,e.hash),await G(r,t),!ts(i,await Be.lstat(t)))throw new Error("Native report evidence changed before rollback");await Be.unlink(t)}async function is(e,t,r,i,n){if(!YN.test(r))throw new Error("Native report evidence hash is invalid");let a=await sr({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==r||typeof o.content!="string"||KN("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function Ui(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function Ih(e,t,r,i,n){let a=li(r,i);return n?Dt.join(n,...a.split("/")):pf(vt(e,t),a)}async function sr(e){let t=Ih(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??Ge(e.paths,t);return await G(r,t),l0(t,r,e.hooks)}async function Ki(e){vu(e.value);let t=Ih(e.paths,e.name,e.kind,e.hash),r=Ge(e.paths,t);await G(r,t);try{let n=await sr(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return li(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await he(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await sr(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return li(e.kind,e.hash)}function vu(e){if(d0(e)>or)throw new Error(`Native evidence document exceeds ${or} bytes`)}function d0(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
233
+ `,"utf8")}function UN(e,t){return cu(e,t)}function p0(e,t){let r=uu(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function QN(e,t,r){let i=zN(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function Th(e,t,r){let i=xh(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}function f0(e){return{total:e.total,evidenced:e.evidenced,skipped:e.skipped}}function h0(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;let i=e;if(i.schema!=="comet.native.verification-evidence.v1")return null;if(i.change!==t||i.envelopeHash!==r)throw new Error("Legacy Native verification evidence ref/hash/change mismatch");let n=i.acceptanceTrace;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Legacy Native acceptance trace is invalid");let a=n,{total:o,evidenced:s,skipped:c}=a,l=typeof o=="number"?o:Number.NaN,u=typeof s=="number"?s:Number.NaN,p=typeof c=="number"?c:Number.NaN;if(a.schema!=="comet.native.acceptance-trace.v1"||!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||!Number.isSafeInteger(p)||l<0||u<0||p<0||u+p>l)throw new Error("Legacy Native acceptance trace is invalid");return{total:l,evidenced:u,skipped:p}}async function $h(e,t,r,i=!1,n){let a=await ns(e,t,r.implementationScopeRef,void 0,n);if(i&&await is(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await jh(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function m0(e){let t=Qo(e.bundle),{baseline:r,current:i,scope:n}=t;return vu(r),vu(i),vu(n),await Ki({paths:e.paths,name:e.name,kind:"snapshots",hash:n.baselineProjectionHash,value:r}),await Ki({paths:e.paths,name:e.name,kind:"snapshots",hash:n.currentProjectionHash,value:i}),Ki({paths:e.paths,name:e.name,kind:"scopes",hash:n.scopeHash,value:n})}async function gu(e,t,r,i,n){let a=Ui(r,"scopes"),o=p0(await sr({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=Ui(o.baselineProjectionRef,"snapshots"),c=Ui(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([sr({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(p=>UN(p,s)),sr({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(p=>UN(p,c))]);return BN({baseline:l,current:u,scope:o})}async function ns(e,t,r,i,n){return(await gu(e,t,r,i,n)).scope}async function v0(e){let t=QN(e.allowance,e.name,e.allowance.allowanceHash),r=await ns(e.paths,e.name,li("scopes",t.scopeHash)),i=r.unresolvedScopes.map(n=>n.id).sort();if(r.complete||JSON.stringify(i)!==JSON.stringify(t.scopeIds))throw new Error("Native partial allowance does not match a persisted partial scope");return Ki({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function jh(e,t,r,i,n){let a=Ui(r,"allowances");return QN(await sr({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function ZN(e){let t=_h(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return Ki({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function wu(e,t,r,i,n){let a=Ui(r,"receipts"),o=_h(await sr({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function ek(e,t){let r=Dt.join(vt(e,t),"evidence","receipts");await G(Ge(e,r),r);let i;try{i=await Be.readdir(r,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}return i.filter(n=>n.isFile()).map(n=>/^([a-f0-9]{64})\.json$/u.exec(n.name)?.[1]).filter(n=>n!==void 0).sort().map(n=>li("receipts",n))}async function tk(e){let t=Th(e.evidence,e.name,e.evidence.envelopeHash);if(t.schema!=="comet.native.verification-evidence.v2")throw new Error("Native active verification evidence must use v2");return await $h(e.paths,e.name,t,!0),Ki({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function Oh(e,t,r,i,n){let a=Ui(r,"verifications"),o=Th(await sr({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await $h(e,t,o,!1,n),o}async function g0(e,t,r,i){let n=Ui(r,"verifications"),a=await sr({paths:e,name:t,kind:"verifications",hash:n,changeDir:i}),o=h0(a,t,n);if(o)return o;let s=Th(a,t,n);return await $h(e,t,s,!1,i),f0(s.acceptanceTrace)}var YN,or,o0,ui=T(()=>{"use strict";ne();ie();Jt();Xn();fu();mu();YN=/^[a-f0-9]{64}$/u,or=Ji,o0=3*or});var nk={};ed(nk,{executeNativeSupervisorChecks:()=>Bh,readNativeSupervisorCheckEvidence:()=>ea});import{createHash as w0,randomUUID as y0}from"node:crypto";import{promises as ik}from"node:fs";import Dh from"node:path";function os(e){return w0("sha256").update(e).digest("hex")}function Hh(e,t){if(I(t.projectRoot,["branch","--show-current"])!==`comet/supervisor/${e}/${t.child}`||I(t.projectRoot,["rev-parse","HEAD"])!==t.baseCommit||!tr(t.projectRoot))throw new Error("Native Supervisor checks require the clean current candidate in its bound worktree")}function as(e,t,r){let i=e?.children.find(n=>n.name===t)?.task;if(!i||i.role!=="verifier"||i.runId!==r)throw new Error("Native Supervisor check runId is not current");return i}async function b0(e,t){return Promise.all(t.map(async r=>{let i=eu(r),n=await G(e,Dh.resolve(e,...i.logRef.split(/[\\/]/u))),a=await ik.readFile(n,"utf8"),o=Ye(a);return{...i,logContent:o.slice(0,128*1024),logDigest:os(o)}}))}function N0(e,t){return typeof e.logContent=="string"&&typeof e.logDigest=="string"&&e.logDigest.length>0&&t.status===e.status&&t.id===e.id&&t.name===e.name&&JSON.stringify(t.argvDisplay)===JSON.stringify(e.argvDisplay)&&t.cwdRef===e.cwdRef&&t.exitCode===e.exitCode&&t.signal===e.signal&&t.timedOut===e.timedOut&&t.durationMs===e.durationMs&&t.startedAt===e.startedAt&&t.completedAt===e.completedAt&&t.repeatable===e.repeatable&&t.logRef===e.logRef}async function k0(e){try{let t=me(e.paths,e.parent);return(await Promise.all(e.checks.map(async i=>{if(typeof i.logContent!="string"||typeof i.logDigest!="string")return!1;let n=await G(t,Dh.resolve(t,...i.logRef.split(/[\\/]/u))),a=Ye(await ik.readFile(n,"utf8"));return os(a)===i.logDigest&&a.slice(0,128*1024)===i.logContent}))).every(Boolean)}catch{return!1}}function S0(e){if(e===void 0)return null;let t=new Set(e);if(t.size===0||t.size!==e.length)throw new Error("Native Supervisor retry IDs must be non-empty and unique");return t}function E0(e,t,r){if(!e)throw new Error("Native Supervisor check retry requires per-check Runtime state");let i=new Map(t.map(n=>[n.id,n]));for(let n of r){let a=e.find(s=>s.id===n),o=i.get(n);if(!a||!o||a.status!=="interrupted")throw new Error(`Native Supervisor retry ID is not an interrupted current check: ${n}`);if(!a.repeatable||!o.repeatable)throw new Error(`Native Supervisor check ${n} is not repeatable and cannot be retried`);if(a.executionCount>=3)throw new Error(`Native Supervisor check retry limit (3) reached: ${n}`)}}async function Bh(e){if(e.plans.length===0||new Set(e.plans.map(({id:l})=>l)).size!==e.plans.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(e.plans.some(({repeatable:l})=>!l))throw new Error("Native Supervisor checks must be repeatable for safe recovery");if(e.materials.some(({name:l,content:u})=>!l.trim()||Buffer.byteLength(u)>1024*1024))throw new Error("Native Supervisor external material name or size is invalid");let t=S0(e.retryCheckIds),r=await A(e.paths,"reserve Supervisor checks",async()=>{let l=await D(e.paths,e.parent),u=as(l,e.child,e.runId);Hh(e.parent,u),lt(u.projectRoot,e.plans);let p=ru(),d=await tu({kind:"child",parent:e.parent,child:e.child,runId:e.runId,projectRoot:u.projectRoot,candidateCommit:u.baseCommit,contractHash:u.contractHash??null,plans:e.plans,materials:e.materials}),f=$("comet.native.supervisor-check-plan.v2",{machineId:p,inputFingerprint:d}),h=u.checkExecution;if(h?.status==="running"){let w=await Fn(h.ownerPid,h.ownerIdentity),N=Date.parse(h.expiresAt??"")||Date.parse(h.startedAt)+3e4;if(w){if(!(Date.now()<N))throw new Error("Native Supervisor check lease expired while owner PID is alive; inspect the original execution before retrying");if(h.key!==f)throw new Error("Native Supervisor check plan is already running with different inputs");return{task:structuredClone(u),execute:!1}}let y=h.activeProcess;if(y===void 0||y?.status==="starting")throw new Error(`Native Supervisor check process registration is incomplete. Check logs in ${Dh.join(me(e.paths,e.parent),"logs","checks")} for operation ${h.operationId}; stop any remaining check process in ${u.projectRoot}, then submit supervisor-cancel for child ${e.child} and runId ${u.runId}, and dispatch a new Verifier for the preserved candidate.`);if(y&&await Fn(y.pid,y.identity)){if(!(Date.now()<N))throw new Error(`Native Supervisor check ${y.checkId} is still running as PID ${y.pid} after its owner exited and lease expired; stop that original check process, then retry supervisor-checks for ${e.child}.`);return{task:structuredClone(u),execute:!1}}if(h.checkStates?.length&&h.checkStates.every(({status:b})=>b==="passed"||b==="failed")&&h.receiptRef){h.status="completed";try{return await ea({...e,task:u,receiptRef:h.receiptRef}),l.stateVersion+=1,await q(e.paths,l),{task:structuredClone(u),execute:!1,key:h.key}}catch{h.status="interrupted"}}h.status="interrupted";for(let b of h.checkStates??[])(b.status==="planned"||b.status==="running")&&(b.status="interrupted")}let m=h?.key===f&&h.machineId===p&&h.inputFingerprint===d;if(t){if(!m||h?.status!=="interrupted")throw new Error("Native Supervisor check retry requires the interrupted current plan on the same candidate, machine and workspace");E0(h.checkStates,e.plans,t)}else if(h?.status==="interrupted"&&m)return{task:structuredClone(u),execute:!1,key:f};if(h?.status==="completed"&&m&&h.receiptRef)try{return await ea({...e,task:u,receiptRef:h.receiptRef}),{task:structuredClone(u),execute:!1,key:f}}catch{}let v=t&&h?.checkStates?h.checkStates.map(w=>t.has(w.id)?{...w,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{...w}):e.plans.map(Gn),g=e.plans.map(w=>v.find(N=>N.id===w.id)??Gn(w));return u.checkExecution={operationId:y0(),key:f,status:"running",ownerPid:process.pid,ownerIdentity:await ct(process.pid)??void 0,activeProcess:null,startedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+e.plans.reduce((w,N)=>w+N.timeoutMs,0)+3e4).toISOString(),machineId:p,inputFingerprint:d,checkStates:g},u.checksReason="running",l.stateVersion+=1,await q(e.paths,l),{task:structuredClone(u),execute:!0,key:f,plansToExecute:e.plans.filter(w=>!t||t.has(w.id))}}),{task:i}=r,n=i.checkExecution.operationId;if(!r.execute)return i.checkExecution.status==="completed"&&i.checkExecution.receiptRef&&await ea({...e,task:i,receiptRef:i.checkExecution.receiptRef}),{status:i.checkExecution.status==="completed"?"completed":i.checkExecution.status==="interrupted"?"interrupted":"running",operationId:n,...i.checkExecution.receiptRef?{receiptRef:i.checkExecution.receiptRef}:{}};let a=me(e.paths,e.parent),o=r.plansToExecute,s=async l=>{await A(e.paths,"register Supervisor check process",async()=>{let u=await D(e.paths,e.parent),p=as(u,e.child,e.runId);if(p.checkExecution?.operationId!==n||p.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");if(l?.status==="starting"){let d=p.checkExecution.checkStates?.find(({id:f})=>f===l.checkId);if(!d||d.status!=="planned")throw new Error(`Native Supervisor check ${l.checkId} is not planned`);d.status="running",d.executionCount+=1,d.startedAt=new Date().toISOString(),d.completedAt=null,d.logRef=null}p.checkExecution.activeProcess=l,u.stateVersion+=1,await q(e.paths,u)})},c=async l=>A(e.paths,"record Supervisor check result",async()=>{let u=await D(e.paths,e.parent),p=as(u,e.child,e.runId);if(p.checkExecution?.operationId!==n||p.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");let d=p.checkExecution.checkStates?.find(({id:f})=>f===l.id);if(!d)throw new Error(`Native Supervisor check state is missing: ${l.id}`);Object.assign(d,Zl(d,l)),p.checkExecution.activeProcess=null,u.stateVersion+=1,await q(e.paths,u)});try{for(let v of o){await s({status:"starting",checkId:v.id});let g=await Bi({projectRoot:i.projectRoot,runtimeDir:a,operationId:n,plan:v,onSpawn:async({pid:w})=>{await s({status:"running",checkId:v.id,pid:w,identity:await ct(w)??void 0})}});if(await c(g),g.status==="interrupted")throw new Error(`Native Supervisor check ${g.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let l=await D(e.paths,e.parent),u=as(l,e.child,e.runId);Hh(e.parent,u);let p=u.checkExecution?.checkStates;if(!p||p.some(({status:v})=>!["passed","failed"].includes(v)))throw new Error("Native Supervisor check plan remains incomplete; retry each interrupted check explicitly");let d=await b0(a,p),f={schema:"comet.native.supervisor-checks.v1",parent:e.parent,child:e.child,runId:e.runId,candidateCommit:i.baseCommit,contractHash:i.contractHash??null,operationId:n,planHash:r.key,machineId:u.checkExecution.machineId,inputFingerprint:u.checkExecution.inputFingerprint,checks:d,materials:e.materials.map(({name:v,content:g})=>{let w=Ye(g);return{name:v,content:w,hash:os(w)}})},h=JSON.stringify(f),m=await rs({paths:e.paths,name:e.parent,hash:os(h),text:h});return await A(e.paths,"complete Supervisor checks",async()=>{let v=await D(e.paths,e.parent),g=as(v,e.child,e.runId);if(g.checkExecution?.operationId!==n)throw new Error("Native Supervisor check operation is stale");Hh(e.parent,g),g.checkExecution.status="completed",g.checkExecution.receiptRef=m,g.checkExecution.activeProcess=null,g.checksReason="completed",v.stateVersion+=1,await q(e.paths,v)}),{status:"completed",operationId:n,receiptRef:m}}catch(l){throw await A(e.paths,"interrupt Supervisor checks",async()=>{let u=await D(e.paths,e.parent),p=u?.children.find(({name:d})=>d===e.child)?.task;if(p?.runId===e.runId&&p.checkExecution?.operationId===n){p.checkExecution.status="interrupted",p.checkExecution.activeProcess=null;for(let d of p.checkExecution.checkStates??[])(d.status==="planned"||d.status==="running")&&(d.status="interrupted");p.checksReason="not-run",u.stateVersion+=1,await q(e.paths,u)}}),l}}async function ea(e){let t=/^runtime\/evidence\/reports\/([a-f0-9]{64})\.json$/u.exec(e.receiptRef);if(!t)throw new Error("Native Supervisor receipt ref is invalid");let r=JSON.parse(await is(e.paths,e.parent,t[1])),i=e.task,n=i.checkExecution?.checkStates,a=n!==void 0&&Array.isArray(r.checks)&&r.checks.length===n.length&&r.checks.every((s,c)=>N0(s,n[c])),o=Array.isArray(r.checks)&&await k0({paths:e.paths,parent:e.parent,checks:r.checks});if(r.schema!=="comet.native.supervisor-checks.v1"||r.parent!==e.parent||r.child!==i.child||r.runId!==i.runId||r.candidateCommit!==i.baseCommit||r.contractHash!==(i.contractHash??null)||r.operationId!==i.checkExecution?.operationId||r.planHash!==i.checkExecution.key||r.machineId!==i.checkExecution.machineId||r.inputFingerprint!==i.checkExecution.inputFingerprint||i.checkExecution.status!=="completed"||i.checkExecution.receiptRef!==e.receiptRef||!Array.isArray(r.checks)||r.checks.length===0||!a||!o||!Array.isArray(r.materials)||r.materials.some(({content:s,hash:c})=>os(s)!==c))throw new Error("Native Supervisor receipt does not match the current candidate, runId, contract or execution");return r}var Lh=T(()=>{"use strict";Jn();We();Ao();pe();Mn();hh();ui();ve();ie();ii();kr()});var lk=hr(Gt(),1);import{promises as I0}from"node:fs";import Bt from"node:path";yn();bn();import{execFileSync as H_}from"child_process";import D_ from"fs";import Ri from"path";import{AsyncLocalStorage as Xw}from"node:async_hooks";Xa();var Ci=new Xw,Qw=new Xw;function Zw(e){return Ci.getStore()?e():Ci.run(new Map,e)}function B_(e){let t=Ci.getStore();for(let r of e)t?.set(Jr(r.root),e);return e}function Ur(e,t){return Ka(()=>H_("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function Kr(e,t){return Jr(e)===Jr(t)}function Jr(e){let t=Ri.resolve(e);try{let r=D_.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function oe(e){try{let t=Qw.getStore()?.get(Jr(e)),r=Ci.getStore()?.get(t??Jr(e));if(r){let c=Yw(t??e,r);if(c)return c;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=Ri.resolve(Ur(e,["rev-parse","--show-toplevel"])),n=Ci.getStore()?.get(Jr(i))??ey(e),a=Yw(i,n);if(Ci.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=Ur(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Kr(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Bc(e){try{let t=Ci.getStore()?.get(Qw.getStore()?.get(Jr(e))??Jr(e));return t?t.map(r=>({...r})):(Ur(e,["rev-parse","--is-inside-work-tree"]),ey(e))}catch{return[]}}function ey(e){let t=L_(Ur(e,["worktree","list","--porcelain","-z"]));return B_(t),t.map(r=>({...r}))}function L_(e){let t=e.split("\0"),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:Ri.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}function gr(e){return Bc(e).map(t=>t.root)}function Yw(e,t){let r=t.find(a=>Kr(Ri.resolve(a.root),Ri.resolve(e)));if(!r)return null;let i=Ri.resolve(t[0].root),n=Ri.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!Kr(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function ty(e){try{return Ur(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function Nn(e,t){try{return Ur(e,["check-ref-format","--branch",t]),Ur(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function wr(e,t){try{let r=Ur(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}We();rt();pe();gt();ie();at();hl();hl();Hi();kr();import{randomUUID as R0}from"node:crypto";import yu from"node:path";We();Ao();ne();pe();Mn();ve();ie();hh();Hi();kr();Jn();We();import{promises as Go}from"node:fs";import Qe from"node:path";gt();Jn();Ho();ie();var ai=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function vN(e,t){let r=Qe.relative(e,t);return r===""||!Qe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Qe.sep}`)}function hN(e){return JSON.stringify(e.native)}async function au(e,t){let r=await Oe(e);if(r&&t){if(hN(r)!==hN(t))throw new Error(`Native worktree configuration differs from the source project: ${Qe.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await al(e,t),await fN(e),!0):!1}async function B$(e,t){if(!vN(e,t))return!1;let i=`/${Qe.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=I(e,["rev-parse","--git-common-dir"]),a=Qe.resolve(e,n),o=Qe.join(a,"info","exclude"),s="";try{s=await Go.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await Go.mkdir(Qe.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
217
234
  `)?"":`
218
- `;return await fo.appendFile(o,`${c}${i}
219
- `,"utf8"),!0}function PI(e,t,r){let i=ze.resolve(e,r??ze.join(".worktrees",t)),n=ze.resolve(e,I(e,["rev-parse","--git-common-dir"]));if(Fy(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(nr(e).some(a=>Ki(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function _I(e){try{throw await fo.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function qy(e){try{return await fo.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Np(e){let t=ze.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=ie(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await Dr(t,e.sourceConfig?.native.artifact_root??"docs");return Bw([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=ie(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;Gd(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(Gd(t,o),!Yi(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let p=!1;if(!a){if(!Zs(t))throw new Error("Native branch isolation requires a clean current working directory");if(Yi(t,n))throw new Error(`Native change branch already exists: ${n}`);I(t,["switch","-c",n,o]),p=!0}let m;try{m=await kl(t,e.sourceConfig)}catch(h){throw new Vr(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let p=e.worktreePath?ze.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Ki(p,i.currentWorktreeRoot))throw new Error(`Native worktree path ${p} does not match the current worktree ${i.currentWorktreeRoot}`);let m;try{m=await kl(t,e.sourceConfig)}catch(h){throw new Vr(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}let s=Qs(i.primaryWorktreeRoot),c=s.find(p=>p.branch===n);if(c&&await qy(c.root)){let p=e.worktreePath?ze.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Ki(p,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let m;try{m=await kl(c.root,e.sourceConfig)}catch(h){throw new Vr(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}c&&!await qy(c.root)&&(I(i.primaryWorktreeRoot,["worktree","prune"]),s=Qs(i.primaryWorktreeRoot));let l=Yi(t,n);if(s.some(p=>p.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=PI(i.primaryWorktreeRoot,e.name,e.worktreePath);await _I(u);let f=await RI(i.primaryWorktreeRoot,u),d={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:f,configInitialized:!1};try{I(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),d.createdBranch=!l,d.createdWorktree=!0,d.configInitialized=await kl(u,e.sourceConfig)}catch(p){throw new Vr(`Native worktree preparation is incomplete: ${p.message}`,d,{cause:p})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:d}})}function Dl(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}async function zp(e){let t=Hl.join(".worktrees",`${e.parent}-integration`);return Np({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:Dl(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function Jp(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return Np({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:Hl.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function vj(e){if(e===void 0)return null;let t=new Set(e);if(t.size===0||t.size!==e.length)throw new Error("Native Supervisor retry IDs must be non-empty and unique");return t}function gj(e,t,r){if(!e)throw new Error("Native Supervisor check retry requires per-check Runtime state");let i=new Map(t.map(n=>[n.id,n]));for(let n of r){let a=e.find(s=>s.id===n),o=i.get(n);if(!a||!o||a.status!=="interrupted")throw new Error(`Native Supervisor retry ID is not an interrupted current check: ${n}`);if(!a.repeatable||!o.repeatable)throw new Error(`Native Supervisor check ${n} is not repeatable and cannot be retried`);if(a.executionCount>=3)throw new Error(`Native Supervisor check retry limit (3) reached: ${n}`)}}function AN(e,t,r){let i=ie(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!zt(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=I(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return I(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return I(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(I(e,["merge","--ff-only",r]),I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function Ro(e){if(!zt(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=I(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Hl.resolve(t)!==Hl.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=I(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return I(e.integration.worktree,["rev-parse","HEAD"])}function IN(e,t,r){let i=ie(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!zt(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}async function Gp(e){let t=vj(e.retryCheckIds),r=await _(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let p=await O(e.paths,e.state.parent)??e.state,m=p.integration.checkExecution;if(m?.status==="running"){if(await mn(m.ownerPid,m.ownerIdentity))throw new Error("Native Supervisor integration checks are already running; wait for the original execution");if(m.activeProcess===void 0||m.activeProcess?.status==="starting")throw new Error("Native Supervisor integration check launch was interrupted; inspect the original check process before retrying");if(m.activeProcess&&await mn(m.activeProcess.pid,m.activeProcess.identity))throw new Error("Native Supervisor integration check process is still running after its owner stopped; wait for that process before retrying")}if(p.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let h=p.children.find(({name:S})=>S===e.name);if(!h)throw new Error(`Native Supervisor child ${e.name} does not exist`);let g=gw(p).find(({status:S})=>S!=="integrated"&&S!=="archived");if(g&&g.name!==e.name)throw new Error(`Native Supervisor integration order requires ${g.name} before ${e.name}`);if(h.status!=="verified"||!h.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);if(e.checkPlans){if(e.checkPlans.some(({repeatable:x})=>!x))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(e.checkPlans.length===0||new Set(e.checkPlans.map(({id:x})=>x)).size!==e.checkPlans.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(Ye(p.integration.worktree,e.checkPlans),!h.verification?.receiptRef||!h.verification.execution)throw new Error("Native Supervisor integration requires current Runtime verification evidence; reverify the child");let{readNativeSupervisorCheckEvidence:S}=await Promise.resolve().then(()=>(Wp(),_N)),N=await S({paths:e.paths,parent:p.parent,task:h.verification.execution,receiptRef:h.verification.receiptRef});if(N.candidateCommit!==h.verifiedCommit||N.checks.some(({status:x})=>x!=="passed"))throw new Error("Native Supervisor integration verification evidence is stale or failed")}let v=Ro(p),w=e.checkPlans!==void 0&&m?.status==="interrupted"&&m.child===e.name&&m.candidateCommit===h.verifiedCommit&&v!==p.integration.headCommit&&v===m.integrationCommit;if(v!==p.integration.headCommit){let S=(()=>{try{return I(p.integration.worktree,["merge-base","--is-ancestor",p.integration.headCommit,v]),!0}catch{return!1}})(),N=(()=>{try{return I(p.integration.worktree,["merge-base","--is-ancestor",h.verifiedCommit,v]),!0}catch{return!1}})();if(!S||!N)throw new Error(`Native Supervisor integration head drifted: expected ${p.integration.headCommit}, got ${v}`)}try{I(p.integration.worktree,["cat-file","-e",`${h.verifiedCommit}^{commit}`])}catch(S){throw new Error(`Native Supervisor verified commit is unavailable: ${h.verifiedCommit}`,{cause:S})}if(v===p.integration.headCommit&&!w){try{I(p.integration.worktree,["merge","--no-ff","--no-edit",h.verifiedCommit])}catch(S){throw new Error(`Native Supervisor integration conflict preserved in ${p.integration.worktree}`,{cause:S})}v=I(p.integration.worktree,["rev-parse","HEAD"])}let y=v;if(e.checkPlans){let S=yl(),N=await wl({kind:"integration",parent:p.parent,child:e.name,runId:h.verification?.execution?.runId??`integration:${e.name}`,projectRoot:p.integration.worktree,candidateCommit:h.verifiedCommit,integrationCommit:y,contractHash:h.contractHash??null,plans:e.checkPlans,materials:[]}),x=T("comet.native.supervisor-integration-plan.v2",{machineId:S,inputFingerprint:N}),k=m?.key===x&&m.machineId===S&&m.inputFingerprint===N&&m.child===e.name&&m.candidateCommit===h.verifiedCommit&&m.integrationCommit===y;if(t){if(!k||m?.status!=="interrupted")throw new Error("Native Supervisor integration retry requires the interrupted current plan on the same candidate, machine and workspace");gj(m.checkStates,e.checkPlans,t)}else if(m?.status==="interrupted"&&k){let P=(m.checkStates??[]).filter(({status:W})=>W==="failed");if(P.length>0)throw new Error(`Native Supervisor integration checks already failed on the identical plan (${P.map(({id:W})=>W).join(", ")}); change the integration check plan or re-verify the child instead of rerunning the same integrate`);return{completed:p}}let E=t&&m?.checkStates?m.checkStates.map(P=>t.has(P.id)?{...P,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{...P}):e.checkPlans.map(bn),C=e.checkPlans.map(P=>E.find(W=>W.id===P.id)??bn(P)),H=mj();return p.integration.checkExecution={operationId:H,key:x,child:e.name,candidateCommit:h.verifiedCommit,integrationCommit:y,status:"running",ownerPid:process.pid,ownerIdentity:await Ke(process.pid)??void 0,startedAt:new Date().toISOString(),activeProcess:null,machineId:S,inputFingerprint:N,checkStates:C},p.stateVersion+=1,await q(e.paths,p),{pending:{state:p,candidateCommit:h.verifiedCommit,integrationCommit:y,operationId:H,key:x,machineId:S,inputFingerprint:N,plansToExecute:e.checkPlans.filter(P=>!t||t.has(P.id))}}}let b=$c(p,{name:e.name,integrationCommit:y,checks:e.checks});return await q(e.paths,b),{completed:b}});if(r.completed)return r.completed;let{state:i,candidateCommit:n,integrationCommit:a,operationId:o,key:s}=r.pending,{writeNativeVerificationReportSnapshot:c}=await Promise.resolve().then(()=>(Gr(),RN)),{createHash:l}=await import("node:crypto"),u=async d=>_(e.paths,"record Supervisor integration check process",async()=>{let p=await O(e.paths,i.parent),m=p?.integration.checkExecution;if(!p||m?.operationId!==o||m.key!==s||m.status!=="running")throw new Error("Native Supervisor integration check operation is stale");if(d?.status==="starting"){let h=m.checkStates?.find(({id:g})=>g===d.checkId);if(!h||h.status!=="planned")throw new Error(`Native Supervisor check ${d.checkId} is not planned`);h.status="running",h.executionCount+=1,h.startedAt=new Date().toISOString(),h.completedAt=null,h.logRef=null}m.activeProcess=d,p.stateVersion+=1,await q(e.paths,p)}),f=async d=>_(e.paths,"record Supervisor integration check result",async()=>{let p=await O(e.paths,i.parent),m=p?.integration.checkExecution;if(!p||m?.operationId!==o||m.key!==s||m.status!=="running")throw new Error("Native Supervisor integration check operation is stale");let h=m.checkStates?.find(({id:g})=>g===d.id);if(!h)throw new Error(`Native Supervisor check state is missing: ${d.id}`);Object.assign(h,vl(h,d)),m.activeProcess=null,p.stateVersion+=1,await q(e.paths,p)});try{for(let b of r.pending.plansToExecute){await u({status:"starting",checkId:b.id});let S=await Ni({projectRoot:i.integration.worktree,runtimeDir:pe(e.paths,i.parent),operationId:o,plan:b,onSpawn:async({pid:N})=>u({status:"running",checkId:b.id,pid:N,identity:await Ke(N)??void 0})});if(await f(S),S.status==="interrupted")throw new Error(`Native Supervisor integration check ${S.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let d=await O(e.paths,i.parent),m=d?.integration.checkExecution?.checkStates;if(!d||!m||m.some(({status:b})=>!["passed","failed"].includes(b)))throw new Error("Native Supervisor integration check plan remains incomplete; retry each interrupted check explicitly");let h=m.map(gl),g=JSON.stringify({schema:"comet.native.supervisor-integration-checks.v1",parent:i.parent,child:e.name,candidateCommit:n,integrationCommit:a,operationId:o,planHash:s,results:h}),v=await c({paths:e.paths,name:i.parent,hash:l("sha256").update(g).digest("hex"),text:g}),w=h.map(b=>({name:b.name,status:b.status==="interrupted"?"incomplete":b.status,reason:b.status==="passed"?null:b.timedOut?"timed out":`exit ${b.exitCode??b.signal??"interrupted"}`,receiptRef:v})),y=w.filter(({status:b})=>b!=="passed");return await _(e.paths,"complete Supervisor integration checks",async()=>{let b=await O(e.paths,i.parent),S=b?.children.find(({name:k})=>k===e.name),N=b?.integration.checkExecution;if(!b||!S||N?.operationId!==o||N.key!==s||N.status!=="running"||N.child!==e.name||N.candidateCommit!==n||N.integrationCommit!==a||S.verifiedCommit!==n||Ro(b)!==a)throw new Error("Native Supervisor integration changed during checks");if(N.receiptRef=v,N.checks=w,y.length>0){let k=`Native Supervisor integration checks did not pass (${y.map(({name:E,reason:C})=>`${E}: ${C}`).join("; ")}); receipt ${v}`;throw N.status="interrupted",N.error=k,S.blocker=k,b.stateVersion+=1,await q(e.paths,b),new Error(k)}N.status="completed";let x=$c(b,{name:e.name,integrationCommit:a,checks:w});return await q(e.paths,x),x})}catch(d){throw await _(e.paths,"interrupt Supervisor integration checks",async()=>{let p=await O(e.paths,i.parent),m=p?.integration.checkExecution;if(p&&m?.operationId===o&&m.key===s&&m.status==="running"){m.status="interrupted",m.error=d.message,m.activeProcess=null;for(let h of m.checkStates??[])(h.status==="planned"||h.status==="running")&&(h.status="interrupted");p.stateVersion+=1,await q(e.paths,p)}}),d}}import{randomUUID as wj}from"node:crypto";import yj from"node:path";rt();st();le();gi();lr();async function Po(e){let t=Dl(e.parent),r=ar(e.paths.projectRoot,t);if(!r)return null;let i=ar(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=nr(e.paths.projectRoot).map(o=>yj.resolve(o)).find(o=>ie(o).currentBranch===t);if(!n)return null;let a=Ja({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return Ue(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}async function Up(e){return _(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await O(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await _e(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let u=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!u)continue;let f;try{f=await Jp({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),u?IN(f.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):AN(f.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(p){let m=Ve(o),h=m.children.find(({name:g})=>g===l.name);h&&(h.blocker=p.message,Ue(m,{kind:"task-blocked",child:l.name,runId:null,summary:h.blocker}),m.stateVersion+=1,o=m,c=!0);continue}let d=Ga(o,{role:u?"verifier":"builder",child:l.name,projectRoot:f.projectRoot,runId:wj()});o=d.state,s.push(d.task)}return(s.length>0||c)&&await q(e.paths,o),{state:o,tasks:s}})}function TN(e,t){if(ft(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=Ve(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Ii(e){let t=Ro(e);if(t===e.integration.headCommit)return e;try{I(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=Ve(e);return r.integration.headCommit=t,Ue(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Ti(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=Ro(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return TN(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function Kp(e,t){let r=_t.normalize(_t.resolve(e)),i=_t.normalize(_t.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function bj(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function kj(e){let t=bj(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function _o(e){try{let t=await Q({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return kj(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function An(e){return T("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function Sj(e){let t=nr(e.projectRoot);t.some(i=>Kp(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>_t.resolve(n)))]){let n=await _e(i);n&&r.push({projectRoot:i,paths:await Dr(i,n.native.artifact_root),parent:Kp(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function Ej(e,t){let r=_t.join(e.paths.changesDir,t,"comet-state.yaml");try{return await lt(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function xj(e,t){let r;try{r=await Nj.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=_t.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await lt(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function Cj(e,t,r){let i=_t.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${_t.sep}`))return null;let n=i.split(_t.sep).join("/");try{let a=(0,$N.parseDocument)(I(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:B(a.toJS({mapAsMap:!1}))}catch{return null}}function Rj(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function jN(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function je(e){let t=_t.join(e.paths.changesDir,e.state.name),r=await _o(t),i=null,n;try{n=await Fe({changeDir:t,validation:dt(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:v})=>v)}:{},policy:"advisory"})}catch(v){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${v.message}`,n=null}if(!n){let v=await O(e.paths,e.state.name,{diagnostics:!0});if(v){let w=Oc(v);return{...w,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(y=>({...y,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=An({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Br){let v=await O(e.paths,e.state.name,{diagnostics:!0});if(!v){let b=e.state.workspace.change_branch??e.state.workspace.target_branch;if(b){let S=await Po({paths:e.paths,parent:e.state.name,targetBranch:b,contract:n.contract});S&&(v=S,await q(e.paths,S))}}if(v){let b=Oc(v);return e.state.children_contract_hash!==a||n.drift?{...b,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(S=>({...S,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...b,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&b.confirmed}}let w=new Map(n.contract.children.map(b=>[b.name,b])),y=n.contract.children.map(b=>({name:b.name,summary:b.summary,dependsOn:[...b.depends_on],covers:[],status:s&&b.depends_on.every(S=>n.contract.children.filter(({name:N})=>N!==b.name).every(({name:N})=>N!==S))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let b of y){if(b.status!=="ready")continue;w.get(b.name).depends_on.length>0&&(b.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:y,readyChildren:y.filter(({status:b})=>b==="ready").map(({name:b})=>b),allDone:!1}}let c=await Sj(e.paths),l=new Set(n.contract.children.map(({name:v})=>v)),u=new Map,f=new Map;for(let v of c){let w=v.parent&&o?`refs/heads/${o}`:"HEAD";for(let y of await xj(v,l)){let b={...y,source:v,committedState:Cj(v,y.file,w)};u.set(y.state.name,[...u.get(y.state.name)??[],b])}for(let y of l){let b=await Ej(v,y);b&&f.set(y,[...f.get(y)??[],{source:v,state:b}])}}let d=new Map;for(let v of n.contract.children){let w=(u.get(v.name)??[]).find(({source:S,committedState:N})=>S.parent&&N?.name===v.name&&jN(N,o));if(w){d.set(v.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let y=u.get(v.name)?.[0];if(y){d.set(v.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${v.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let b=f.get(v.name)??[];b.length>1?d.set(v.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${v.name} has multiple active workspace owners`}):b[0]&&d.set(v.name,Rj(b[0].state,b[0].source,o))}let p=new Map(n.contract.children.map(v=>[v.name,v])),m=new Map,h=v=>{let w=m.get(v);if(w)return w;let y=p.get(v),S=y.depends_on.map(h).every(({status:H})=>H==="done"),N=d.get(v),x=N?.kind==="active"&&S?y.depends_on.filter(H=>!(u.get(H)??[]).some(({source:P,committedState:W})=>Kp(P.projectRoot,N.projectRoot)&&W?.name===H&&jN(W,o))):[],k,E=N?.message??null;N?.kind==="done"?(k=S?"done":"blocked",S||(E=`Native child ${v} was merged before its dependencies`)):N?.kind==="active"?(k=S&&x.length===0?"active":"blocked",S?x.length>0&&(E=`Native child ${v} does not include merged dependencies: ${x.join(", ")}`):E=`Native child ${v} started before its dependencies merged`):N?.kind==="blocked"?k="blocked":(k=s&&S?"ready":"pending",s||(E="Parent Shape confirmation is required"));let C={name:v,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:k,phase:N?.phase??null,projectRoot:N?.projectRoot??null,message:E};return m.set(v,C),C},g=n.contract.children.map(({name:v})=>h(v));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:g,readyChildren:g.filter(({status:v})=>v==="ready").map(({name:v})=>v),allDone:g.every(({status:v})=>v==="done")}}cn();gi();function $e(e,t,r){return e.language==="zh-CN"?r:t}function Pj(e,t,r){let i=n=>({required:!1,message:null,suggestedReply:null,agentInstruction:n});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:$e(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:$e(e,"Reply A or B","回复 A 或 B"),agentInstruction:$e(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return i($e(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i($e(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:n})=>n==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}:e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let a=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",o=a?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",s=a?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:o,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:s,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:$e(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements.","当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"),suggestedReply:$e(e,"Accept the result","接受结果"),agentInstruction:$e(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let n=r?.children.some(({status:c})=>c==="blocked")??!1,a=r?.children.some(({status:c})=>c==="needs-reverify")??!1,o=r?.children.some(({status:c})=>c==="ready"||c==="active")??!1,s=r?.children.some(({status:c,builderFailureCount:l})=>c==="blocked"&&(l??0)>=cr)??!1;return n&&!a&&!o&&!s?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:i($e(e,"Implement the confirmed scope and run focused checks. A separate pre-review is optional, not a prerequisite for Builder handoff. If review is useful, retain the same Reviewer for focused repair follow-ups rather than starting repeated full reviews. Submit the stable candidate for one complete independent verification; release completed helper tasks.","实现已确认范围并运行相关检查。额外预审是可选项,不是 Builder 交接的前置条件。确有必要审查时,保留同一个 Reviewer 复核修复及受影响范围,避免反复启动完整审查。候选稳定后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return i($e(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function _j(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function Aj(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:$e(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:$e(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function BN(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function ji(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function ON(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function Ij(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function HN(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function Tj(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function jj(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function Ur(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:BN({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[ji("summary","--summary"),Ij(e.name,e.flag)]}}function DN(e,t){return t.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:$e(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function $j(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function Bl(e){return[Ur({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Ur({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Oj(e){let t={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(i=>{let n=i.response?.kind??i.kind;return{...r,name:n,required:!1,exclusiveGroup:"runner-input",description:t[n],template:i}}):[r])}function K(e,t,r={}){let i=Tj(t)&&e.coordination_mode===void 0,n=Pj(e,i,t),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[ji("summary","--summary")],commandAlternatives:[Ur({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[ji("summary","--summary")],commandAlternatives:[Ur({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Bl({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[ji("summary","--summary")],commandAlternatives:[Ur({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Ur({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[ji("summary","--summary")],commandAlternatives:[Ur({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Bl({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[ji("summary","--summary")],commandAlternatives:Bl({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:Bl({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?BN({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:jj({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[HN("coordination-mode","--coordination-mode",Nc)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[ON()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),u=t.children.some(({status:m})=>m==="ready"||m==="active"),f=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=cr)??null,d=f===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:f.name,stateVersion:t.supervisorStateVersion},description:$e(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},p=c&&!l&&!u&&d===null;return{...a,disposition:p?"blocked":"continue",action:"advance-children",commandArgs:p?null:d!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:p?[]:d!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:p?[]:d!==null?[d]:[ji("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=ON();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${$e(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:Oj([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"blocked",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=DN(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(f=>$j(f))?{...a,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:DN(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[HN("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...Aj(e)],userCommunication:_j(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Ur({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}rt();Xa();fe();gn();import{createHash as bb,randomUUID as kb}from"node:crypto";import{promises as Qt}from"node:fs";import Zr from"node:os";import j from"node:path";ut();Fr();mi();Ma();import{randomUUID as Hj}from"node:crypto";var Ao=3,Yp=2;function Oe(e){return e.state_version+1}function Dj(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function LN(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Xp(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function Bj(e){return(e??[]).map(t=>({name:J(t.name),result:t.result,note:t.note?J(t.note):null}))}function Kr(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:J(e.summary),completed_at:e.completedAt}}function qN(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,phase:"build",status:"active",state_version:Oe(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function FN(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,status:"await-user",state_version:Oe(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function VN(e){let t=B(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!mw(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(r.review){if(r.review.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}let i=Dj(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=LN(t.acceptance),a=(r.now??new Date).toISOString();return B({...t,phase:"verify",state_version:Oe(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:n,builder_handoff:{candidate_id:r.candidateId??Hj(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:J(r.summary),addressed_acceptance_ids:i,checks:Bj(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(o=>J(o)),known_limits_truncated:!1,review:r.review?{status:"passed",summary:J(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef}:null,submitted_at:a},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function MN(e){let t=B(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt requires a current Builder candidate");return B({...t,state_version:Oe(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function Lj(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function qj(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Ne?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:J(e.response.result.summary),risks:e.response.result.risks.map(t=>J(t)),risks_truncated:!1,completed_at:e.completedAt}}function WN(e){let t=B(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=Xp(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=vw({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,knownAcceptanceIds:t.acceptance.map(({id:g})=>g),previouslyPassedAcceptanceIds:t.acceptance.filter(({result:g})=>g==="passed").map(({id:g})=>g),requiredChecksPassed:e.checks.every(({status:g})=>g==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(g=>[g.id,g])),o=t.acceptance.map(g=>{let v=a.get(g.id);return v?{...g,result:v.result,reason:J(v.reason)}:g}),s=o.filter(({result:g})=>g==="failed"||g==="blocked").map(({id:g})=>g),c=qj({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){let g=ye({...t,acceptance:o,verification:c},Kr({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),v=t.builder_handoff.identity_provider===Ne;return{response:i,state:B({...g,phase:v?"verify":"archive",status:v?"await-user":"active",state_version:Oe(t),verification_result:"pass",verification_report:"verification.md",blockers:v?[{owner:"user",reason:J("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:v?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:v?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let g=ye({...t,acceptance:o,verification:c},Kr({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...g,status:"await-user",state_version:Oe(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:J(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,u=Lj(t,s),f=l>=e.maxVerifyFailures,d=u>=3,p=f||d,m=d?"stalled":f?"budget":void 0,h=ye({...t,acceptance:o,verification:c},Kr({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...h,phase:p?"verify":"build",status:p?"await-user":"active",state_version:Oe(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:p?[{owner:"user",reason:J(m==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:u>=2?[{owner:"builder",reason:J("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:p?"await-user":"repairing",iteration:p?t.loop.iteration:t.loop.iteration+1,attempt:p?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:u,...m===void 0?{}:{stop_reason:m},execution_failure_count:0,previous_unresolved_ids:s,next_action:p?"await-user":"repair-failed-acceptance"}})}}function zN(e){let t=B(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Ne||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return B({...t,phase:"archive",status:"active",state_version:Oe(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function JN(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Ne||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=Xp(t),n=ye(t,Kr({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return B({...n,status:"await-user",state_version:Oe(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:J(e.summary),risks:[J("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:J("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function GN(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=J(e.summary),n=ye(t,Kr({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return B({...n,phase:"archive",status:"active",state_version:Oe(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:J(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function UN(e,t){let r=B(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=ye(r,Kr({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return B({...i,status:"active",state_version:Oe(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function KN(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=Ao,a=ye(t,Kr({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return B({...a,status:n?"blocked":"active",state_version:Oe(t),blockers:n?[{owner:"runtime",reason:J(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function YN(e){let t=B(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=Xp(t),a=t.acceptance.some(({result:o})=>o==="passed");return B({...t,status:"active",state_version:Oe(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function Yr(e){let t=B(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=e.failureBudget,i=r?t.loop.failed_iteration_count+1:t.loop.failed_iteration_count,n=r!==void 0&&i>=r.maxVerifyFailures,a=(e.now??new Date).toISOString(),o=ye(t,Kr({state:t,outcome:"recovery",summary:e.reason,completedAt:a})),s=new Set(t.loop.previous_unresolved_ids),c=s.size===0?LN(t.acceptance):t.acceptance.map(l=>s.has(l.id)?{...l,result:"pending",reason:null}:l);return n?B({...o,phase:"verify",status:"await-user",state_version:Oe(t),verification_result:"fail",builder_handoff:t.builder_handoff,blockers:[{owner:"user",reason:J(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${e.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...t.loop,stage:"await-user",failed_iteration_count:i,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):B({...o,phase:"build",status:"active",state_version:Oe(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:c,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:i,stop_reason:void 0,next_action:"submit-builder-candidate"}})}ne();cn();import{promises as XN}from"node:fs";import Fj from"node:os";import jo from"node:path";function Io(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function To(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function He(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function In(e,t){return e===null?null:He(e,t)}function Tn(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function Vj(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function Mj(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function jn(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Qp(e,t){if(e===null)return null;let r=He(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Wj(e,t){let r=He(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Zp(e,t){let r=He(e,t);if(!jo.isAbsolute(r))throw new Error(`${t} must be absolute`);return jo.resolve(r)}function zj(e,t){let r=`Native local checks[${t}]`,i=Io(e,r);if(To(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((u,f)=>He(u,`${r}.argv[${f}]`,!0)),a=jn(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Qp(i.startedAt,`${r}.startedAt`),s=Qp(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=Tn(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let u=Io(i.activeProcess,`${r}.activeProcess`),f=jn(u.status,["starting","running"],`${r}.activeProcess.status`);if(To(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),f==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:Tn(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:He(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:He(i.id,`${r}.id`),name:He(i.name,`${r}.name`),operationId:He(i.operationId,`${r}.operationId`),status:a,repeatable:Mj(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Tn(i.executionCount,`${r}.executionCount`),argv:n,cwd:Zp(i.cwd,`${r}.cwd`),exitCode:Vj(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:He(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:jn(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:He(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function eh(e){let t="Native local execution state",r=Io(e,t);if(To(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==Da)throw new Error(`Native local execution schema must be ${Da}`);let i=Io(r.workspace,"Native local workspace");To(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Io(r.execution,"Native local execution");To(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Qp(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:He(o.operationId,"Native local execution.operationId"),stage:jn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:jn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:In(o.executionId,"Native local execution.executionId"),status:jn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Tn(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:Wj(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:Tn(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:He(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(zj);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:Da,change:He(r.change,"Native local change"),basedOnStateVersion:Tn(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:In(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:In(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:In(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:In(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Zp(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Zp(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:In(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:He(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function re(e){return eh({schema:Da,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,candidateId:e.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:jo.resolve(e.projectRoot),worktreeRoot:jo.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:Fj.hostname()},execution:null,checks:[]})}async function Se(e){let t;try{t=await XN.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return eh(r)}function QN(e,t){let r=t?.execution;if(!(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||e.builder_handoff?.candidate_id===void 0||e.builder_handoff?.candidate_id===null||t===null||t.change!==e.name||t.basedOnStateVersion!==e.state_version||t.candidateId!==e.builder_handoff.candidate_id||r==null||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null))return r.executionId}async function F(e,t,r={}){let i=eh(t);await XN.mkdir(jo.dirname(e),{recursive:!0}),await we(e,i,r)}async function Ll(e){let t=null,r=null;try{t=await Se(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=re(e);return await F(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}le();Fr();te();async function th(e,t,r){if(!Number.isInteger(t)||t<1)throw new Error("Concurrency must be a positive integer");let i=new Array(e.length),n=0,a=async()=>{for(;n<e.length;){let o=n;n+=1,i[o]=await r(e[o],o)}};return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>a())),i}import{promises as ZN}from"node:fs";import ql from"node:path";rt();ut();te();var rh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eb="comet-state.yaml",tb="state.json";function se(e,t){if(!rh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=ql.join(e.changesDir,t);if(!be(e.changesDir,r))throw new Error("Native change path escaped");return r}function Qe(e,t){return ql.join(se(e,t),eb)}function D(e,t){return ql.join(pe(e,t),tb)}async function $n(e,t){try{let r=await ZN.readFile(Qe(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function ve(e){return Tg(e)}function Fl(e,t){let r=ie(t);if(!r.isGitWorktree||r.currentBranch===null||ar(t,r.currentBranch)===null)return null;if(!Zs(t))throw new Error("Native Supervisor Git binding requires a clean current working directory; commit or stash pending changes, then rerun the latest continuation");return{...e,change_branch:r.currentBranch,target_branch:r.currentBranch}}async function $(e,t){return lt(Qe(e,t))}async function ce(e){let t=await dn({file:Qe(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=ql.join(se(e.paths,t.name),"verification.md");await z(e.paths.nativeRoot,r),await ZN.rm(r,{force:!0})}return t}async function ih(e){let t=await $(e.paths,e.name),r=D(e.paths,e.name);try{let i=await Se(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}ne();import{promises as zl}from"node:fs";import $i from"node:path";xi();var ah=br(rr(),1);import Ho from"path";nt();ne();xi();st();le();te();Mt();po();le();te();nn();$r();var Xj=br(rr(),1);nn();$r();Hr();Hr();rn();hf();nn();Hr();var wM=4*1024*1024;var Qj=null;function Zj(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function rb(e,t){return(...r)=>{let i=Qj;if(i===null)return t(...r);let n=Zj(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}rn();var SM=rb("hookWritePolicy",async e=>(await nf(e))?.hook??{allow_paths:[]});Ta();var e$=16*1024;ff();Ea();var S1=Number.MAX_SAFE_INTEGER;ne();Dt();var H1={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER};import On from"node:path";ne();nt();le();te();var $o=/^[a-f0-9]{64}$/u,nb=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,s$=16*1024,X1=process.platform;function c$(e,t){let r=On.relative(e,t);return On.isAbsolute(r)||r===".."||r.startsWith(`..${On.sep}`)?null:r.replaceAll("\\","/")||"."}function ab(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function ob(e,t){if(e.length===0||ab(e)||e.includes("\\")||On.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=On.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function l$(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function nh(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||ab(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function u$(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(nh(e.changeBranch,"Native workspace change branch"),nh(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function d$(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!nb.test(t.baseCommit)||typeof t.targetCommit!="string"||!nb.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");nh(t.targetBranch,"Native workspace Git target branch")}function f$(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!$o.test(String(t.projectRootId))||!$o.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");l$(t.capturedAt),ob(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!$o.test(String(t.projectRootPathId))||a&&!$o.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!$o.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&d$(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(u$(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function p$(e,t){return On.join(ot(e,t),"workspace.json")}function h$(e,t){let r=p$(e,t),i=qe(e,r),n=c$(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:ob(n,"Native workspace file ref")}}async function m$(e,t){try{let r=h$(e,t),i=await Q({root:r.root,ref:r.ref,maxBytes:s$});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Oo(e,t){let r=await m$(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(f$(r),r)}no();Yc();Yc();var Vl=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Do=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Ml=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},EW=Qc("en");function At(e,t){co(t);let r=Ho.join(e.changesDir,t);if(!be(e.changesDir,r))throw new Error("Native change path escaped");return r}async function y$(e,t=Ho.dirname(e)){let r=Ho.relative(t,e).split(Ho.sep).join("/"),i=await Q({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,ah.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function sb(e,t){let r=Ho.join(At(e,t),fr);await z(e.nativeRoot,r);let i=ip(await y$(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}nt();Jt();te();var lb=["outcome","scope","nonGoals","acceptanceExamples"],cb=[...lb,"constraints","decisions","openQuestions","verificationExpectations"];var b$=new Set(["nonGoals","decisions","openQuestions"]),k$={maxFileBytes:Kd};function S$(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
220
- `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),r=o[1].trim(),i=[]):r!==null&&i.push(a)}return n(),t}function oh(e){return{valid:e.length===0,findings:e}}function sh(e){let t=[],r=0;for(;r<e.length;){let i=e.indexOf("<!--",r);if(i<0){t.push(e.slice(r));break}t.push(e.slice(r,i));let n=e.indexOf("-->",i+4);if(n<0){t.push(e.slice(i));break}r=n+3}return t.join("")}function E$(e){return sh(e).trim()}function Wl(e){let t=E$(e).split(/\r?\n/u),r=[],i=!1;for(let n of t){if(/^\s*(?:```|~~~)/u.test(n)){i=!i;continue}!i&&/^\s*#{1,6}\s*$/u.test(n)||!i&&/^\s*#{1,6}\s+/u.test(n)||!i&&/^\s*(?:[-*+]\s*|\d+[.)]\s*)$/u.test(n)||r.push(n)}return r.join(`
221
- `).trim()}function x$(e){let t=Wl(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim().toLocaleLowerCase("en-US");return/^(?:none|n\/a|not applicable|no(?:ne)?(?:\s+at\s+this\s+time)?|no\s+(?:additional\s+)?(?:non-goals?|decisions?|open\s+questions?|questions?)|无|无相关事项|没有(?:额外)?(?:非目标|决定|待解决问题)|不适用|暂无)[.!。;;::,,、 -]*$/iu.test(t)}function ub(e){let t=Wl(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/\s+/gu," ").trim();if(t.length===0)return!1;let r=t.replace(/[*_`]/gu,"").replace(/^\s*>+\s?/gmu,"").replace(/\s+/gu," ").trim();if(/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!。;;::,,、 -]*$/iu.test(r))return!0;let i=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:(?:todo|tbd|fixme)(?:\s*[::-]\s*.+)?|fill(?:\s+this\s+in)?(?:\s*[::-]\s*.+)?|placeholder(?:\s*[::-]\s*.+)?|待填写\S*|待补充\S*|<[^>]+>|\{\{[^}]+\}\})[.!。;;::,,、 -]*$/iu.test(i)}function db(e,t){let r=[];return Wl(e).length===0?r.push({code:"spec-document-empty",message:`Native target Spec is empty: ${t}. Add the complete target requirements or use an explicit no-product-behavior exemption in brief.md.`,path:t}):ub(e)&&r.push({code:"spec-document-placeholder",message:`Native target Spec contains only template placeholder content: ${t}. Replace it with complete target requirements.`,path:t}),oh(r)}function ch(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function lh(e,t,r={}){let i=[],n;try{n=(await Q({root:e,ref:t,maxBytes:k$.maxFileBytes})).text}catch(s){return oh([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,c]of S$(n))a.set(Xc(s)??s,c);for(let s of cb)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?cb:lb;for(let s of o){let c=a.get(s)??"";Wl(c).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):ub(c)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!b$.has(s)&&x$(c)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:t})}return ch(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),oh(i)}nt();fe();le();il();Zf();ut();Fr();ne();xi();mi();import{promises as C$}from"node:fs";function It(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
222
- `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function gr(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function R$(e){return e.archived?We(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?We(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?We(e.language,"Verification passed; ready to archive","验收通过,可归档"):We(e.language,"Verification passed","验收通过")}function P$(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?We(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?R$(e):e.verification_result==="blocked"?We(t,"Blocked","已阻塞"):e.verification_result==="fail"?We(t,"Failed","未通过"):We(t,"Pending","待处理")}function _$(e){if(e.verification?.assurance==="semantic-verification-unavailable")return We(e.language,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查");if(e.verification_result==="fail")return We(e.language,"Fix unresolved acceptance criteria and verify again","修复未通过的验收项后重新验证");if(e.verification_result==="blocked")return We(e.language,"Resolve the reported blockers and resume verification","解决报告中的阻塞项后恢复验证");let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Ne?Ne:"host-attested"),r=t===Ne&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function A$(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=d=>ap(r,d),n=(d,p)=>We(r,d,p),a=e.acceptance.map(d=>`| ${gr(d.id)} | ${gr(d.result)} | ${gr(d.source)} | ${gr(d.text)} | ${gr(It(d.reason))} |`).join(`
223
- `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let p=d.argv_display.map(It).join(" ");return`| ${gr(It(d.name))} | ${gr(p||"—")} | ${gr(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
224
- `),s=e.builder_handoff?[`### ${n("Builder-reported evidence","Builder 报告的证据")}`,"",n("These are Builder reports, not Runtime check receipts or independent verification results.","以下为 Builder 报告,不等同于 Runtime 检查凭据或独立验收结果。"),"",...e.builder_handoff.checks.map(d=>`- ${It(d.name)}: ${d.result} — ${It(d.note)}`),...e.builder_handoff.checks_truncated?[n("Check list was truncated.","检查列表已截断。")]:[],...e.builder_handoff.known_limits.map(d=>`- ${n("Known limitation","已知限制")}: ${It(d)}`),...e.builder_handoff.known_limits_truncated?[n("Limitations list was truncated.","限制列表已截断。")]:[]].join(`
225
- `):"",c=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${It(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
226
- `),l=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${It(d)}`).join(`
227
- `),u=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${gr(It(d.summary))} | ${d.completed_at} |`)].join(`
228
- `),f=t?.finalVerification.layers?`
235
+ `;return await Go.appendFile(o,`${c}${i}
236
+ `,"utf8"),!0}function L$(e,t,r){let i=Qe.resolve(e,r??Qe.join(".worktrees",t)),n=Qe.resolve(e,I(e,["rev-parse","--git-common-dir"]));if(vN(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(gr(e).some(a=>Kr(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function F$(e){try{throw await Go.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function mN(e){try{return await Go.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function mh(e){let t=Qe.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=oe(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await ei(t,e.sourceConfig?.native.artifact_root??"docs");return sb([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=oe(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;qp(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(qp(t,o),!Nn(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let f=!1;if(!a){if(!Lc(t))throw new Error("Native branch isolation requires a clean current working directory");if(Nn(t,n))throw new Error(`Native change branch already exists: ${n}`);I(t,["switch","-c",n,o]),f=!0}let h;try{h=await au(t,e.sourceConfig)}catch(m){throw new ai(`Native branch preparation is incomplete: ${m.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:f,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:f,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:h}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let f=e.worktreePath?Qe.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(f&&!Kr(f,i.currentWorktreeRoot))throw new Error(`Native worktree path ${f} does not match the current worktree ${i.currentWorktreeRoot}`);let h;try{h=await au(t,e.sourceConfig)}catch(m){throw new ai(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:h}}}let s=Bc(i.primaryWorktreeRoot),c=s.find(f=>f.branch===n);if(c&&await mN(c.root)){let f=e.worktreePath?Qe.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(f&&!Kr(f,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let h;try{h=await au(c.root,e.sourceConfig)}catch(m){throw new ai(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:h}}}c&&!await mN(c.root)&&(I(i.primaryWorktreeRoot,["worktree","prune"]),s=Bc(i.primaryWorktreeRoot));let l=Nn(t,n);if(s.some(f=>f.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=L$(i.primaryWorktreeRoot,e.name,e.worktreePath);await F$(u);let p=await B$(i.primaryWorktreeRoot,u),d={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:p,configInitialized:!1};try{I(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),d.createdBranch=!l,d.createdWorktree=!0,d.configInitialized=await au(u,e.sourceConfig)}catch(f){throw new ai(`Native worktree preparation is incomplete: ${f.message}`,d,{cause:f})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:d}})}function bu(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}async function Fh(e){let t=yu.join(".worktrees",`${e.parent}-integration`);return mh({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:bu(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function qh(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return mh({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:yu.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function C0(e){if(e===void 0)return null;let t=new Set(e);if(t.size===0||t.size!==e.length)throw new Error("Native Supervisor retry IDs must be non-empty and unique");return t}function P0(e,t,r){if(!e)throw new Error("Native Supervisor check retry requires per-check Runtime state");let i=new Map(t.map(n=>[n.id,n]));for(let n of r){let a=e.find(s=>s.id===n),o=i.get(n);if(!a||!o||a.status!=="interrupted")throw new Error(`Native Supervisor retry ID is not an interrupted current check: ${n}`);if(!a.repeatable||!o.repeatable)throw new Error(`Native Supervisor check ${n} is not repeatable and cannot be retried`);if(a.executionCount>=3)throw new Error(`Native Supervisor check retry limit (3) reached: ${n}`)}}function ak(e,t,r){let i=oe(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!tr(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=I(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return I(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return I(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(I(e,["merge","--ff-only",r]),I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function ss(e){if(!tr(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=I(e.integration.worktree,["rev-parse","--show-toplevel"]);if(yu.resolve(t)!==yu.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=I(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return I(e.integration.worktree,["rev-parse","HEAD"])}function ok(e,t,r){let i=oe(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!tr(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}async function Mh(e){let t=C0(e.retryCheckIds),r=await A(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let f=await D(e.paths,e.state.parent)??e.state,h=f.integration.checkExecution;if(h?.status==="running"){if(await Fn(h.ownerPid,h.ownerIdentity))throw new Error("Native Supervisor integration checks are already running; wait for the original execution");if(h.activeProcess===void 0||h.activeProcess?.status==="starting")throw new Error("Native Supervisor integration check launch was interrupted; inspect the original check process before retrying");if(h.activeProcess&&await Fn(h.activeProcess.pid,h.activeProcess.identity))throw new Error("Native Supervisor integration check process is still running after its owner stopped; wait for that process before retrying")}if(f.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let m=f.children.find(({name:E})=>E===e.name);if(!m)throw new Error(`Native Supervisor child ${e.name} does not exist`);let v=By(f).find(({status:E})=>E!=="integrated"&&E!=="archived");if(v&&v.name!==e.name)throw new Error(`Native Supervisor integration order requires ${v.name} before ${e.name}`);if(m.status!=="verified"||!m.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);if(e.checkPlans){if(e.checkPlans.some(({repeatable:x})=>!x))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(e.checkPlans.length===0||new Set(e.checkPlans.map(({id:x})=>x)).size!==e.checkPlans.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(lt(f.integration.worktree,e.checkPlans),!m.verification?.receiptRef||!m.verification.execution)throw new Error("Native Supervisor integration requires current Runtime verification evidence; reverify the child");let{readNativeSupervisorCheckEvidence:E}=await Promise.resolve().then(()=>(Lh(),nk)),b=await E({paths:e.paths,parent:f.parent,task:m.verification.execution,receiptRef:m.verification.receiptRef});if(b.candidateCommit!==m.verifiedCommit||b.checks.some(({status:x})=>x!=="passed"))throw new Error("Native Supervisor integration verification evidence is stale or failed")}let g=ss(f),w=e.checkPlans!==void 0&&h?.status==="interrupted"&&h.child===e.name&&h.candidateCommit===m.verifiedCommit&&g!==f.integration.headCommit&&g===h.integrationCommit;if(g!==f.integration.headCommit){let E=(()=>{try{return I(f.integration.worktree,["merge-base","--is-ancestor",f.integration.headCommit,g]),!0}catch{return!1}})(),b=(()=>{try{return I(f.integration.worktree,["merge-base","--is-ancestor",m.verifiedCommit,g]),!0}catch{return!1}})();if(!E||!b)throw new Error(`Native Supervisor integration head drifted: expected ${f.integration.headCommit}, got ${g}`)}try{I(f.integration.worktree,["cat-file","-e",`${m.verifiedCommit}^{commit}`])}catch(E){throw new Error(`Native Supervisor verified commit is unavailable: ${m.verifiedCommit}`,{cause:E})}if(g===f.integration.headCommit&&!w){try{I(f.integration.worktree,["merge","--no-ff","--no-edit",m.verifiedCommit])}catch(E){throw new Error(`Native Supervisor integration conflict preserved in ${f.integration.worktree}`,{cause:E})}g=I(f.integration.worktree,["rev-parse","HEAD"])}let N=g;if(e.checkPlans){let E=ru(),b=await tu({kind:"integration",parent:f.parent,child:e.name,runId:m.verification?.execution?.runId??`integration:${e.name}`,projectRoot:f.integration.worktree,candidateCommit:m.verifiedCommit,integrationCommit:N,contractHash:m.contractHash??null,plans:e.checkPlans,materials:[]}),x=$("comet.native.supervisor-integration-plan.v2",{machineId:E,inputFingerprint:b}),k=h?.key===x&&h.machineId===E&&h.inputFingerprint===b&&h.child===e.name&&h.candidateCommit===m.verifiedCommit&&h.integrationCommit===N;if(t){if(!k||h?.status!=="interrupted")throw new Error("Native Supervisor integration retry requires the interrupted current plan on the same candidate, machine and workspace");P0(h.checkStates,e.checkPlans,t)}else if(h?.status==="interrupted"&&k){let _=(h.checkStates??[]).filter(({status:j})=>j==="failed");if(_.length>0)throw new Error(`Native Supervisor integration checks already failed on the identical plan (${_.map(({id:j})=>j).join(", ")}); change the integration check plan or re-verify the child instead of rerunning the same integrate`);return{completed:f}}let S=t&&h?.checkStates?h.checkStates.map(_=>t.has(_.id)?{..._,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{..._}):e.checkPlans.map(Gn),C=e.checkPlans.map(_=>S.find(j=>j.id===_.id)??Gn(_)),P=R0();return f.integration.checkExecution={operationId:P,key:x,child:e.name,candidateCommit:m.verifiedCommit,integrationCommit:N,status:"running",ownerPid:process.pid,ownerIdentity:await ct(process.pid)??void 0,startedAt:new Date().toISOString(),activeProcess:null,machineId:E,inputFingerprint:b,checkStates:C},f.stateVersion+=1,await q(e.paths,f),{pending:{state:f,candidateCommit:m.verifiedCommit,integrationCommit:N,operationId:P,key:x,machineId:E,inputFingerprint:b,plansToExecute:e.checkPlans.filter(_=>!t||t.has(_.id))}}}let y=yl(f,{name:e.name,integrationCommit:N,checks:e.checks});return await q(e.paths,y),{completed:y}});if(r.completed)return r.completed;let{state:i,candidateCommit:n,integrationCommit:a,operationId:o,key:s}=r.pending,{writeNativeVerificationReportSnapshot:c}=await Promise.resolve().then(()=>(ui(),rk)),{createHash:l}=await import("node:crypto"),u=async d=>A(e.paths,"record Supervisor integration check process",async()=>{let f=await D(e.paths,i.parent),h=f?.integration.checkExecution;if(!f||h?.operationId!==o||h.key!==s||h.status!=="running")throw new Error("Native Supervisor integration check operation is stale");if(d?.status==="starting"){let m=h.checkStates?.find(({id:v})=>v===d.checkId);if(!m||m.status!=="planned")throw new Error(`Native Supervisor check ${d.checkId} is not planned`);m.status="running",m.executionCount+=1,m.startedAt=new Date().toISOString(),m.completedAt=null,m.logRef=null}h.activeProcess=d,f.stateVersion+=1,await q(e.paths,f)}),p=async d=>A(e.paths,"record Supervisor integration check result",async()=>{let f=await D(e.paths,i.parent),h=f?.integration.checkExecution;if(!f||h?.operationId!==o||h.key!==s||h.status!=="running")throw new Error("Native Supervisor integration check operation is stale");let m=h.checkStates?.find(({id:v})=>v===d.id);if(!m)throw new Error(`Native Supervisor check state is missing: ${d.id}`);Object.assign(m,Zl(m,d)),h.activeProcess=null,f.stateVersion+=1,await q(e.paths,f)});try{for(let y of r.pending.plansToExecute){await u({status:"starting",checkId:y.id});let E=await Bi({projectRoot:i.integration.worktree,runtimeDir:me(e.paths,i.parent),operationId:o,plan:y,onSpawn:async({pid:b})=>u({status:"running",checkId:y.id,pid:b,identity:await ct(b)??void 0})});if(await p(E),E.status==="interrupted")throw new Error(`Native Supervisor integration check ${E.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let d=await D(e.paths,i.parent),h=d?.integration.checkExecution?.checkStates;if(!d||!h||h.some(({status:y})=>!["passed","failed"].includes(y)))throw new Error("Native Supervisor integration check plan remains incomplete; retry each interrupted check explicitly");let m=h.map(eu),v=JSON.stringify({schema:"comet.native.supervisor-integration-checks.v1",parent:i.parent,child:e.name,candidateCommit:n,integrationCommit:a,operationId:o,planHash:s,results:m}),g=await c({paths:e.paths,name:i.parent,hash:l("sha256").update(v).digest("hex"),text:v}),w=m.map(y=>({name:y.name,status:y.status==="interrupted"?"incomplete":y.status,reason:y.status==="passed"?null:y.timedOut?"timed out":`exit ${y.exitCode??y.signal??"interrupted"}`,receiptRef:g})),N=w.filter(({status:y})=>y!=="passed");return await A(e.paths,"complete Supervisor integration checks",async()=>{let y=await D(e.paths,i.parent),E=y?.children.find(({name:k})=>k===e.name),b=y?.integration.checkExecution;if(!y||!E||b?.operationId!==o||b.key!==s||b.status!=="running"||b.child!==e.name||b.candidateCommit!==n||b.integrationCommit!==a||E.verifiedCommit!==n||ss(y)!==a)throw new Error("Native Supervisor integration changed during checks");if(b.receiptRef=g,b.checks=w,N.length>0){let k=`Native Supervisor integration checks did not pass (${N.map(({name:S,reason:C})=>`${S}: ${C}`).join("; ")}); receipt ${g}`;throw b.status="interrupted",b.error=k,E.blocker=k,y.stateVersion+=1,await q(e.paths,y),new Error(k)}b.status="completed";let x=yl(y,{name:e.name,integrationCommit:a,checks:w});return await q(e.paths,x),x})}catch(d){throw await A(e.paths,"interrupt Supervisor integration checks",async()=>{let f=await D(e.paths,i.parent),h=f?.integration.checkExecution;if(f&&h?.operationId===o&&h.key===s&&h.status==="running"){h.status="interrupted",h.error=d.message,h.activeProcess=null;for(let m of h.checkStates??[])(m.status==="planned"||m.status==="running")&&(m.status="interrupted");f.stateVersion+=1,await q(e.paths,f)}}),d}}import{randomUUID as _0}from"node:crypto";import A0 from"node:path";We();gt();ve();Hi();kr();async function cs(e){let t=bu(e.parent),r=wr(e.paths.projectRoot,t);if(!r)return null;let i=wr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=gr(e.paths.projectRoot).map(o=>A0.resolve(o)).find(o=>oe(o).currentBranch===t);if(!n)return null;let a=Ro({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return ot(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}async function Vh(e){return A(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await D(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await Oe(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let u=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!u)continue;let p;try{p=await qh({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),u?ok(p.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):ak(p.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(f){let h=Ue(o),m=h.children.find(({name:v})=>v===l.name);m&&(m.blocker=f.message,ot(h,{kind:"task-blocked",child:l.name,runId:null,summary:m.blocker}),h.stateVersion+=1,o=h,c=!0);continue}let d=Co(o,{role:u?"verifier":"builder",child:l.name,projectRoot:p.projectRoot,runId:_0()});o=d.state,s.push(d.task)}return(s.length>0||c)&&await q(e.paths,o),{state:o,tasks:s}})}function sk(e,t){if(Nt(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=Ue(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Yi(e){let t=ss(e);if(t===e.integration.headCommit)return e;try{I(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=Ue(e);return r.integration.headCommit=t,ot(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Xi(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=ss(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return sk(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function Wh(e,t){let r=Bt.normalize(Bt.resolve(e)),i=Bt.normalize(Bt.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function T0(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function $0(e){let t=T0(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function ls(e){try{let t=await Z({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return $0(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function ta(e){return $("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function j0(e){let t=gr(e.projectRoot);t.some(i=>Wh(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Bt.resolve(n)))]){let n=await Oe(i);n&&r.push({projectRoot:i,paths:await ei(i,n.native.artifact_root),parent:Wh(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function O0(e,t){let r=Bt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await yt(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function H0(e,t){let r;try{r=await I0.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Bt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await yt(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function D0(e,t,r){let i=Bt.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Bt.sep}`))return null;let n=i.split(Bt.sep).join("/");try{let a=(0,lk.parseDocument)(I(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:B(a.toJS({mapAsMap:!1}))}catch{return null}}function B0(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function ck(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Le(e){let t=Bt.join(e.paths.changesDir,e.state.name),r=await ls(t),i=null,n;try{n=await Je({changeDir:t,validation:bt(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await D(e.paths,e.state.name,{diagnostics:!0});if(g){let w=bl(g);return{...w,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(N=>({...N,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=ta({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===ti){let g=await D(e.paths,e.state.name,{diagnostics:!0});if(!g){let y=e.state.workspace.change_branch??e.state.workspace.target_branch;if(y){let E=await cs({paths:e.paths,parent:e.state.name,targetBranch:y,contract:n.contract});E&&(g=E,await q(e.paths,E))}}if(g){let y=bl(g);return e.state.children_contract_hash!==a||n.drift?{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(E=>({...E,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&y.confirmed}}let w=new Map(n.contract.children.map(y=>[y.name,y])),N=n.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:s&&y.depends_on.every(E=>n.contract.children.filter(({name:b})=>b!==y.name).every(({name:b})=>b!==E))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let y of N){if(y.status!=="ready")continue;w.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:N,readyChildren:N.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let c=await j0(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,p=new Map;for(let g of c){let w=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let N of await H0(g,l)){let y={...N,source:g,committedState:D0(g,N.file,w)};u.set(N.state.name,[...u.get(N.state.name)??[],y])}for(let N of l){let y=await O0(g,N);y&&p.set(N,[...p.get(N)??[],{source:g,state:y}])}}let d=new Map;for(let g of n.contract.children){let w=(u.get(g.name)??[]).find(({source:E,committedState:b})=>E.parent&&b?.name===g.name&&ck(b,o));if(w){d.set(g.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let N=u.get(g.name)?.[0];if(N){d.set(g.name,{kind:"blocked",phase:N.state.phase,projectRoot:N.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let y=p.get(g.name)??[];y.length>1?d.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):y[0]&&d.set(g.name,B0(y[0].state,y[0].source,o))}let f=new Map(n.contract.children.map(g=>[g.name,g])),h=new Map,m=g=>{let w=h.get(g);if(w)return w;let N=f.get(g),E=N.depends_on.map(m).every(({status:P})=>P==="done"),b=d.get(g),x=b?.kind==="active"&&E?N.depends_on.filter(P=>!(u.get(P)??[]).some(({source:_,committedState:j})=>Wh(_.projectRoot,b.projectRoot)&&j?.name===P&&ck(j,o))):[],k,S=b?.message??null;b?.kind==="done"?(k=E?"done":"blocked",E||(S=`Native child ${g} was merged before its dependencies`)):b?.kind==="active"?(k=E&&x.length===0?"active":"blocked",E?x.length>0&&(S=`Native child ${g} does not include merged dependencies: ${x.join(", ")}`):S=`Native child ${g} started before its dependencies merged`):b?.kind==="blocked"?k="blocked":(k=s&&E?"ready":"pending",s||(S="Parent Shape confirmation is required"));let C={name:g,summary:N.summary,dependsOn:[...N.depends_on],covers:[...N.covers],status:k,phase:b?.phase??null,projectRoot:b?.projectRoot??null,message:S};return h.set(g,C),C},v=n.contract.children.map(({name:g})=>m(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:v,readyChildren:v.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:v.every(({status:g})=>g==="done")}}On();Hi();function Re(e,t,r){return e.language==="zh-CN"?r:t}function L0(e,t,r,i){let n=a=>({required:!1,message:null,suggestedReply:null,agentInstruction:a});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return t?{required:!0,message:Re(e,"Shape is ready. Confirm the complete plan and choose A) Multi-session coordination (recommended), or B) Single-session progression in one reply.","Shape 已整理完成。请确认完整方案,并在同一次回复中选择 A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:Re(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:Re(e,"First present the target, scope, key decisions, acceptance criteria, non-goals, child responsibilities and dependencies, and both coordination choices. Execute the matching confirm-shape alternative only when the user explicitly accepts this complete Shape and chooses its mode. Choosing a mode alone, additions, or corrections are not full confirmation; retain that choice and ask only for the missing decision. Do not run --confirmed before full confirmation.","先展示目标、范围、关键决定、验收标准、非目标、各 Child 的职责与依赖,以及两种推进方式。只有用户明确同意当前完整 Shape 并选择推进方式后,才执行对应的 confirm-shape 选项。仅选择推进方式、补充或修改要求都不算完整确认;保留已选方式,只补问缺少的决定。完整确认前不要运行 --confirmed。")}:e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return n(Re(e,"Complete the Shape documents and child plan, resolve blocking questions, then execute prepare-shape-confirmation. Its persisted response combines complete Shape confirmation and coordination choice in one user decision. If the user already chose only a mode, include that --coordination-mode when preparing and ask only for complete Shape confirmation afterward.","完成 Shape 文档和 Child 计划,解决阻塞问题后执行 prepare-shape-confirmation。持久化后的响应会让用户一次确认完整 Shape 并选择推进方式。如果用户已经仅选择了推进方式,准备时附上对应的 --coordination-mode,随后只确认完整 Shape。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return n(Re(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result"){let a=i==="confirmed"?Re(e,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):Re(e,"Check whether the host accepted the startup call and locate the task for the current verifierExecutionRef. If the call has not been made, start the dispatched task once; if the host accepted it, check that same task and let the Verifier submit its startup receipt. A missing receipt alone does not prove failure. If local startup state is unavailable, recover the host task context before deciding whether startup is needed.","先核实宿主是否接受了启动调用,并找到当前 verifierExecutionRef 对应的任务。尚未调用时启动已派发的任务一次;宿主已接受时检查同一个任务,由 Verifier 提交启动回执。仅缺少回执不能证明执行失败。本地启动记录不可用时,先恢复宿主任务上下文,再判断是否需要启动。");return n(`${a} ${Re(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")}`)}if(e.status==="blocked"&&e.blockers.some(({resolution_action:a})=>a==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}:e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let o=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",s=o?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",c=o?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:s,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:c,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:Re(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements."+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" If accepting, also choose: keep the workspace, merge locally, push the branch, or push and create a PR. You may accept the result and defer the finish choice.":""),"当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" 接受时可一起选择:保留工作区、本地合并、推送分支,或推送并创建 PR;也可以先接受结果,稍后再选择收尾方式。":"")),suggestedReply:Re(e,"Accept the result","接受结果"),agentInstruction:Re(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let a=r?.children.some(({status:l})=>l==="blocked")??!1,o=r?.children.some(({status:l})=>l==="needs-reverify")??!1,s=r?.children.some(({status:l})=>l==="ready"||l==="active")??!1,c=r?.children.some(({status:l,builderFailureCount:u})=>l==="blocked"&&(u??0)>=Nr)??!1;return a&&!o&&!s&&!c?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:n(Re(e,"Implement the complete confirmed brief and Spec scope, then review every acceptance ID with its implementation and evidence before handoff. Fill acceptance_review from this audit; derive remaining work from it. Do not submit a partial candidate just to obtain verification feedback. Run focused checks; a separate pre-review is optional. If review is useful, retain the same Reviewer for focused repair follow-ups. Submit the completed candidate for one complete independent verification and release completed helper tasks.","完成已确认的 brief 和 Spec 全部范围,交接前逐项核对所有验收 ID 的实现和证据,填写 acceptance_review,并由这份自查生成剩余工作。不得提交未完成的候选来试探验收反馈。开发期运行相关检查,额外预审为可选项;确需审查时,保留同一个 Reviewer 复核修复及受影响范围。全部完成后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return n(Re(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function F0(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会完成预检,检查通过后按所选方式归档;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 的完整命令,Runtime 会在归档前检查状态和证据;选择 E 时停止,不运行 Archive 命令。按用户的明确选择执行 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run preflight and archive with the selected finish when the checks pass; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative; Runtime checks state and evidence before archiving. For E, stop without running an Archive command. Use the finish explicitly selected by the user."}}function q0(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed","--finish",i,"--expected-state-version",String(e.state_version)],requiredInputs:[],inputOptions:[],description:Re(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Re(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function fk(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Qi(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function uk(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function M0(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function dk(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function V0(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function W0(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function cr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:fk({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Qi("summary","--summary"),M0(e.name,e.flag)]}}function pk(e,t){return t.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:Re(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function z0(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function Nu(e){return[cr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),cr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function G0(e){let t={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(i=>{let n=i.response?.kind??i.kind;return{...r,name:n,required:!1,exclusiveGroup:"runner-input",description:t[n],template:i}}):[r])}function Y(e,t,r={}){let i=V0(t)&&e.coordination_mode===void 0,n=L0(e,i,t,r.verifierStartup),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation",...i?["coordination-choice"]:[]],inputOptions:[Qi("summary","--summary")],commandAlternatives:i?ol.map(s=>{let c=cr({name:`confirm-shape-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"});return{...c,commandArgs:[...c.commandArgs,"--coordination-mode",s],requiredInputs:[...c.requiredInputs,"coordination-choice"],inputOptions:[...c.inputOptions,dk("coordination-mode","--coordination-mode",[s])]}}):[cr({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Qi("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=cr({name:`accept-result-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"});return{...c,commandArgs:[...c.commandArgs,"--finish",s]}}):[],cr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Nu({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Qi("summary","--summary")],commandAlternatives:[cr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),cr({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Qi("summary","--summary")],commandAlternatives:[cr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Nu({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Qi("summary","--summary")],commandAlternatives:Nu({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:Nu({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?fk({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:"continue",action:"prepare-shape-confirmation",commandArgs:W0({change:e.name,stateVersion:e.state_version}),requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:h})=>h),acceptance_review:e.acceptance.map(({id:h})=>({id:h,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[uk()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:h})=>h==="verified");if(s){let h=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...h&&h.length>0?{retry_check_ids:[...h]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:h})=>h==="blocked"||h==="needs-reverify"),l=t.children.some(({status:h})=>h==="needs-reverify"),u=t.children.some(({status:h})=>h==="ready"||h==="active"),p=t.supervisorStateVersion===void 0?null:t.children.find(h=>h.status==="blocked"&&(h.builderFailureCount??0)>=Nr)??null,d=p===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:p.name,stateVersion:t.supervisorStateVersion},description:Re(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},f=c&&!l&&!u&&d===null;return{...a,disposition:f?"blocked":"continue",action:"advance-children",commandArgs:f?null:d!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:f?[]:d!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:f?[]:d!==null?[d]:[Qi("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:s})=>s),acceptance_review:e.acceptance.map(({id:s})=>{let c=e.builder_handoff?.acceptance_review?.find(l=>l.id===s);return c?{...c,evidence:[...c.evidence],...e.loop.previous_unresolved_ids.includes(s)?{status:"implemented-no-evidence",evidence:[],note:"<current repair and evidence summary>"}:{}}:{id:s,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"}}),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=uk();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Re(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:G0([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"blocked",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=pk(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(p=>z0(p))?{...a,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:pk(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[dk("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...q0(e)],userCommunication:F0(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[cr({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}We();Ao();pe();import{createHash as gS,randomUUID as wS}from"node:crypto";import{promises as ur}from"node:fs";import Tr from"node:os";import O from"node:path";We();br();ne();import{createHash as J0}from"node:crypto";import ku from"node:path";var hk=".comet/runtime/native/runner-input-artifacts.json",mk=256,vk=8*1024*1024;function gk(e){return J0("sha256").update(e).digest("hex")}function Zi(e){return process.platform==="win32"?e.toLowerCase():e}function Su(e,t){let r=ku.relative(e,ku.resolve(e,t)).replaceAll("\\","/");return r&&!ku.isAbsolute(r)&&r!==".."&&!r.startsWith("../")?r:null}async function U0(e){try{let t=await nt(e,hk,262144,{label:"Native Runner input registry"}),r=JSON.parse(t.bytes.toString("utf8"));if(!Array.isArray(r)||r.length>mk)throw new Error("Invalid Native Runner input registry");return r.map(i=>{let n=i;if(!n||typeof n.path!="string"||Su(e,n.path)!==n.path||typeof n.digest!="string"||!/^[a-f0-9]{64}$/u.test(n.digest))throw new Error("Invalid Native Runner input artifact");return{path:n.path,digest:n.digest}})}catch{return[]}}function wk(e){try{return new Set(I(e,["ls-files","-z"]).split("\0").filter(Boolean).map(Zi))}catch{return null}}async function yk(e){let t=await U0(e);if(!t.length)return[];let r=wk(e);if(!r)return[];let i=[];for(let n of t)if(!r.has(Zi(n.path)))try{let a=await nt(e,n.path,vk,{label:"Native Runner input artifact"}),o=Su(e,a.realPath);o&&!r.has(Zi(o))&&gk(a.bytes)===n.digest&&i.push({path:o,digest:n.digest})}catch{}return i}async function zh(e){return new Set((await yk(e)).map(t=>t.path))}async function bk(e){let t=Su(e.paths.projectRoot,e.file);if(!t)return;let r=wk(e.paths.projectRoot);if(!r||r.has(Zi(t)))return;let i=await nt(e.paths.projectRoot,t,vk,{label:"Native Runner input artifact"});e.validateContent(i.bytes.toString("utf8"));let n=Su(e.paths.projectRoot,i.realPath);if(!n||r.has(Zi(n)))return;let a=(await yk(e.paths.projectRoot)).filter(o=>Zi(o.path)!==Zi(n));if(a.length>=mk)throw new Error("Too many retained Native Runner input files; remove unused protocol files before continuing");await he(ku.join(e.paths.projectRoot,...hk.split("/")),[...a,{path:n,digest:gk(i.bytes)}],{containedRoot:e.paths.runtimeDir})}Mn();go();at();ni();ji();So();import{randomUUID as K0}from"node:crypto";var Gh=3,Jh=2;function Fe(e){return e.state_version+1}function Y0(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function Nk(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Uh(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function X0(e){return(e??[]).map(t=>({name:J(t.name),result:t.result,note:t.note?J(t.note):null}))}function di(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:J(e.summary),completed_at:e.completedAt}}function kk(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,phase:"build",status:"active",state_version:Fe(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function Sk(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,status:"await-user",state_version:Fe(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function Ek(e){let t=B(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Hy(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(r.review){if(r.review.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}let i=Y0(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=r.acceptanceReview===void 0?void 0:$n(r.acceptanceReview);jn(t.acceptance,n);let a=Nk(t.acceptance),o=(r.now??new Date).toISOString();return B({...t,phase:"verify",state_version:Fe(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??K0(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:J(r.summary),addressed_acceptance_ids:i,acceptance_review:n,checks:X0(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>J(s)),known_limits_truncated:!1,review:r.review?{status:"passed",summary:J(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef}:null,submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function xk(e){let t=B(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt requires a current Builder candidate");return B({...t,state_version:Fe(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function Q0(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function Z0(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Se?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:J(e.response.result.summary),risks:e.response.result.risks.map(t=>J(t)),risks_truncated:!1,completed_at:e.completedAt}}function Rk(e){let t=B(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=Uh(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=Dy({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,knownAcceptanceIds:t.acceptance.map(({id:v})=>v),previouslyPassedAcceptanceIds:t.acceptance.filter(({result:v})=>v==="passed").map(({id:v})=>v),requiredChecksPassed:e.checks.every(({status:v})=>v==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(v=>[v.id,v])),o=t.acceptance.map(v=>{let g=a.get(v.id);return g?{...v,result:g.result,reason:J(g.reason)}:v}),s=o.filter(({result:v})=>v==="failed"||v==="blocked").map(({id:v})=>v),c=Z0({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){let v=ke({...t,acceptance:o,verification:c},di({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),g=t.builder_handoff.identity_provider===Se;return{response:i,state:B({...v,phase:g?"verify":"archive",status:g?"await-user":"active",state_version:Fe(t),verification_result:"pass",verification_report:"verification.md",blockers:g?[{owner:"user",reason:J("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:g?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:g?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let v=ke({...t,acceptance:o,verification:c},di({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...v,status:"await-user",state_version:Fe(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:J(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,u=Q0(t,s),p=l>=e.maxVerifyFailures,d=u>=3,f=p||d,h=d?"stalled":p?"budget":void 0,m=ke({...t,acceptance:o,verification:c},di({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...m,phase:f?"verify":"build",status:f?"await-user":"active",state_version:Fe(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:f?[{owner:"user",reason:J(h==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:u>=2?[{owner:"builder",reason:J("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:f?"await-user":"repairing",iteration:f?t.loop.iteration:t.loop.iteration+1,attempt:f?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:u,...h===void 0?{}:{stop_reason:h},execution_failure_count:0,previous_unresolved_ids:s,next_action:f?"await-user":"repair-failed-acceptance"}})}}function Ck(e){let t=B(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Se||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return B({...t,phase:"archive",status:"active",state_version:Fe(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function Pk(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Se||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=Uh(t),n=ke(t,di({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return B({...n,status:"await-user",state_version:Fe(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:J(e.summary),risks:[J("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:J("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function _k(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=J(e.summary),n=ke(t,di({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return B({...n,phase:"archive",status:"active",state_version:Fe(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:J(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function Ak(e,t){let r=B(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=ke(r,di({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return B({...i,status:"active",state_version:Fe(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function Ik(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=Gh,a=ke(t,di({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return B({...a,status:n?"blocked":"active",state_version:Fe(t),blockers:n?[{owner:"runtime",reason:J(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Tk(e){let t=B(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=Uh(t),a=t.acceptance.some(({result:o})=>o==="passed");return B({...t,status:"active",state_version:Fe(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function pi(e){let t=B(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=e.failureBudget,i=r?t.loop.failed_iteration_count+1:t.loop.failed_iteration_count,n=r!==void 0&&i>=r.maxVerifyFailures,a=(e.now??new Date).toISOString(),o=ke(t,di({state:t,outcome:"recovery",summary:e.reason,completedAt:a})),s=new Set(t.loop.previous_unresolved_ids),c=s.size===0?Nk(t.acceptance):t.acceptance.map(l=>s.has(l.id)?{...l,result:"pending",reason:null}:l);return n?B({...o,phase:"verify",status:"await-user",state_version:Fe(t),verification_result:"fail",builder_handoff:t.builder_handoff,blockers:[{owner:"user",reason:J(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${e.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...t.loop,stage:"await-user",failed_iteration_count:i,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):B({...o,phase:"build",status:"active",state_version:Fe(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:c,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:i,stop_reason:void 0,next_action:"submit-builder-candidate"}})}ne();On();import{promises as $k}from"node:fs";import eO from"node:os";import ps from"node:path";function us(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ds(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function qe(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function ra(e,t){return e===null?null:qe(e,t)}function ia(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function tO(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function rO(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function na(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Kh(e,t){if(e===null)return null;let r=qe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function iO(e,t){let r=qe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Yh(e,t){let r=qe(e,t);if(!ps.isAbsolute(r))throw new Error(`${t} must be absolute`);return ps.resolve(r)}function nO(e,t){let r=`Native local checks[${t}]`,i=us(e,r);if(ds(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((u,p)=>qe(u,`${r}.argv[${p}]`,!0)),a=na(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Kh(i.startedAt,`${r}.startedAt`),s=Kh(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=ia(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let u=us(i.activeProcess,`${r}.activeProcess`),p=na(u.status,["starting","running"],`${r}.activeProcess.status`);if(ds(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),p==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);l={status:"starting"}}else l={status:"running",pid:ia(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:qe(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:qe(i.id,`${r}.id`),name:qe(i.name,`${r}.name`),operationId:qe(i.operationId,`${r}.operationId`),status:a,repeatable:rO(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:ia(i.executionCount,`${r}.executionCount`),argv:n,cwd:Yh(i.cwd,`${r}.cwd`),exitCode:tO(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:qe(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:na(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:qe(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function Xh(e){let t="Native local execution state",r=us(e,t);if(ds(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==wo)throw new Error(`Native local execution schema must be ${wo}`);let i=us(r.workspace,"Native local workspace");ds(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=us(r.execution,"Native local execution");ds(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Kh(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:qe(o.operationId,"Native local execution.operationId"),stage:na(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:na(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:ra(o.executionId,"Native local execution.executionId"),status:na(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ia(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:iO(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:ia(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:qe(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(nO);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:wo,change:qe(r.change,"Native local change"),basedOnStateVersion:ia(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:ra(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:ra(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:ra(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:ra(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Yh(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Yh(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:ra(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:qe(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function ae(e){return Xh({schema:wo,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,candidateId:e.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:ps.resolve(e.projectRoot),worktreeRoot:ps.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:eO.hostname()},execution:null,checks:[]})}async function Ce(e){let t;try{t=await $k.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return Xh(r)}function Qh(e,t){let r=t?.execution;if(!(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result"||e.builder_handoff?.candidate_id===void 0||e.builder_handoff?.candidate_id===null||t===null||t.change!==e.name||t.basedOnStateVersion!==e.state_version||t.candidateId!==e.builder_handoff.candidate_id||r==null||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null))return r.executionId}function jk(e,t){if(Qh(e,t)!==void 0)return t.execution.verifierStartedAt!=null||t.execution.requestCheckRounds>0?"confirmed":"unconfirmed"}async function M(e,t,r={}){let i=Xh(t);await $k.mkdir(ps.dirname(e),{recursive:!0}),await he(e,i,r)}async function Eu(e){let t=null,r=null;try{t=await Ce(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=ae(e);return await M(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}ve();ni();ie();async function Zh(e,t,r){if(!Number.isInteger(t)||t<1)throw new Error("Concurrency must be a positive integer");let i=new Array(e.length),n=0,a=async()=>{for(;n<e.length;){let o=n;n+=1,i[o]=await r(e[o],o)}};return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>a())),i}import{promises as Ok}from"node:fs";import xu from"node:path";We();at();ie();var em=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Hk="comet-state.yaml",Dk="state.json";function le(e,t){if(!em.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=xu.join(e.changesDir,t);if(!Ee(e.changesDir,r))throw new Error("Native change path escaped");return r}function dt(e,t){return xu.join(le(e,t),Hk)}function L(e,t){return xu.join(me(e,t),Dk)}async function aa(e,t){try{let r=await Ok.readFile(dt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function ge(e){return ty(e)}function Ru(e,t){let r=oe(t);if(!r.isGitWorktree||r.currentBranch===null||wr(t,r.currentBranch)===null)return null;if(!Lc(t))throw new Error("Native Supervisor Git binding requires a clean current working directory; commit or stash pending changes, then rerun the latest continuation");return{...e,change_branch:r.currentBranch,target_branch:r.currentBranch}}async function H(e,t){return yt(dt(e,t))}async function fe(e){let t=await Bn({file:dt(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=xu.join(le(e.paths,t.name),"verification.md");await G(e.paths.nativeRoot,r),await Ok.rm(r,{force:!0})}return t}async function tm(e){let t=await H(e.paths,e.name),r=L(e.paths,e.name);try{let i=await Ce(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}import{promises as ju}from"node:fs";import nn from"node:path";function am(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var rn=am();function zk(e){rn=e}var en={exec:()=>null};function oa(e){let t=[];return r=>{let i=Math.max(0,Math.min(3,r-1)),n=t[i];return n||(n=e(i),t[i]=n),n}}function V(e,t=""){let r=typeof e=="string"?e:e.source,i={replace:(n,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace($e.caret,"$1"),r=r.replace(n,o),i},getRegex:()=>new RegExp(r,t)};return i}var aO=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),$e={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:oa(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:oa(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:oa(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:oa(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:oa(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:oa(e=>new RegExp(`^ {0,${e}}>`))},oO=/^(?:[ \t]*(?:\n|$))+/,sO=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,cO=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ms=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,lO=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,om=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Gk=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Jk=V(Gk).replace(/bull/g,om).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),uO=V(Gk).replace(/bull/g,om).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),sm=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,dO=/^[^\n]+/,cm=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,pO=V(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",cm).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),fO=V(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,om).getRegex(),Iu="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",lm=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,hO=V("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",lm).replace("tag",Iu).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Uk=e=>V(sm).replace("hr",ms).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Iu).getRegex(),mO=Uk(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),vO=Uk(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),gO=V(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",vO).getRegex(),um={blockquote:gO,code:sO,def:pO,fences:cO,heading:lO,hr:ms,html:hO,lheading:Jk,list:fO,newline:oO,paragraph:mO,table:en,text:dO},Bk=V("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",ms).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Iu).getRegex(),wO={...um,lheading:uO,table:Bk,paragraph:V(sm).replace("hr",ms).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Bk).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Iu).getRegex()},yO={...um,html:V(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",lm).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:en,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:V(sm).replace("hr",ms).replace("heading",` *#{1,6} *[^
237
+ ]`).replace("lheading",Jk).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},bO=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,NO=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Kk=/^( {2,}|\\)\n(?!\s*$)/,kO=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ar=/[\p{P}\p{S}]/u,sa=/[\s\p{P}\p{S}]/u,vs=/[^\s\p{P}\p{S}]/u,SO=V(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,sa).getRegex(),EO=/[\p{Pi}\p{Ps}"']/u,Yk=/(?!~)[\p{P}\p{S}]/u,xO=/(?!~)[\s\p{P}\p{S}]/u,RO=/(?:[^\s\p{P}\p{S}]|~)/u,CO=V(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",aO?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Xk=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,PO=V(Xk,"u").replace(/punct/g,Ar).getRegex(),_O=V(Xk,"u").replace(/punct/g,Yk).getRegex(),AO=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,IO=V(AO,"u").replace(/openQuote/g,EO).replace(/punct/g,Ar).getRegex(),Qk="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",TO=V(Qk,"gu").replace(/notPunctSpace/g,vs).replace(/punctSpace/g,sa).replace(/punct/g,Ar).getRegex(),$O=V(Qk,"gu").replace(/notPunctSpace/g,RO).replace(/punctSpace/g,xO).replace(/punct/g,Yk).getRegex(),jO="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",OO=V(jO,"gu").replace(/notPunctSpace/g,vs).replace(/punctSpace/g,sa).replace(/punct/g,Ar).getRegex(),HO=V("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,vs).replace(/punctSpace/g,sa).replace(/punct/g,Ar).getRegex(),DO="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",BO=V(DO,"gu").replace(/notPunctSpace/g,vs).replace(/punctSpace/g,sa).replace(/punct/g,Ar).getRegex(),LO=V(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Ar).getRegex(),FO="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",qO=V(FO,"gu").replace(/notPunctSpace/g,vs).replace(/punctSpace/g,sa).replace(/punct/g,Ar).getRegex(),MO=V(/\\(punct)/,"gu").replace(/punct/g,Ar).getRegex(),VO=V(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),WO=V(lm).replace("(?:-->|$)","-->").getRegex(),zO=V("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",WO).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Pu=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,GO=V(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Pu).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Zk=V(/^!?\[(label)\]\[(ref)\]/).replace("label",Pu).replace("ref",cm).getRegex(),eS=V(/^!?\[(ref)\](?:\[\])?/).replace("ref",cm).getRegex(),JO=V("reflink|nolink(?!\\()","g").replace("reflink",Zk).replace("nolink",eS).getRegex(),Lk=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,dm={_backpedal:en,anyPunctuation:MO,autolink:VO,blockSkip:CO,br:Kk,code:NO,del:en,delLDelim:en,delRDelim:en,emStrongLDelim:PO,emStrongRDelimAst:TO,emStrongRDelimUnd:HO,escape:bO,link:GO,nolink:eS,punctuation:SO,reflink:Zk,reflinkSearch:JO,tag:zO,text:kO,url:en},UO={...dm,emStrongLDelim:IO,emStrongRDelimAst:OO,emStrongRDelimUnd:BO,link:V(/^!?\[(label)\]\((.*?)\)/).replace("label",Pu).getRegex(),reflink:V(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Pu).getRegex()},rm={...dm,emStrongRDelimAst:$O,emStrongLDelim:_O,delLDelim:LO,delRDelim:qO,url:V(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Lk).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:V(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Lk).getRegex()},KO={...rm,br:V(Kk).replace("{2,}","*").getRegex(),text:V(rm.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Cu={normal:um,gfm:wO,pedantic:yO},fs={normal:dm,gfm:rm,breaks:KO,pedantic:UO},YO={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Fk=e=>YO[e];function lr(e,t){if(t){if($e.escapeTest.test(e))return e.replace($e.escapeReplace,Fk)}else if($e.escapeTestNoEncode.test(e))return e.replace($e.escapeReplaceNoEncode,Fk);return e}function qk(e){try{e=encodeURI(e).replace($e.percentDecode,"%")}catch{return null}return e}function Mk(e,t){let r=e.replace($e.findPipe,(a,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),i=r.split($e.splitPipe),n=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),t)if(i.length>t)i.splice(t);else for(;i.length<t;)i.push("");for(;n<i.length;n++)i[n]=i[n].trim().replace($e.slashPipe,"|");return i}function fi(e,t,r){let i=e.length;if(i===0)return"";let n=0;for(;n<i;){let a=e.charAt(i-n-1);if(a===t&&!r)n++;else if(a!==t&&r)n++;else break}return e.slice(0,i-n)}function Vk(e){let t=e.split(`
238
+ `),r=t.length-1;for(;r>=0&&$e.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
239
+ `)}function XO(e,t){if(e.indexOf(t[1])===-1)return-1;let r=0;for(let i=0;i<e.length;i++)if(e[i]==="\\")i++;else if(e[i]===t[0])r++;else if(e[i]===t[1]&&(r--,r<0))return i;return r>0?-2:-1}function QO(e,t=0){let r=t,i="";for(let n of e)if(n===" "){let a=4-r%4;i+=" ".repeat(a),r+=a}else i+=n,r++;return i}function Wk(e,t,r,i,n){let a=t.href,o=t.title||null,s=e[1].replace(n.other.outputLinkReplace,"$1"),c=e[0].charAt(0)==="!";i.state.inLink=!0;let l=i.state.linkEmitted,u=i.state.inRawBlock;i.state.linkEmitted=!1;let p=i.inlineTokens(s),d=i.state.linkEmitted;if(i.state.linkEmitted=l,i.state.inLink=!1,!c){if(d){i.state.inRawBlock=u;return}i.state.linkEmitted=!0}return{type:c?"image":"link",raw:r,href:a,title:o,text:s,tokens:p}}function ZO(e,t,r){let i=e.match(r.other.indentCodeCompensation);if(i===null)return t;let n=i[1];return t.split(`
240
+ `).map(a=>{let o=a.match(r.other.beginningSpace);if(o===null)return a;let[s]=o;return s.length>=n.length?a.slice(n.length):a}).join(`
241
+ `)}var _u=class{options;rules;lexer;constructor(e){this.options=e||rn}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let r=this.options.pedantic?t[0]:Vk(t[0]),i=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:i}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let r=t[0],i=ZO(r,t[3]||"",this.rules);return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:i}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(this.rules.other.endingHash.test(r)){let i=fi(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:fi(t[0],`
242
+ `),depth:t[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:fi(t[0],`
243
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=fi(t[0],`
244
+ `).split(`
245
+ `),i="",n="",a=[];for(;r.length>0;){let o=!1,s=[],c;for(c=0;c<r.length;c++)if(this.rules.other.blockquoteStart.test(r[c]))s.push(r[c]),o=!0;else if(!o)s.push(r[c]);else break;r=r.slice(c);let l=s.join(`
246
+ `),u=l.replace(this.rules.other.blockquoteSetextReplace,`
247
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
248
+ ${l}`:l,n=n?`${n}
249
+ ${u}`:u;let p=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,a,!0),this.lexer.state.top=p,r.length===0)break;let d=a.at(-1);if(d?.type==="code")break;if(d?.type==="blockquote"){let f=d,h=r.join(`
250
+ `),m=f.raw+`
251
+ `+h.replace(this.rules.other.blockquoteSetextReplace2,""),v=this.blockquote(m);a[a.length-1]=v,i=`${i}
252
+ ${h}`,n=n.substring(0,n.length-f.text.length)+v.text;break}else if(d?.type==="list"){let f=d,h=f.raw+`
253
+ `+r.join(`
254
+ `),m=this.list(h);a[a.length-1]=m,i=i.substring(0,i.length-d.raw.length)+m.raw,n=n.substring(0,n.length-f.raw.length)+m.raw,r=h.substring(a.at(-1).raw.length).split(`
255
+ `);continue}}return{type:"blockquote",raw:i,tokens:a,text:n}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[1].trim(),i=r.length>1,n={type:"list",raw:"",ordered:i,start:i?+r.slice(0,-1):"",loose:!1,items:[]};r=i?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=i?r:"[*+-]");let a=this.rules.other.listItemRegex(r),o=!1;for(;e;){let c=!1,l="",u="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let p=QO(t[2].split(`
256
+ `,1)[0],t[1].length),d=e.split(`
257
+ `,1)[0],f=!p.trim(),h=0;if(this.options.pedantic?(h=2,u=p.trimStart()):f?h=t[1].length+1:(h=p.search(this.rules.other.nonSpaceChar),h=h>4?1:h,u=p.slice(h),h+=t[1].length),f&&this.rules.other.blankLine.test(d)&&(l+=d+`
258
+ `,e=e.substring(d.length+1),c=!0),!c){let m=this.rules.other.nextBulletRegex(h),v=this.rules.other.hrRegex(h),g=this.rules.other.fencesBeginRegex(h),w=this.rules.other.headingBeginRegex(h),N=this.rules.other.htmlBeginRegex(h),y=this.rules.other.blockquoteBeginRegex(h);for(;e;){let E=e.split(`
259
+ `,1)[0],b;if(d=E,this.options.pedantic?(d=d.replace(this.rules.other.listReplaceNesting," "),b=d):b=d.replace(this.rules.other.tabCharGlobal," "),g.test(d)||w.test(d)||N.test(d)||y.test(d)||m.test(d)||v.test(d))break;if(b.search(this.rules.other.nonSpaceChar)>=h||!d.trim())u+=`
260
+ `+b.slice(h);else{if(f||p.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||g.test(p)||w.test(p)||v.test(p))break;u+=`
261
+ `+d}f=!d.trim(),l+=E+`
262
+ `,e=e.substring(E.length+1),p=b.slice(h)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(o=!0)),n.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),n.raw+=l}let s=n.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let c of n.items)if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),!n.loose){let l=c.tokens.filter(p=>p.type==="space"),u=l.length>0&&l.some(p=>this.rules.other.anyLine.test(p.raw));n.loose=u}for(let c of n.items){let l=c.tokens[0];if(c.task&&(l?.type==="text"||l?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),l.raw=l.raw.replace(this.rules.other.listReplaceTask,""),l.text=l.text.replace(this.rules.other.listReplaceTask,"");for(let p=this.lexer.inlineQueue.length-1;p>=0;p--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[p].src)){this.lexer.inlineQueue[p].src=this.lexer.inlineQueue[p].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let p={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=p.checked,n.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=p.raw+c.tokens[0].raw,c.tokens[0].text=p.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(p)):c.tokens.unshift({type:"paragraph",raw:p.raw,text:p.raw,tokens:[p]}):c.tokens.unshift(p)}}else c.task&&(c.task=!1)}if(n.loose)for(let c of n.items){c.loose=!0;for(let l of c.tokens)l.type==="text"&&(l.type="paragraph")}return n}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=Vk(t[0]);return{type:"html",block:!0,raw:r,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:r}}}def(e){let t=this.rules.block.def.exec(e);if(t){let r=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",n=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:r,raw:fi(t[0],`
263
+ `),href:i,title:n}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let r=Mk(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
264
+ `):[],a={type:"table",raw:fi(t[0],`
265
+ `),header:[],align:[],rows:[]};if(r.length===i.length){for(let o of i)this.rules.other.tableAlignRight.test(o)?a.align.push("right"):this.rules.other.tableAlignCenter.test(o)?a.align.push("center"):this.rules.other.tableAlignLeft.test(o)?a.align.push("left"):a.align.push(null);for(let o=0;o<r.length;o++)a.header.push({text:r[o],tokens:this.lexer.inline(r[o]),header:!0,align:a.align[o]});for(let o of n)a.rows.push(Mk(o,a.header.length).map((s,c)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:a.align[c]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:fi(t[0],`
266
+ `),depth:t[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let r=t[1].charAt(t[1].length-1)===`
267
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:r,tokens:this.lexer.inline(r)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let a=fi(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=XO(t[2],"()");if(a===-2)return;if(a>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let i=t[2],n="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(i);a&&(i=a[1],n=a[3])}else n=t[3]?t[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?i=i.slice(1):i=i.slice(1,-1)),Wk(t,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:n&&n.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let i=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=t[i.toLowerCase()];if(!n){let a=r[0].charAt(0);return{type:"text",raw:a,text:a}}return Wk(r,n,r[0],this.lexer,this.rules)}}emStrong(e,t,r=""){let i=this.rules.inline.emStrongLDelim.exec(e);if(!(!i||!i[1]&&!i[2]&&!i[3]&&!i[4]||i[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[3])||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,c=0,l=i[0][0],u=r===l,p=l==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+n);(i=p.exec(t))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a)continue;if(o=[...a].length,i[3]||i[4]){s+=o;continue}else if(i[5]||i[6]){if(n%3&&!((n+o)%3)){c+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+c);let d=[...i[0]][0].length,f=e.slice(0,n+i.index+d+o);if(Math.min(n,o)%2){let m=f.slice(1,-1);return{type:"em",raw:f,text:m,tokens:this.lexer.inlineTokens(m)}}let h=f.slice(2,-2);return{type:"strong",raw:f,text:h,tokens:this.lexer.inlineTokens(h)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let r=t[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(r),n=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return i&&n&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:t[0],text:r}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,r=""){let i=this.rules.inline.delLDelim.exec(e);if(i&&(!i[1]||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(i=c.exec(t))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a||(o=[...a].length,o!==n))continue;if(i[3]||i[4]){s+=o;continue}if(s-=o,s>0)continue;o=Math.min(o,o+s);let l=[...i[0]][0].length,u=e.slice(0,n+i.index+l+o),p=u.slice(n,-n);return{type:"del",raw:u,text:p,tokens:this.lexer.inlineTokens(p)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let r,i;return t[2]==="@"?(r=t[1],i="mailto:"+r):(r=t[1],i=r),{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let r,i;if(t[2]==="@")r=t[0],i="mailto:"+r;else{let n;do n=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(n!==t[0]);r=t[0],t[1]==="www."?i="http://"+t[0]:i=t[0]}return{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let r=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:r}}}},pt=class im{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||rn,this.options.tokenizer=this.options.tokenizer||new _u,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let r={other:$e,block:Cu.normal,inline:fs.normal};this.options.pedantic?(r.block=Cu.pedantic,r.inline=fs.pedantic):this.options.gfm&&(r.block=Cu.gfm,this.options.breaks?r.inline=fs.breaks:r.inline=fs.gfm),this.tokenizer.rules=r}static get rules(){return{block:Cu,inline:fs}}static lex(t,r){return new im(r).lex(t)}static lexInline(t,r){return new im(r).inlineTokens(t)}lex(t){t=t.replace($e.carriageReturn,`
268
+ `),this.blockTokens(t,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let i=this.inlineQueue[r];this.inlineTokens(i.src,i.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,r=[],i=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace($e.tabCharGlobal," ").replace($e.spaceLine,""));let n=1/0;for(;t;){if(t.length<n)n=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let a;if(this.options.extensions?.block?.some(s=>(a=s.call({lexer:this},t,r))?(t=t.substring(a.raw.length),r.push(a),!0):!1))continue;if(a=this.tokenizer.space(t)){t=t.substring(a.raw.length);let s=r.at(-1);a.raw.length===1&&s!==void 0?s.raw+=`
269
+ `:r.push(a);continue}if(a=this.tokenizer.code(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
270
+ `)?"":`
271
+ `)+a.raw,s.text+=`
272
+ `+a.text,this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(a=this.tokenizer.fences(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.heading(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.hr(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.blockquote(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.list(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.html(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.def(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
273
+ `)?"":`
274
+ `)+a.raw,s.text+=`
275
+ `+a.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title},r.push(a));continue}if(a=this.tokenizer.table(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.lheading(t)){t=t.substring(a.raw.length),r.push(a);continue}let o=t;if(this.options.extensions?.startBlock){let s=1/0,c=t.slice(1),l;this.options.extensions.startBlock.forEach(u=>{l=u.call({lexer:this},c),typeof l=="number"&&l>=0&&(s=Math.min(s,l))}),s<1/0&&s>=0&&(o=t.substring(0,s+1))}if(this.state.top&&(a=this.tokenizer.paragraph(o))){let s=r.at(-1);i&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
276
+ `)?"":`
277
+ `)+a.raw,s.text+=`
278
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a),i=o.length!==t.length,t=t.substring(a.raw.length);continue}if(a=this.tokenizer.text(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
279
+ `)?"":`
280
+ `)+a.raw,s.text+=`
281
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}linkInText(t){if(!t.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let i of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(i[0])&&t.charAt(i.index-1)!=="!")return!0;for(let i of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let n=i[0],a=n.lastIndexOf("[");if(!(n.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,n.slice(a+1,-1)))&&!(a>1&&this.linkInText(n.slice(1,a-1))))return!0}return!1}inlineTokens(t,r=[]){this.tokenizer.lexer=this;let i=t;if(this.tokens.links&&t.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,c=l=>{let u=l.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,l.slice(u+1,-1)))return l;if(u>1&&l.charAt(0)!=="!"){let p=l.slice(1,u-1);if(this.linkInText(p))return"["+p.replace(s,c)+"]["+"a".repeat(l.length-u-2)+"]"}return"["+"a".repeat(l.length-2)+"]"};i=i.replace(s,c)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(s,c,l)=>{let u=l?l.length:0;return s.slice(0,u)+"["+"a".repeat(s.length-u-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let n=!1,a="",o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let s;if(this.options.extensions?.inline?.some(l=>(s=l.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(s.raw.length);let l=r.at(-1);s.type==="text"&&l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(t,i,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.codespan(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.br(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.del(t,i,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.autolink(t)){t=t.substring(s.raw.length),r.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(t))){t=t.substring(s.raw.length),r.push(s);continue}let c=t;if(this.options.extensions?.startInline){let l=1/0,u=t.slice(1),p;this.options.extensions.startInline.forEach(d=>{p=d.call({lexer:this},u),typeof p=="number"&&p>=0&&(l=Math.min(l,p))}),l<1/0&&l>=0&&(c=t.substring(0,l+1))}if(s=this.tokenizer.inlineText(c)){t=t.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(a=s.raw.slice(-1)),n=!0;let l=r.at(-1);l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},Au=class{options;parser;constructor(e){this.options=e||rn}space(e){return""}code({text:e,lang:t,escaped:r}){let i=(t||"").match($e.notSpaceStart)?.[0],n=e.replace($e.endingNewline,"")+`
282
+ `;return i?'<pre><code class="language-'+lr(i)+'">'+(r?n:lr(n,!0))+`</code></pre>
283
+ `:"<pre><code>"+(r?n:lr(n,!0))+`</code></pre>
284
+ `}blockquote({tokens:e}){return`<blockquote>
285
+ ${this.parser.parse(e)}</blockquote>
286
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
287
+ `}hr(e){return`<hr>
288
+ `}list(e){let t=e.ordered,r=e.start,i="";for(let o=0;o<e.items.length;o++){let s=e.items[o];i+=this.listitem(s)}let n=t?"ol":"ul",a=t&&r!==1?' start="'+r+'"':"";return"<"+n+a+`>
289
+ `+i+"</"+n+`>
290
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
291
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
292
+ `}table(e){let t="",r="";for(let n=0;n<e.header.length;n++)r+=this.tablecell(e.header[n]);t+=this.tablerow({text:r});let i="";for(let n=0;n<e.rows.length;n++){let a=e.rows[n];r="";for(let o=0;o<a.length;o++)r+=this.tablecell(a[o]);i+=this.tablerow({text:r})}return i&&(i=`<tbody>${i}</tbody>`),`<table>
293
+ <thead>
294
+ `+t+`</thead>
295
+ `+i+`</table>
296
+ `}tablerow({text:e}){return`<tr>
297
+ ${e}</tr>
298
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
299
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${lr(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){let i=this.parser.parseInline(r),n=qk(e);if(n===null)return i;e=n;let a='<a href="'+e+'"';return t&&(a+=' title="'+lr(t)+'"'),a+=">"+i+"</a>",a}image({href:e,title:t,text:r,tokens:i}){i&&(r=this.parser.parseInline(i,this.parser.textRenderer));let n=qk(e);if(n===null)return lr(r);e=n;let a=`<img src="${e}" alt="${lr(r)}"`;return t&&(a+=` title="${lr(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:lr(e.text)}},pm=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Lt=class nm{options;renderer;textRenderer;constructor(t){this.options=t||rn,this.options.renderer=this.options.renderer||new Au,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new pm}static parse(t,r){return new nm(r).parse(t)}static parseInline(t,r){return new nm(r).parseInline(t)}parse(t){this.renderer.parser=this;let r="";for(let i=0;i<t.length;i++){let n=t[i];if(this.options.extensions?.renderers?.[n.type]){let o=n,s=this.options.extensions.renderers[o.type].call({parser:this},o);if(s!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){r+=s||"";continue}}let a=n;switch(a.type){case"space":{r+=this.renderer.space(a);break}case"hr":{r+=this.renderer.hr(a);break}case"heading":{r+=this.renderer.heading(a);break}case"code":{r+=this.renderer.code(a);break}case"table":{r+=this.renderer.table(a);break}case"blockquote":{r+=this.renderer.blockquote(a);break}case"list":{r+=this.renderer.list(a);break}case"checkbox":{r+=this.renderer.checkbox(a);break}case"html":{r+=this.renderer.html(a);break}case"def":{r+=this.renderer.def(a);break}case"paragraph":{r+=this.renderer.paragraph(a);break}case"text":{r+=this.renderer.text(a);break}default:{let o='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return r}parseInline(t,r=this.renderer){this.renderer.parser=this;let i="";for(let n=0;n<t.length;n++){let a=t[n];if(this.options.extensions?.renderers?.[a.type]){let s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(a.type)){i+=s||"";continue}}let o=a;switch(o.type){case"escape":{i+=r.text(o);break}case"html":{i+=r.html(o);break}case"link":{i+=r.link(o);break}case"image":{i+=r.image(o);break}case"checkbox":{i+=r.checkbox(o);break}case"strong":{i+=r.strong(o);break}case"em":{i+=r.em(o);break}case"codespan":{i+=r.codespan(o);break}case"br":{i+=r.br(o);break}case"del":{i+=r.del(o);break}case"text":{i+=r.text(o);break}default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return i}},hs=class{options;block;constructor(e){this.options=e||rn}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?pt.lex:pt.lexInline}provideParser(e=this.block){return e?Lt.parse:Lt.parseInline}},eH=class{defaults=am();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Lt;Renderer=Au;TextRenderer=pm;Lexer=pt;Tokenizer=_u;Hooks=hs;constructor(...e){this.use(...e)}walkTokens(e,t){let r=[];for(let i of e)switch(r=r.concat(t.call(this,i)),i.type){case"table":{let n=i;for(let a of n.header)r=r.concat(this.walkTokens(a.tokens,t));for(let a of n.rows)for(let o of a)r=r.concat(this.walkTokens(o.tokens,t));break}case"list":{let n=i;r=r.concat(this.walkTokens(n.items,t));break}default:{let n=i;this.defaults.extensions?.childTokens?.[n.type]?this.defaults.extensions.childTokens[n.type].forEach(a=>{let o=n[a].flat(1/0);r=r.concat(this.walkTokens(o,t))}):n.tokens&&(r=r.concat(this.walkTokens(n.tokens,t)))}}return r}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(r=>{let i={...r};if(i.async=this.defaults.async||i.async||!1,r.extensions&&(r.extensions.forEach(n=>{if(!n.name)throw new Error("extension name required");if("renderer"in n){let a=t.renderers[n.name];a?t.renderers[n.name]=function(...o){let s=n.renderer.apply(this,o);return s===!1&&(s=a.apply(this,o)),s}:t.renderers[n.name]=n.renderer}if("tokenizer"in n){if(!n.level||n.level!=="block"&&n.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=t[n.level];a?a.unshift(n.tokenizer):t[n.level]=[n.tokenizer],n.start&&(n.level==="block"?t.startBlock?t.startBlock.push(n.start):t.startBlock=[n.start]:n.level==="inline"&&(t.startInline?t.startInline.push(n.start):t.startInline=[n.start]))}"childTokens"in n&&n.childTokens&&(t.childTokens[n.name]=n.childTokens)}),i.extensions=t),r.renderer){let n=this.defaults.renderer||new Au(this.defaults);for(let a in r.renderer){if(!(a in n))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,s=r.renderer[o],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u||""}}i.renderer=n}if(r.tokenizer){let n=this.defaults.tokenizer||new _u(this.defaults);for(let a in r.tokenizer){if(!(a in n))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,s=r.tokenizer[o],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u}}i.tokenizer=n}if(r.hooks){let n=this.defaults.hooks||new hs;for(let a in r.hooks){if(!(a in n))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,s=r.hooks[o],c=n[o];hs.passThroughHooks.has(a)?n[o]=l=>{if(this.defaults.async&&hs.passThroughHooksRespectAsync.has(a))return(async()=>{let p=await s.call(n,l);return c.call(n,p)})();let u=s.call(n,l);return c.call(n,u)}:n[o]=(...l)=>{if(this.defaults.async)return(async()=>{let p=await s.apply(n,l);return p===!1&&(p=await c.apply(n,l)),p})();let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u}}i.hooks=n}if(r.walkTokens){let n=this.defaults.walkTokens,a=r.walkTokens;i.walkTokens=function(o){let s=[];return s.push(a.call(this,o)),n&&(s=s.concat(n.call(this,o))),s}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return pt.lex(e,t??this.defaults)}parser(e,t){return Lt.parse(e,t??this.defaults)}parseMarkdown(e){return(t,r)=>{let i={...r},n={...this.defaults,...i},a=this.onError(!!n.silent,!!n.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(n.hooks&&(n.hooks.options=n,n.hooks.block=e),n.async)return(async()=>{let o=n.hooks?await n.hooks.preprocess(t):t,s=await(n.hooks?await n.hooks.provideLexer(e):e?pt.lex:pt.lexInline)(o,n),c=n.hooks?await n.hooks.processAllTokens(s):s;n.walkTokens&&await Promise.all(this.walkTokens(c,n.walkTokens));let l=await(n.hooks?await n.hooks.provideParser(e):e?Lt.parse:Lt.parseInline)(c,n);return n.hooks?await n.hooks.postprocess(l):l})().catch(a);try{n.hooks&&(t=n.hooks.preprocess(t));let o=(n.hooks?n.hooks.provideLexer(e):e?pt.lex:pt.lexInline)(t,n);n.hooks&&(o=n.hooks.processAllTokens(o)),n.walkTokens&&this.walkTokens(o,n.walkTokens);let s=(n.hooks?n.hooks.provideParser(e):e?Lt.parse:Lt.parseInline)(o,n);return n.hooks&&(s=n.hooks.postprocess(s)),s}catch(o){return a(o)}}}onError(e,t){return r=>{if(r.message+=`
300
+ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+lr(r.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(r);throw r}}},tn=new eH;function re(e,t){return tn.parse(e,t)}re.options=re.setOptions=function(e){return tn.setOptions(e),re.defaults=tn.defaults,zk(re.defaults),re};re.getDefaults=am;re.defaults=rn;function tH(...e){return tn.use(...e),re.defaults=tn.defaults,zk(re.defaults),re}re.use=tH;re.walkTokens=function(e,t){return tn.walkTokens(e,t)};re.parseInline=tn.parseInline;re.Parser=Lt;re.parser=Lt.parse;re.Renderer=Au;re.TextRenderer=pm;re.Lexer=pt;re.lexer=pt.lex;re.Tokenizer=_u;re.Hooks=hs;re.parse=re;var Wz=re.options,zz=re.setOptions,Gz=re.walkTokens,Jz=re.parseInline;var Uz=Lt.parse,Kz=pt.lex;ne();Wi();var hm=hr(Gt(),1);import ys from"path";rt();ne();Wi();gt();ve();ie();Zt();Jo();ve();ie();Pn();Qr();var sH=hr(Gt(),1);Pn();Qr();br();br();Cn();cf();Pn();br();var g2=4*1024*1024;import{AsyncLocalStorage as cH}from"node:async_hooks";var lH=new cH;function uH(){let e=lH.getStore();return e?.active?e:null}function dH(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function tS(e,t){return(...r)=>{let i=uH();if(i===null)return t(...r);let n=dH(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.get(n)?.value===o&&i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}Cn();var S2=tS("hookWritePolicy",async e=>(await Xp(e))?.hook??{allow_paths:[]});lo();var pH=16*1024;of();to();var SG=Number.MAX_SAFE_INTEGER;ne();Jt();var HG={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER};import ca from"node:path";ne();rt();ve();ie();var gs=/^[a-f0-9]{64}$/u,iS=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,yH=16*1024,XG=process.platform;function bH(e,t){let r=ca.relative(e,t);return ca.isAbsolute(r)||r===".."||r.startsWith(`..${ca.sep}`)?null:r.replaceAll("\\","/")||"."}function nS(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function aS(e,t){if(e.length===0||nS(e)||e.includes("\\")||ca.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=ca.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function NH(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function fm(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||nS(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function kH(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(fm(e.changeBranch,"Native workspace change branch"),fm(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function SH(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!iS.test(t.baseCommit)||typeof t.targetCommit!="string"||!iS.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");fm(t.targetBranch,"Native workspace Git target branch")}function EH(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!gs.test(String(t.projectRootId))||!gs.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");NH(t.capturedAt),aS(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!gs.test(String(t.projectRootPathId))||a&&!gs.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!gs.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&SH(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(kH(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function xH(e,t){return ca.join(vt(e,t),"workspace.json")}function RH(e,t){let r=xH(e,t),i=Ge(e,r),n=bH(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:aS(n,"Native workspace file ref")}}async function CH(e,t){try{let r=RH(e,t),i=await Z({root:r.root,ref:r.ref,maxBytes:yH});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function ws(e,t){let r=await CH(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(EH(r),r)}Bo();jl();jl();var Tu=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},bs=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},$u=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},EJ=Hl("en");function Ft(e,t){Mo(t);let r=ys.join(e.changesDir,t);if(!Ee(e.changesDir,r))throw new Error("Native change path escaped");return r}async function IH(e,t=ys.dirname(e)){let r=ys.relative(t,e).split(ys.sep).join("/"),i=await Z({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,hm.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function oS(e,t){let r=ys.join(Ft(e,t),xr);await G(e.nativeRoot,r);let i=Yf(await IH(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}rt();rr();ie();var mm=["outcome","scope","nonGoals","acceptanceExamples"],sS=[...mm,"constraints","decisions","openQuestions","verificationExpectations"];var $H=new Set(["nonGoals","decisions","openQuestions"]),la=class extends Error{constructor(r,i,n){super(r);this.findings=i;this.change=n;this.name="NativeDocumentConstraintError"}findings;change},jH={maxFileBytes:Vp};function OH(e){let t=new Map,r=null,i=[],n={marker:null,length:0},a=()=>{r!==null&&t.set(r,i.join(`
301
+ `).trim())};for(let o of e.split(/\r?\n/u)){let c=ks(o,n)===null&&n.marker===null?/^# ([^#].*)$/u.exec(o):null;c?(a(),r=c[1].trim(),i=[]):r!==null&&i.push(o)}return a(),t}function vm(e){return{valid:e.length===0,findings:e}}function gm(e){let t=[],r=0;for(;r<e.length;){let i=e.indexOf("<!--",r);if(i<0){t.push(e.slice(r));break}t.push(e.slice(r,i));let n=e.indexOf("-->",i+4);if(n<0){t.push(e.slice(i));break}r=n+3}return t.join("")}function wm(e){return gm(e).trim()}function Ns(e){let t=wm(e).split(/\r?\n/u),r=[],i={marker:null,length:0};for(let n of t)ks(n,i)===null&&(i.marker===null&&/^\s*#{1,6}\s*$/u.test(n)||i.marker===null&&/^\s*#{1,6}\s+/u.test(n)||i.marker===null&&/^\s*(?:[-*+]\s*|\d+[.)]\s*)$/u.test(n)||r.push(n));return r.join(`
302
+ `).trim()}function HH(e){let t=Ns(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim().toLocaleLowerCase("en-US");return/^(?:none|n\/a|not applicable|no(?:ne)?(?:\s+at\s+this\s+time)?|no\s+(?:additional\s+)?(?:non-goals?|decisions?|open\s+questions?|questions?)|无|无相关事项|没有(?:额外)?(?:非目标|决定|待解决问题)|不适用|暂无)[.!。;;::,,、 -]*$/iu.test(t)}function ym(e){let t=Ns(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/\s+/gu," ").trim();if(t.length===0)return!1;let r=t.replace(/[*_`]/gu,"").replace(/^\s*>+\s?/gmu,"").replace(/\s+/gu," ").trim();if(/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!。;;::,,、 -]*$/iu.test(r))return!0;let i=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:(?:todo|tbd|fixme)(?:\s*[::-]\s*.+)?|fill(?:\s+this\s+in)?(?:\s*[::-]\s*.+)?|placeholder(?:\s*[::-]\s*.+)?|待填写\S*|待补充\S*|<[^>]+>|\{\{[^}]+\}\})[.!。;;::,,、 -]*$/iu.test(i)}function cS(e,t){let r=[];return Ns(e).length===0?r.push({code:"spec-document-empty",message:`Native target Spec is empty: ${t}. Add the complete target requirements or use an explicit no-product-behavior exemption in brief.md.`,path:t}):ym(e)&&r.push({code:"spec-document-placeholder",message:`Native target Spec contains only template placeholder content: ${t}. Replace it with complete target requirements.`,path:t}),vm(r)}function bm(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r={marker:null,length:0};for(let i of e.split(/\r?\n/u)){if(ks(i,r)!==null||r.marker!==null)continue;let n=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(n)||n.includes("|")&&n.split("|").some(o=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(o)))return!0;let a=n.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(a){let o=a[1]?.toLocaleLowerCase("en-US")??"";if(t.has(o)||/[./_-]/u.test(o))return!0}}return!1}function ks(e,t){let r=/^ {0,3}(`{3,}|~{3,})/u.exec(e);if(r===null)return null;let i=r[1]??"",n=i[0];return t.marker===null?(t.marker=n,t.length=i.length,"opened"):n===t.marker&&i.length>=t.length&&e.trim()===i?(t.marker=null,t.length=0,"closed"):null}function DH(e){let t=wm(e).split(/\r?\n/u),r={marker:null,length:0},i=-1;for(let n=0;n<t.length;n+=1){let a=t[n]??"";if(ks(a,r)!==null||r.marker!==null)continue;let o=/^##\s+(.+)$/u.exec(a);if(o!==null){if(i===-1){jb(o[1]??"")&&(i=n+1);continue}return t.slice(i,n).join(`
303
+ `)}}return i===-1?null:t.slice(i).join(`
304
+ `)}function BH(e){let t=new Map,r=null,i=[],n={marker:null,length:0},a=()=>{r!==null&&t.set(r,i.join(`
305
+ `).trim())};for(let o of wm(e).split(/\r?\n/u)){if(ks(o,n)!==null){r!==null&&i.push(o);continue}let s=n.marker===null?/^###\s+(.+)$/u.exec(o):null;s!==null?(a(),r=Ob(s[1]??""),i=[]):r!==null&&i.push(o)}return a(),t}function LH(e,t){let r=[],i=DH(e);if(i===null)return r.push({code:"brief-structure-missing",message:'Brief scope must include a "## Directory structure"/「## 目录结构」 section with the subsections Created/新建, Modified/修改, Deleted/删除, and Not created/明确不建',path:t}),r;let n=BH(i),a=[];for(let o of Qf){let s=n.get(o);(s===void 0||Ns(s).length===0||ym(s))&&a.push($b(o))}return a.length>0&&r.push({code:"brief-structure-subsection-missing",message:`Brief directory structure subsections are missing or empty: ${a.join(", ")}. Keep every heading and write "None"/「无」 when there is no content`,path:t}),r}async function Nm(e,t,r={}){let i=[],n;try{n=(await Z({root:e,ref:t,maxBytes:jH.maxFileBytes})).text}catch(s){return vm([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,c]of OH(n))a.set(Ol(s)??s,c);for(let s of r.compact?mm:sS)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?sS.filter(s=>!r.compact||a.has(s)):mm;for(let s of o){let c=a.get(s)??"";Ns(c).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):ym(c)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!$H.has(s)&&HH(c)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:t})}return r.strict&&r.structure&&i.push(...LH(a.get("scope")??"",t)),bm(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),vm(i)}rt();pe();ve();Fl();Gf();at();ni();ne();Wi();ji();import{promises as FH}from"node:fs";function qt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
306
+ `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Ir(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function qH(e){return e.archived?Xe(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Xe(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Xe(e.language,"Verification passed; ready to archive","验收通过,可归档"):Xe(e.language,"Verification passed","验收通过")}function MH(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Xe(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?qH(e):e.verification_result==="blocked"?Xe(t,"Blocked","已阻塞"):e.verification_result==="fail"?Xe(t,"Failed","未通过"):Xe(t,"Pending","待处理")}function VH(e){if(e.verification?.assurance==="semantic-verification-unavailable")return Xe(e.language,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查");if(e.verification_result==="fail")return Xe(e.language,"Fix unresolved acceptance criteria and verify again","修复未通过的验收项后重新验证");if(e.verification_result==="blocked")return Xe(e.language,"Resolve the reported blockers and resume verification","解决报告中的阻塞项后恢复验证");let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Se?Se:"host-attested"),r=t===Se&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function WH(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=d=>Zf(r,d),n=(d,f)=>Xe(r,d,f),a=e.acceptance.map(d=>`| ${Ir(d.id)} | ${Ir(d.result)} | ${Ir(d.source)} | ${Ir(d.text)} | ${Ir(qt(d.reason))} |`).join(`
307
+ `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let f=d.argv_display.map(qt).join(" ");return`| ${Ir(qt(d.name))} | ${Ir(f||"—")} | ${Ir(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
308
+ `),s=e.builder_handoff?[`### ${n("Builder-reported evidence","Builder 报告的证据")}`,"",n("These are Builder reports, not Runtime check receipts or independent verification results.","以下为 Builder 报告,不等同于 Runtime 检查凭据或独立验收结果。"),"",...e.builder_handoff.checks.map(d=>`- ${qt(d.name)}: ${d.result} — ${qt(d.note)}`),...e.builder_handoff.checks_truncated?[n("Check list was truncated.","检查列表已截断。")]:[],...e.builder_handoff.known_limits.map(d=>`- ${n("Known limitation","已知限制")}: ${qt(d)}`),...e.builder_handoff.known_limits_truncated?[n("Limitations list was truncated.","限制列表已截断。")]:[]].join(`
309
+ `):"",c=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${qt(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
310
+ `),l=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${qt(d)}`).join(`
311
+ `),u=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${Ir(qt(d.summary))} | ${d.completed_at} |`)].join(`
312
+ `),p=t?.finalVerification.layers?`
229
313
  ## ${n("Supervisor evidence layers","Supervisor 分层证据")}
230
314
 
231
315
  - ${n("Child verification","Child 验证")}: ${t.finalVerification.layers.childVerification}
@@ -241,13 +325,13 @@ generated_from_state_version: ${e.state_version}
241
325
 
242
326
  ## ${i("currentResult")}
243
327
 
244
- - ${n("Result","结果")}: **${P$(e)}**
245
- - ${n("Verification status","验证情况")}: **${_$(e)}**
328
+ - ${n("Result","结果")}: **${MH(e)}**
329
+ - ${n("Verification status","验证情况")}: **${VH(e)}**
246
330
  - ${n("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
247
331
  - ${n("Iteration","迭代")}: ${e.verification.iteration}
248
332
  - ${n("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
249
333
  - ${n("Completed","完成时间")}: ${e.verification.completed_at}
250
- - ${n("Summary","摘要")}: ${It(e.verification.summary)}
334
+ - ${n("Summary","摘要")}: ${qt(e.verification.summary)}
251
335
 
252
336
  ## ${i("acceptance")}
253
337
 
@@ -273,38 +357,39 @@ ${l}
273
357
 
274
358
  ${u}
275
359
 
276
- ${f}
360
+ ${p}
277
361
 
278
362
  ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into summary","更早的历史记录已折叠到摘要中")}: ${e.history_overflow.dropped_entries}.
279
363
 
280
364
  `:""}## ${i("conclusion")}
281
365
 
282
- ${It(e.verification.summary)}
283
- `}function I$(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function fb(e){let t;try{t=await C$.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=I$(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function Xr(e){await at(e.file,A$(e.state,e.supervisor))}te();xi();Gr();st();var dh=br(rr(),1);Hr();var LW=new Set("a an and are as at be by for from in is it of on or that the this to with you your".split(" "));var pb=5,T$=600,zW=256*1024,j$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$$=/^[A-Za-z0-9][A-Za-z0-9._-]*$/u;var O$=/^[a-f0-9]{64}$/iu;function hb(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qr(e,t,r=4096){if(typeof e!="string"||e.trim().length===0||e.length>r)throw new Error(`${t} must be a non-empty string within the association limit`);return e}function uh(e,t){let r=Qr(e,t).replaceAll("\\","/");if(r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${t} must be a project-relative path`);return r}function H$(e,t){let r=Qr(e,t,64).toLowerCase();if(!O$.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function D$(e,t){let r=`Capability association evidence[${t}]`,i=hb(e,r),n=Object.keys(i).filter(a=>!new Set(["source","kind","title","snippet"]).has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return{source:uh(i.source,`${r}.source`),kind:Qr(i.kind,`${r}.kind`,128),...i.title===void 0?{}:{title:Qr(i.title,`${r}.title`)},...i.snippet===void 0?{}:{snippet:Qr(i.snippet,`${r}.snippet`,T$)}}}function mb(e){let t=typeof e=="string"?(()=>{if(e.length>65536)throw new Error("Capability association exceeds the size limit");let l=(0,dh.parseDocument)(e,{uniqueKeys:!0});if(l.errors.length>0)throw new Error(l.errors[0].message);return l.toJS({mapAsMap:!1})})():e,r=hb(t,"Capability association"),i=Object.keys(r).filter(l=>!new Set(["schema","status","workflow","capability","current_spec","current_hash","confidence","query","reason","historical_sources","evidence"]).has(l));if(i.length>0)throw new Error(`Capability association has unknown field(s): ${i.join(", ")}`);if(r.schema!=="comet.capability-association.v1")throw new Error("Unsupported capability association schema");let n=r.workflow;if(n!=="native"&&n!=="classic")throw new Error("Capability association workflow is invalid");let a=B$(Qr(r.capability,"Capability association capability"),n);if(!Array.isArray(r.historical_sources))throw new Error("Capability association historical_sources must be an array");let o=r.historical_sources.map((l,u)=>uh(l,`Capability association historical_sources[${u}]`));if(!Array.isArray(r.evidence)||r.evidence.length>pb)throw new Error(`Capability association evidence must contain at most ${pb} entries`);let s=r.status;if(s!=="suggested"&&s!=="explicit")throw new Error("Capability association status is invalid");let c=r.confidence;if(c!=="high"&&c!=="medium"&&c!=="low")throw new Error("Capability association confidence is invalid");return{schema:"comet.capability-association.v1",status:s,workflow:n,capability:a,current_spec:uh(r.current_spec,"Capability association current_spec"),current_hash:H$(r.current_hash,"Capability association current_hash"),confidence:c,...r.query===void 0?{}:{query:Qr(r.query,"Capability association query")},reason:Qr(r.reason,"Capability association reason",2048),historical_sources:o,evidence:r.evidence.map(D$)}}function B$(e,t){let r=e.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""),i=r.split("/"),n=t==="native"?j$:$$;if(!r||i.some(a=>!n.test(a)))throw new Error(`Invalid ${t} capability: ${e}`);return i.join("/")}ut();Fr();async function Hn(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...ye(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}lr();var L$=Qc("en"),vb="capability-association.yaml";function Jl(e){let t=e.replace(/\r\n?/gu,`
366
+ ${qt(e.verification.summary)}
367
+ `}function zH(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function lS(e){let t;try{t=await FH.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=zH(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function hi(e){await mt(e.file,WH(e.state,e.supervisor))}ie();Wi();ui();gt();var Sm=hr(Gt(),1);br();var LJ=new Set("a an and are as at be by for from in is it of on or that the this to with you your".split(" "));var uS=5,GH=600,zJ=256*1024,JH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,UH=/^[A-Za-z0-9][A-Za-z0-9._-]*$/u;var KH=/^[a-f0-9]{64}$/iu;function dS(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mi(e,t,r=4096){if(typeof e!="string"||e.trim().length===0||e.length>r)throw new Error(`${t} must be a non-empty string within the association limit`);return e}function km(e,t){let r=mi(e,t).replaceAll("\\","/");if(r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${t} must be a project-relative path`);return r}function YH(e,t){let r=mi(e,t,64).toLowerCase();if(!KH.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function XH(e,t){let r=`Capability association evidence[${t}]`,i=dS(e,r),n=Object.keys(i).filter(a=>!new Set(["source","kind","title","snippet"]).has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return{source:km(i.source,`${r}.source`),kind:mi(i.kind,`${r}.kind`,128),...i.title===void 0?{}:{title:mi(i.title,`${r}.title`)},...i.snippet===void 0?{}:{snippet:mi(i.snippet,`${r}.snippet`,GH)}}}function pS(e){let t=typeof e=="string"?(()=>{if(e.length>65536)throw new Error("Capability association exceeds the size limit");let l=(0,Sm.parseDocument)(e,{uniqueKeys:!0});if(l.errors.length>0)throw new Error(l.errors[0].message);return l.toJS({mapAsMap:!1})})():e,r=dS(t,"Capability association"),i=Object.keys(r).filter(l=>!new Set(["schema","status","workflow","capability","current_spec","current_hash","confidence","query","reason","historical_sources","evidence"]).has(l));if(i.length>0)throw new Error(`Capability association has unknown field(s): ${i.join(", ")}`);if(r.schema!=="comet.capability-association.v1")throw new Error("Unsupported capability association schema");let n=r.workflow;if(n!=="native"&&n!=="classic")throw new Error("Capability association workflow is invalid");let a=QH(mi(r.capability,"Capability association capability"),n);if(!Array.isArray(r.historical_sources))throw new Error("Capability association historical_sources must be an array");let o=r.historical_sources.map((l,u)=>km(l,`Capability association historical_sources[${u}]`));if(!Array.isArray(r.evidence)||r.evidence.length>uS)throw new Error(`Capability association evidence must contain at most ${uS} entries`);let s=r.status;if(s!=="suggested"&&s!=="explicit")throw new Error("Capability association status is invalid");let c=r.confidence;if(c!=="high"&&c!=="medium"&&c!=="low")throw new Error("Capability association confidence is invalid");return{schema:"comet.capability-association.v1",status:s,workflow:n,capability:a,current_spec:km(r.current_spec,"Capability association current_spec"),current_hash:YH(r.current_hash,"Capability association current_hash"),confidence:c,...r.query===void 0?{}:{query:mi(r.query,"Capability association query")},reason:mi(r.reason,"Capability association reason",2048),historical_sources:o,evidence:r.evidence.map(XH)}}function QH(e,t){let r=e.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""),i=r.split("/"),n=t==="native"?JH:UH;if(!r||i.some(a=>!n.test(a)))throw new Error(`Invalid ${t} capability: ${e}`);return i.join("/")}at();ni();async function ua(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...ke(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await fe({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}kr();var ZH=Hl("en",{compact:!0}),fS="capability-association.yaml";function Ou(e,t=!1){if(t){let i=n=>{if(Array.isArray(n))return n.filter(a=>a?.type!=="space").map(i);if(n&&typeof n=="object"){let a=n;return Object.fromEntries(Object.entries(a).filter(([o])=>o!=="raw"&&!(o==="text"&&Array.isArray(a.tokens))).map(([o,s])=>[o,o==="text"&&a.type==="text"&&typeof s=="string"?s.replace(/[\t ]*\n[\t ]*/gu," "):i(s)]))}return n};return JSON.stringify(i(pt.lex(e.replace(/\r\n?/gu,`
368
+ `))))}let r=e.replace(/\r\n?/gu,`
284
369
  `).split(`
285
- `);for(;t.length>0&&t.at(-1)?.trim().length===0;)t.pop();return`${t.map(r=>r.replace(/[\t ]+$/gu,"")).join(`
370
+ `);for(;r.length>0&&r.at(-1)?.trim().length===0;)r.pop();return`${r.map(i=>i.replace(/[\t ]+$/gu,"")).join(`
286
371
  `)}
287
- `}function q$(e){let t=e.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/u,"").replace(/\s+/gu," ").trim();if(t.length===0||/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!:: -]*$/iu.test(t))return!0;let r=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:todo|tbd|fixme)(?:\s*[::-]|\s*$)/iu.test(r)||/^(?:fill(?:\s+this\s+in)?|placeholder)\b/iu.test(r)||/^(?:待填写|待补充)/u.test(r)?!0:/^(?:(?:todo|tbd|fixme)\b|fill(?:\s+this\s+in)?\b|placeholder\b|documentation[- ]only\b|no\s+product\s+behavior\s+change\b|待填写|待补充|仅文档|不改变产品行为|不涉及产品行为)[.!。;;::,,、 -]*$/iu.test(r)}function F$(e){let t=[],r=!1;for(let i of sh(e).split(/\r?\n/u)){if(/^\s*(?:```|~~~)/u.test(i)){r=!r;continue}!r&&!/^\s*#{1,6}\s+/u.test(i)&&t.push(i)}return t.some(i=>{let n=/(?:no\s+product\s+behavior\s+change|documentation[- ]only|不改变产品行为|不涉及产品行为|仅文档)\s*[::]\s*(.*)$/iu.exec(i);return n!==null&&!q$(n[1]??"")})}function gb(e,t){let r=e.map(({code:i,message:n,path:a})=>`- ${i}${a?` (${a})`:""}: ${n}`).join(`
372
+ `}function eD(e){let t=e.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/u,"").replace(/\s+/gu," ").trim();if(t.length===0||/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!:: -]*$/iu.test(t))return!0;let r=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:todo|tbd|fixme)(?:\s*[::-]|\s*$)/iu.test(r)||/^(?:fill(?:\s+this\s+in)?|placeholder)\b/iu.test(r)||/^(?:待填写|待补充)/u.test(r)?!0:/^(?:(?:todo|tbd|fixme)\b|fill(?:\s+this\s+in)?\b|placeholder\b|documentation[- ]only\b|no\s+product\s+behavior\s+change\b|待填写|待补充|仅文档|不改变产品行为|不涉及产品行为)[.!。;;::,,、 -]*$/iu.test(r)}function tD(e){let t=[],r=!1;for(let i of gm(e).split(/\r?\n/u)){if(/^\s*(?:```|~~~)/u.test(i)){r=!r;continue}!r&&!/^\s*#{1,6}\s+/u.test(i)&&t.push(i)}return t.some(i=>{let n=/(?:no\s+product\s+behavior\s+change|documentation[- ]only|不改变产品行为|不涉及产品行为|仅文档)\s*[::]\s*(.*)$/iu.exec(i);return n!==null&&!eD(n[1]??"")})}function hS(e,t){let r=e.map(({code:i,message:n,path:a})=>`- ${i}${a?` (${a})`:""}: ${n}`).join(`
288
373
  `);return[`Native ${t.phase} document checks failed for ${t.change}.`,r,"Recovery: edit the reported formal file in the configured Native change directory, then rerun the latest continuation command. The current state and existing work are preserved; do not edit comet-state.yaml or bypass the Hook."].join(`
289
- `)}async function fh(e){let t=se(e.paths,e.state.name),r=[...(await lh(t,e.state.brief,{strict:!0})).findings],i="";try{i=(await Q({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1})).text}catch{}let n=e.specChanges??e.state.spec_changes,a=n.filter(({operation:l})=>l!=="remove"),o=e.state.spec_changes.filter(({operation:l})=>l!=="remove"),s=new Set(a.map(({capability:l})=>l));if(e.specChanges!==void 0)for(let l of o)s.has(l.capability)||r.push({code:"spec-document-missing",message:`Previously declared target Spec is missing: specs/${l.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${l.capability}/spec.md`});let c=n.length>0&&n.every(({operation:l})=>l==="remove");a.length===0&&o.length===0&&!c&&!F$(i)&&r.push({code:"spec-exemption-missing",message:"This change declares no target Spec. Add a complete target Spec, or record a concrete reason such as “No product behavior change: documentation-only wording.” in brief.md.",path:e.state.brief});for(let l of a){let u=`specs/${l.capability}/spec.md`;if(l.source!==u){r.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${u}.`,path:l.source??u});continue}try{let f=(await Q({root:t,ref:u,maxBytes:null,includeHash:!1})).text;r.push(...db(f,u).findings)}catch(f){r.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${f.message}. Restore the complete file at ${u}.`,path:u})}}return{valid:r.length===0,findings:r}}async function Gl(e){let t=await fh(e);if(!t.valid)throw new Error(gb(t.findings,{change:e.state.name,phase:e.state.phase}))}function Tt(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale: the change moved on since the referenced response (current phase ${e.state.phase}, next action ${e.state.loop.next_action}, state version ${e.state.state_version}). Run comet native status ${e.state.name} --json and execute its commandAlternatives with --expected-state-version ${e.state.state_version} --expected-action ${e.state.loop.next_action}.`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}async function Ul(e){let t=se(e.paths,e.state.name),r=$i.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await zl.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!rh.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=$i.join(t,...s.split("/")),l=await zl.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=$i.join(e.paths.specsDir,o.name,"spec.md"),f="create",d=null;try{let g=await zl.lstat(u);if(!g.isFile()||g.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);f="modify",d=ur((await Q({root:e.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(g){if(g.code!=="ENOENT")throw g}let p=`specs/${o.name}/${Ww}`,m=$i.join(t,...p.split("/")),h={};try{let g=await zl.lstat(m);if(!g.isFile()||g.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${p}`);let v=await Q({root:t,ref:p,maxBytes:null,includeHash:!1}),w=io(v.text);if(w.capability!==o.name)throw new Error(`Native delta capability ${w.capability} does not match directory ${o.name}`);let y=d??ur(""),b=e.state.spec_changes.find(S=>S.capability===o.name);if(b?.delta_source!==void 0){if(b.base_hash!==w.base_hash)throw new Error(`Native delta base changed for ${o.name}; explicit conversion is required`)}else if(w.base_hash!==y)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);h={delta_source:p,base_hash:w.base_hash}}catch(g){if(g.code!=="ENOENT")throw g}a.push({capability:o.name,operation:f,source:s,...h})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Kl(e){let t=se(e.paths,e.state.name),r=await Q({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(ch(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let o of e.specChanges){if(o.source===null){n.push({...o,contentHash:null});continue}let s=await Q({root:t,ref:o.source,maxBytes:null,includeHash:!1}),c=s.text,l=null;if(o.delta_source){let u=await Q({root:t,ref:o.delta_source,maxBytes:null,includeHash:!1}),f=io(u.text);c=Uw(s.text,f);let d="";try{d=(await Q({root:e.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(p){if(p.code!=="ENOENT")throw p}if(ur(d)===f.base_hash){let p=Yw({baselineMarkdown:d,delta:f,allowAlreadyApplied:!0});if(ur(s.text)!==p.result_hash)throw new Error(`Native full target Spec does not match delta result for ${o.capability}; update the complete target before confirming Shape`)}l=T("comet.native.shape-artifact-content.v1",Jl(u.text))}i.push({capability:o.capability,source:s.ref,markdown:c}),n.push({...o,contentHash:T("comet.native.shape-artifact-content.v1",Jl(s.text)),...l===null?{}:{deltaContentHash:l}})}let a=null;try{let o=await Q({root:t,ref:vb,maxBytes:65536,includeHash:!1}),s=mb(o.text);if(s.workflow!=="native")throw new Error("Native capability association must use the native workflow");if(!e.specChanges.some(({capability:u})=>u===s.capability))throw new Error(`Native capability association ${s.capability} is not declared by this change`);let l=$i.relative(e.paths.projectRoot,$i.join(e.paths.specsDir,s.capability,"spec.md")).replaceAll($i.sep,"/");if(s.current_spec!==l)throw new Error(`Native capability association points to ${s.current_spec}, expected ${l}`);a=T("comet.native.shape-artifact-content.v1",Jl(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:rl({briefMarkdown:r.text,specs:i}),formalHash:T("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:T("comet.native.shape-artifact-content.v1",Jl(r.text))},specs:n,association:{source:vb,contentHash:a}})}}function Yl(e){return T("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function ph(e){return _(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(Tt({state:t,expected:e.expectedContinuation,action:"prepare-shape-confirmation"}),t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");let r=await Ul({paths:e.paths,state:t});e.enforceDocumentConstraints===!0&&await Gl({paths:e.paths,state:t,specChanges:r});let i=await Kl({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Fe({changeDir:se(e.paths,t.name),acceptanceIds:n.map(({id:d})=>d),validation:dt({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await Hc(e.paths,t.name);let d=Fl(t.workspace,e.paths.projectRoot);if(d===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");o=ye({...t,workspace:d},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${d.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await _o(se(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2;if(s&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");let c=s?e.coordinationMode??t.coordination_mode:void 0;if(s&&c===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!s&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let l={...o,spec_changes:r,shape_confirmation_hash:Yl({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:c})};delete l.children_contract_hash,delete l.coordination_mode,s&&(l.coordination_mode=c);let u=FN({state:l,acceptance:n.map(d=>({...d}))});e.enforceDocumentConstraints===!0&&(u.document_constraints_version=1),a&&(u.children_contract_hash=An({acceptance:u.acceptance,children:a.contract}));let f=await ce({paths:e.paths,previous:t,next:u});return await F(D(e.paths,t.name),re({portableState:f,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),f})}async function Bo(e){if(e.state.document_constraints_version===1){let l=await fh(e);if(!l.valid){let u=l.findings[0];return{drifted:!0,reason:u?`Native formal documents are invalid (${u.code}${u.path?`: ${u.path}`:""})`:"Native formal documents are invalid"}}}let t=await Ul(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,u)=>{let f=e.state.spec_changes[u];return f!==void 0&&l.capability===f.capability&&l.source===f.source&&l.delta_source===f.delta_source&&l.base_hash===f.base_hash&&(l.operation===f.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await Kl({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:u})=>({source:l,text:u}));if(!my(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Fe({changeDir:se(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:dt({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&Yl({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?An({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Je(e){let t=await Bo(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await qo({paths:e.paths,state:e.state,reason:r,keepFailureBudget:!0}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Lo(e){return _(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await $(e.paths,e.name);if(Tt({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:qo({paths:e.paths,state:t,reason:e.reason,...e.keepFailureBudget?{keepFailureBudget:!0}:{}})})}async function qo(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...ye(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:e.keepFailureBudget?t.loop.failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}function eu(e,t){let r=j.relative(j.resolve(e),j.resolve(t));if(j.isAbsolute(r)||r===".."||r.startsWith(`..${j.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(j.sep).join("/");return Za(e,i),i}function V$(e){return e.split("\0").some(t=>t.startsWith("160000 "))}function Xl(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return vn({id:e.id,name:e.name,executable:r,argv:i,cwdRef:eu(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function Sb(e,t=e.workspace.projectRoot){return e.checks.map(r=>{let[i,...n]=r.argv;if(!i)throw new Error(`Native local check ${r.id} has no executable`);return{id:r.id,name:r.name,executable:i,argv:n,cwdRef:eu(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function Eb(e,t,r,i,n,a){return e.candidateId!==i.builder_handoff?.candidate_id||e.inputFingerprint!==n||j.resolve(e.workspace.projectRoot)!==j.resolve(r)||j.resolve(e.workspace.worktreeRoot)!==j.resolve(r)||e.workspace.branch!==a||e.workspace.machineId!==Zr.hostname()||e.checks.length!==t.length?!1:e.checks.every((o,s)=>Xl(o,r)===vn(t[s]))}function wb(e,t,r){return e.checks.length===t.length&&e.checks.every((i,n)=>Xl(i,r)===vn(t[n]))}async function Ql(e){let t=e.execution;if(t===null||t.status!=="running")return"not-running";if(t.ownerPid===void 0)return"unknown";let r=await hn(t.ownerPid,t.ownerIdentity);if(r==="alive")return"running";let i=r==="unknown";for(let n of e.checks){if(n.status!=="running")continue;let a=n.activeProcess;if(!a||a.status==="starting"){i=!0;continue}let o=await hn(a.pid,a.identity);if(o==="alive")return"running";o==="unknown"&&(i=!0)}return i?"unknown":"orphaned"}function yb(e){return{...e,execution:e.execution===null?null:{...e.execution,status:"interrupted"},checks:e.checks.map(t=>t.status==="planned"||t.status==="running"?{...t,status:"interrupted",activeProcess:null}:t)}}function Zl(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:Za(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`,activeProcess:null}}function xb(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return Cb(e,t,r,i)}function Cb(e,t,r,i){return{...Zl(t,r,i),executionCount:e.executionCount}}function Rb(e){return bb("sha256").update(e).digest("hex")}async function Mo(e){let t=await Qt.lstat(e);if(!t.isFile())throw new Error("Native check input must be a regular file");let r=bb("sha256"),i=await Qt.open(e,"r"),n=0;try{let o=Buffer.allocUnsafe(M$);for(;;){let{bytesRead:s}=await i.read(o,0,o.length,null);if(s===0)break;n+=s,r.update(o.subarray(0,s).toString("base64"))}}finally{await i.close()}let a=await Qt.lstat(e);if(a.size!==t.size||a.mtimeMs!==t.mtimeMs)throw new Error("Native check input changed while reading");return{digest:r.digest("hex"),size:n}}var Pb=2e4,_b=1024*1024*1024,M$=65535,Ab=["build","dist","gen","generated","out","target",".next",".nuxt",".output",".svelte-kit"],W$=new Set([".agents",".cache",".claude",".codex",".comet",".git",".idea",".next",".nuxt",".output",".parcel-cache",".svelte-kit",".tmp",".turbo",".vscode",".worktrees","coverage","logs","node_modules","temp","tmp"]),hh=[":(exclude).comet/runtime/**",":(exclude).comet/current-change.json"],Ib=new Set(["comet-state.yaml","children.yaml","verification.md"]);function Bn(e,t){if(!t)return[...hh];let r=j.relative(e,t).replaceAll("\\","/");if(j.isAbsolute(r)||r===".."||r.startsWith("../"))return[...hh];let i=r===""?"":`${r}/`;return[...hh,...["changes","archive"].flatMap(n=>[...Ib].map(a=>`:(exclude)${i}comet/${n}/**/${a}`))]}function mh(e,t,r){let i=e.replaceAll("\\","/").replace(/^\.\//u,"");if(i===".comet/current-change.json"||i.startsWith(".comet/runtime/"))return!0;if(!t||!r||!Ib.has(j.basename(i)))return!1;let n=j.resolve(t,...i.split("/")),a=j.relative(j.resolve(r),n);if(j.isAbsolute(a)||a===".."||a.startsWith(`..${j.sep}`))return!1;let[,o]=a.split(j.sep);return a.startsWith(`comet${j.sep}`)&&(o==="changes"||o==="archive")}function Dn(){return{complete:!1,files:[]}}function z$(e){let t=e==="."?"":`${e}/`;return Ab.flatMap(r=>[`:(glob)${t}${r}/**`,`:(glob)${t}**/${r}/**`])}function Tb(e){return/(?:^|\/)(?:\.env(?:\..*)?|[^/]+\.(?:key|pem|p12|pfx))$/iu.test(e)}async function jb(e,t,r){let i=[...new Set(t.map(({cwdRef:s})=>s))];if(i.length===0)return{complete:!0,files:[]};let n;try{n=[...new Set(I(e,["ls-files","--others","--ignored","--exclude-standard","-z","--",...i.flatMap(z$)]).split("\0").filter(Boolean).map(s=>s.replaceAll("\\","/")))].sort()}catch{return Dn()}if(n.length>Pb)return Dn();let a=[],o=0;for(let s of n){if(mh(s,e,r))continue;let c=j.resolve(e,...s.split("/"));if(!be(e,c)||Tb(s))return Dn();try{let l=await Qt.lstat(c);if(!l.isFile()||o+l.size>_b)return Dn();let{digest:u,size:f}=await Mo(c);o+=f,a.push({path:s,digest:u,size:f})}catch{return Dn()}}return{complete:!0,files:a}}async function J$(e,t,r){let i=[...new Set(t.map(({cwdRef:c})=>c))],n=new Map,a=0,o=c=>Ab.includes(c),s=async(c,l,u)=>{let f;try{f=await Qt.readdir(c,{withFileTypes:!0})}catch{return!1}f.sort((d,p)=>d.name.localeCompare(p.name,"en"));for(let d of f){let p=l?`${l}/${d.name}`:d.name;if(mh(p,e,r)||d.isDirectory()&&W$.has(d.name))continue;let m=j.join(c,d.name);if(d.isDirectory()){if(!await s(m,p,u||o(d.name)))return!1;continue}if(u){if(Tb(p)||!d.isFile())return!1;try{let h=await Qt.lstat(m);if(a+h.size>_b)return!1;let{digest:g,size:v}=await Mo(m);if(a+=v,n.set(p,{path:p,digest:g,size:v}),n.size>Pb)return!1}catch{return!1}}}return!0};for(let c of i){let l=Za(e,c);if(!await s(l,c==="."?"":c,o(j.basename(l))))return Dn()}return{complete:!0,files:[...n.values()].sort((c,l)=>c.path.localeCompare(l.path,"en"))}}function vh(e,t){return T("comet.native.local-check-evidence.v1",{id:e.id,name:e.name,status:e.status,repeatable:e.repeatable,timeoutMs:e.timeoutMs,argv:e.argv,cwd:j.resolve(e.cwd),exitCode:e.exitCode,startedAt:e.startedAt,completedAt:e.completedAt,log:e.log,logDigest:Rb(t)})}async function G$(e){let t={complete:!0,capture:"git",head:null,branch:null,status:null,diff:null,stagedDiff:null,submodules:null,untracked:[],ignored:{complete:!0,files:[]},physical:{complete:!0,files:[]},reuseNonce:null},r=!1;try{t.head=I(e.projectRoot,["rev-parse","HEAD"]),r=!0,t.branch=I(e.projectRoot,["branch","--show-current"]),t.status=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...Bn(e.projectRoot,e.managedArtifactRoot)]);let i=I(e.projectRoot,["diff","--name-only","-z","HEAD","--",...Bn(e.projectRoot,e.managedArtifactRoot)]).split("\0").filter(Boolean).sort();t.diff=await th(i,4,async o=>{let s=j.resolve(e.projectRoot,...o.split("/"));try{let{digest:c}=await Mo(s);return{path:o,digest:c}}catch{return{path:o,digest:null}}}),t.diff.some(({digest:o})=>o===null)&&(t.complete=!1);let n=I(e.projectRoot,["ls-files","--stage","-z","--",...Bn(e.projectRoot,e.managedArtifactRoot)]);t.stagedDiff=Rb(n),t.submodules=V$(n)?I(e.projectRoot,["submodule","status","--recursive"]):"";let a=I(e.projectRoot,["ls-files","--others","--exclude-standard","-z","--",...Bn(e.projectRoot,e.managedArtifactRoot)]).split("\0").filter(Boolean).sort();t.untracked=await th(a,4,async o=>{let s=j.resolve(e.projectRoot,...o.split("/"));try{let{digest:c,size:l}=await Mo(s);return{path:o,digest:c,size:l}}catch{return{path:o,digest:null,size:null}}}),t.untracked.some(({digest:o})=>o===null)&&(t.complete=!1),t.ignored=await jb(e.projectRoot,e.plans,e.managedArtifactRoot),t.ignored.complete||(t.complete=!1)}catch{r?t.complete=!1:(t.capture="physical-tree",t.physical=await J$(e.projectRoot,e.plans,e.managedArtifactRoot),t.complete=t.physical.complete)}return T("comet.native.check-input.v1",{candidateId:e.state.builder_handoff?.candidate_id??null,shapeConfirmationHash:e.state.shape_confirmation_hash??null,acceptance:e.state.acceptance.map(({id:i,source:n,text:a})=>({id:i,source:n,text:a})),git:t,projectRoot:j.resolve(e.projectRoot),machineId:Zr.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,path:process.env.PATH??null,pathext:process.env.PATHEXT??null,boundEnvironment:Object.entries(process.env).filter(([i])=>$b.has(i.toUpperCase())).map(([i,n])=>[i,n??null]).sort(([i],[n])=>i.localeCompare(n))})}var $b=new Set(["PATH","PATHEXT","NODE_OPTIONS","NODE_ENV","NODE_PATH","LANG","LC_ALL","HOME","USERPROFILE","SYSTEMROOT","COMSPEC","SHELL","TMPDIR","TEMP","TMP","HTTP_PROXY","HTTPS_PROXY","NO_PROXY"]);function U$(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function K$(){return Object.entries(process.env).filter(([e])=>$b.has(e.toUpperCase())).map(([e,t])=>[e,t??null]).sort(([e],[t])=>e.localeCompare(t))}async function Nb(e){try{let t=I(e.projectRoot,["rev-parse","HEAD"]),r=I(e.projectRoot,["branch","--show-current"]),i=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...Bn(e.projectRoot,e.managedArtifactRoot)]),n=I(e.projectRoot,["ls-files","--stage","-z","--",...Bn(e.projectRoot,e.managedArtifactRoot)]);if(t===null||i===null)return null;let a=[];for(let s of ka(e.projectRoot).filter(c=>!mh(c,e.projectRoot,e.managedArtifactRoot))){let c=j.resolve(e.projectRoot,...s.split("/")),l=null;try{l=(await Mo(c)).digest}catch{return null}a.push({path:s,digest:l})}a.sort((s,c)=>s.path.localeCompare(c.path,"en"));let o=await jb(e.projectRoot,e.plans??[],e.managedArtifactRoot);return o.complete?T("comet.native.check-input-gate.v1",{candidateId:e.candidateId,head:t,branch:r,status:i,staged:n,workingTree:a,ignored:o,projectRoot:j.resolve(e.projectRoot),machineId:Zr.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,boundEnvironment:K$()}):null}catch{return null}}function ei(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);if(r.status==="passed"&&(r.evidence!=="runtime"||!r.evidenceDigest))throw new Error(`Native Runtime check ${r.id} has no Runtime execution evidence`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:J(i),argv_display:eo(r.argv.slice(1)).map(n=>J(n)),argv_truncated:!1,cwd_ref:eu(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:U$(r)}})}function Y$(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function Oi(e){if(e.local===null||e.local.change!==e.state.name)return re({portableState:e.state,projectRoot:e.projectRoot,branch:ve(e.projectRoot)});let t=e.local.execution?.operationId??kb();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function ti(e){try{let t=await Se(D(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}async function Wo(e){let t=await ti({paths:e.paths,state:e.state}),r=KN({state:e.state,summary:e.summary}),i=await ce({paths:e.paths,previous:e.state,next:r});return await F(D(e.paths,e.state.name),Oi({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}async function X$(e,t){for(let r of e.checks)if(r.status==="passed"){if(r.evidence!=="runtime")return!1;try{let i=await z(t,j.resolve(t,...r.log.split(/[\\/]/u)));if(!(await Qt.stat(i)).isFile())return!1;let n=await Qt.readFile(i,"utf8");if(!r.evidenceDigest||r.evidenceDigest!==vh(r,n))return!1}catch{return!1}}return!0}async function Q$(e){return _(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(await Je({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=ve(e.projectRoot),i=D(e.paths,t.name),n=(await Ll({file:i,portableState:t,projectRoot:e.projectRoot,branch:r,containedRoot:e.paths.runtimeDir})).state,a=await Nb({projectRoot:e.projectRoot,candidateId:t.builder_handoff?.candidate_id??null,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),o=await Nb({projectRoot:e.projectRoot,candidateId:t.builder_handoff?.candidate_id??null,plans:[],managedArtifactRoot:e.paths.artifactRoot}),s=a===null,l=a!==null&&n.inputFingerprint!==null&&n.inputFingerprintGate===a&&n.candidateInputFingerprintGate===o&&n.candidateId===t.builder_handoff?.candidate_id&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.machineId===Zr.hostname()?n.inputFingerprint:await G$({state:t,projectRoot:e.projectRoot,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),u=pe(e.paths,t.name),f=await X$(n,u),d=n.checks.every(k=>k.status==="passed"),p=e.retryCheckIds===void 0?null:new Set(e.retryCheckIds),m=n.candidateId===t.builder_handoff?.candidate_id&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===Zr.hostname()&&n.inputFingerprint===l,h=o!==null&&n.candidateInputFingerprintGate===o&&n.candidateId===t.builder_handoff?.candidate_id&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===Zr.hostname(),g=h&&n.inputFingerprint!==null&&n.inputFingerprint!==l,v=Eb(n,e.plans,e.projectRoot,t,l,r)||h&&wb(n,e.plans,e.projectRoot),w=n.candidateId===t.builder_handoff?.candidate_id&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===Zr.hostname(),y=m&&d&&!f;if(p&&p.size===0)throw new Error("Native check retry list must contain at least one ID");if(!m&&n.execution?.stage==="checking"&&n.execution.actor==="runtime"&&n.execution.status==="running"){let k=await Ql(n);if(k!=="orphaned")throw new Error(k==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before changing its binding":"Native check plan is already in progress on another workspace binding");n=yb(n),await F(i,n,{containedRoot:e.paths.runtimeDir})}if(!m&&w&&n.inputFingerprint!==null&&(n.execution!==null||n.checks.length>0)){let k=n.inputFingerprint!==l;if(!(s&&!k||g)){let E=Yr({state:t,reason:"Native check input changed after the candidate was built; a new Builder candidate is required before checks can run again."}),C=await ce({paths:e.paths,previous:t,next:E});throw await F(i,re({portableState:C,projectRoot:e.paths.projectRoot,branch:r}),{containedRoot:e.paths.runtimeDir}),new Error("Native check input changed after the candidate was built; the change returned to Build for a new candidate")}}if(!m&&!h){let k=re({portableState:t,projectRoot:e.projectRoot,branch:r});await F(i,k,{containedRoot:e.paths.runtimeDir}),n=k}let b=wb(n,e.plans,e.projectRoot);if(n.execution?.stage==="checking"&&n.execution.actor==="runtime"&&b&&v){let k=n.execution;if(k.status==="running"){let C=await Ql(n);if(C!=="orphaned")throw new Error(C==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before retrying":"Native check plan is already in progress");n=yb(n),await F(i,n,{containedRoot:e.paths.runtimeDir}),k=n.execution}let E=n.checks.filter(C=>C.status==="interrupted");if(E.length===0&&k.status==="completed"&&d&&!y&&!g){let C=new Map(e.plans.map(({id:H,name:P})=>[H,P]));return{kind:"reuse",state:t,checks:ei({local:n,projectRoot:e.projectRoot,supplied:[],requestedNames:C})}}if(E.length===0&&k.status==="completed"&&!d&&!y&&!g)throw new Error(`Native check plan contains a failed check (${n.checks.filter(({status:C})=>C==="failed").map(({id:C})=>C).join(", ")}); submit a new Builder candidate`);if(E.length>0&&E.some(C=>!C.repeatable)&&!y){let C=Yr({state:t,reason:`A non-repeatable Runtime check was interrupted (${E.filter(P=>!P.repeatable).map(({id:P})=>P).join(", ")}); a new Builder candidate is required before it can run again.`}),H=await ce({paths:e.paths,previous:t,next:C});throw await F(D(e.paths,t.name),re({portableState:H,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${E.find(P=>!P.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}if(E.length>0&&p===null&&!y&&!g){let C=new Map(e.plans.map(({id:H,name:P})=>[H,P]));return{kind:"reuse",state:t,checks:ei({local:n,projectRoot:e.projectRoot,supplied:[],requestedNames:C})}}if(p){let C=[...p].filter(P=>!E.some(W=>W.id===P));if(C.length>0)throw new Error(`Native check retry IDs must refer to interrupted checks: ${C.join(", ")}`);let H=E.filter(P=>p.has(P.id)&&P.executionCount>=3);if(H.length>0)throw new Error(`Native check retry limit (3) reached: ${H.map(({id:P})=>P).join(", ")}`)}}if(n.execution!==null&&n.checks.length>0){if(!(n.execution.stage==="checking"&&n.execution.actor==="runtime"&&n.checks.some(E=>E.status==="interrupted")&&b)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan")}else if((n.execution!==null||n.checks.length>0)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan");let S=kb(),N=await Ke(process.pid),x={...n,candidateId:t.builder_handoff?.candidate_id??null,inputFingerprint:l,inputFingerprintGate:a,candidateInputFingerprintGate:o,workspace:{...n.workspace,projectRoot:j.resolve(e.projectRoot),worktreeRoot:j.resolve(e.projectRoot),branch:ve(e.projectRoot),machineId:Zr.hostname()},execution:{operationId:S,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0,ownerPid:process.pid,...N?{ownerIdentity:N}:{}},checks:e.plans.map(k=>{let E=n.checks.find(C=>C.id===k.id);return g&&E?Zl(k,S,e.projectRoot):y&&E?Cb(E,k,S,e.projectRoot):E?.status==="interrupted"&&(p===null||p.has(E.id))?xb(E,k,S,e.projectRoot):E?{...E,operationId:S,activeProcess:null}:Zl(k,S,e.projectRoot)})};return await F(i,x,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:x,plans:e.plans.filter(k=>{let E=n.checks.find(C=>C.id===k.id);return y||g||E===void 0||E.status==="interrupted"&&(p===null||p.has(E.id))})}})}async function Fo(e){return _(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await $(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=D(e.paths,t.name),i=await Se(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await F(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function zo(e){let t=e.projectRoot??e.paths.projectRoot;Ye(t,e.plans);let r=[],i=new Set;for(let c of e.plans){to(t,c);let l=vn(c);i.has(l)||(i.add(l),r.push(c))}let n=await Q$({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return{...n,disposition:"reused"};let a=n.local.execution.operationId,o=pe(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await Fo({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(p=>p.id===c.id?{...p,status:"running",executionCount:p.executionCount+1,startedAt:l,activeProcess:{status:"starting"}}:p)})});let u=await Ni({projectRoot:t,runtimeDir:o,operationId:a,plan:c,onSpawn:async({pid:d})=>{let p=await Ke(d);await Fo({paths:e.paths,state:n.state,operationId:a,update:m=>({...m,checks:m.checks.map(h=>h.id===c.id?{...h,activeProcess:{status:"running",pid:d,...p?{identity:p}:{}}}:h)})})}}),f=await Qt.readFile(j.resolve(o,...u.logRef.split("/")),"utf8");await Fo({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(p=>{if(p.id!==c.id)return p;let m={...p,status:u.status,exitCode:u.exitCode,startedAt:u.startedAt,completedAt:u.completedAt,log:u.logRef,activeProcess:null,evidence:"runtime"};return{...m,evidenceDigest:vh(m,f)}})})})}await Fo({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await Fo({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted",activeProcess:null}:u)})})}catch{}throw c}let s=await Se(D(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:ei({local:s,projectRoot:t,supplied:[]}),disposition:"executed"}}async function gh(e){if(e.checkIds.length===0)throw new Error("Native check retry list must contain at least one ID");let t=e.projectRoot??e.paths.projectRoot,r=await $(e.paths,e.name);if(r.phase!=="verify"||r.status!=="active"||r.loop.stage!=="verify-ready"||r.builder_handoff===null)throw new Error("Native check retry requires an active Verify-ready candidate");let i=await Se(D(e.paths,e.name));if(i===null||i.change!==r.name||i.basedOnStateVersion!==r.state_version||i.execution===null||i.execution.stage!=="checking"||i.execution.actor!=="runtime")throw new Error("Native check retry has no current Runtime check execution");let n=new Set(e.checkIds);if(n.size!==e.checkIds.length)throw new Error("Native check retry list contains duplicate IDs");let a=i.checks.filter(c=>n.has(c.id)),o=e.checkIds.filter(c=>!a.some(l=>l.id===c));if(o.length>0)throw new Error(`Native check retry IDs are unknown: ${o.join(", ")}`);for(let c of a){if(c.status!=="interrupted")throw new Error(`Native check ${c.id} is not interrupted and cannot be retried`);if(!c.repeatable)throw new Error(`Native check ${c.id} is not repeatable and cannot be retried`);if(c.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${c.id}`)}let s=i.checks.map(c=>{let[l,...u]=c.argv;if(!l)throw new Error(`Native local check ${c.id} has no executable`);return{id:c.id,name:c.name,executable:l,argv:u,cwdRef:eu(t,c.cwd),timeoutMs:c.timeoutMs,repeatable:c.repeatable}});return zo({paths:e.paths,name:e.name,plans:s,projectRoot:t,retryCheckIds:e.checkIds})}async function Ob(e){let t=D(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=Yp)throw new Error(`Native Verifier request-checks exceeded ${Yp} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let p of r.checks){let m=Xl(p,e.projectRoot);n.set(m,p),p.status!=="interrupted"&&i.set(m,p),a.set(p.id,m)}let o=new Map,s=new Map;for(let p of e.response.checks){let m=Y$(p);to(e.projectRoot,m);let h=vn(m),g=s.get(m.id);if(g!==void 0&&g!==h)throw new Error(`Native Verifier check ID ${m.id} refers to conflicting commands`);let v=a.get(m.id);if(v!==void 0&&v!==h)throw new Error(`Native Verifier check ID ${m.id} conflicts with a Runtime check`);s.set(m.id,h);let w=n.get(h);if(w?.status==="interrupted"&&!w.repeatable)throw new Error(`Native check ${w.id} was interrupted and is not repeatable; user resolution is required`);if(w?.status==="interrupted"&&w.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${w.id}`);o.has(h)||o.set(h,m)}Ye(e.projectRoot,[...o.values()]);let c=[...o.entries()],l=c.filter(([p])=>!i.has(p));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let u=r.execution.requestCheckRounds+1,f=new Map(c.map(([,p])=>[p.id,p.name])),d={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:u},checks:[...r.checks.map(p=>{let m=Xl(p,e.projectRoot),h=o.get(m);return h&&p.status==="interrupted"?xb(p,h,r.execution.operationId,e.projectRoot):p}),...l.filter(([p])=>!n.has(p)).map(([,p])=>Zl(p,r.execution.operationId,e.projectRoot))]};return await F(t,d,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:d,verifierExecutionRef:e.envelope.verifierExecutionRef,round:u,novelPlans:l.map(([,p])=>p),requestedNames:f,reusedCheckIds:c.filter(([p])=>i.has(p)).map(([,p])=>p.id),suppliedChecks:e.suppliedChecks}}async function Vo(e){return _(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await $(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=D(e.paths,t.name),i=await Se(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await F(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function Hb(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await Vo({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>c.id===r.id?{...c,status:"running",executionCount:c.executionCount+1,startedAt:i,activeProcess:{status:"starting"}}:c)})});let n=pe(e.paths,e.reservation.state.name),a=await Ni({projectRoot:e.projectRoot,runtimeDir:n,operationId:e.reservation.local.execution.operationId,plan:r,onSpawn:async({pid:s})=>{let c=await Ke(s);await Vo({paths:e.paths,reservation:e.reservation,update:l=>({...l,checks:l.checks.map(u=>u.id===r.id?{...u,activeProcess:{status:"running",pid:s,...c?{identity:c}:{}}}:u)})})}}),o=await Qt.readFile(await z(n,j.resolve(n,...a.logRef.split(/[\\/]/u))),"utf8");t=await Vo({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>{if(c.id!==r.id)return c;let l={...c,status:a.status,exitCode:a.exitCode,startedAt:a.startedAt,completedAt:a.completedAt,log:a.logRef,activeProcess:null,evidence:"runtime"};return{...l,evidenceDigest:vh(l,o)}})})})}t=await Vo({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await Vo({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted",activeProcess:null}:n)})})}catch{}throw r}return{checks:ei({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}ne();Bc();rt();import{accessSync as yJ,constants as NJ,promises as qb}from"node:fs";import Mb from"node:path";st();le();st();le();gi();lr();ut();Fr();async function wh(e){return _(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(Tt({state:t,expected:e.expectedContinuation,action:"confirm-shape"}),t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native Shape can only be confirmed from the persisted user confirmation boundary");if(e.coordinationMode!==void 0)throw new Error("--coordination-mode must be selected before final Shape confirmation");await Je({paths:e.paths,state:t});let r=await Ul({paths:e.paths,state:t}),i=await Kl({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Fe({changeDir:se(e.paths,t.name),acceptanceIds:n.map(({id:v})=>v),validation:dt({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await Hc(e.paths,t.name);let v=Fl(t.workspace,e.paths.projectRoot);if(v===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");o=ye({...t,workspace:v},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${v.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await _o(se(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2,c=t.coordination_mode;if(s&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(s&&c===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");let l=Yl({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:c});if(t.shape_confirmation_hash===void 0||l!==t.shape_confirmation_hash){let v=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await qo({paths:e.paths,state:t,reason:v,keepFailureBudget:!0}),new Error(`${v}; Native change returned to Shape and requires confirmation`)}let u=qN({state:{...o,spec_changes:r},acceptance:n.map(v=>({...v}))});if(delete u.children_contract_hash,delete u.coordination_mode,a){u.children_contract_hash=An({acceptance:u.acceptance,children:a.contract}),s&&(u.coordination_mode=c);let v=[...t.history].reverse().find(({outcome:w})=>w==="pass"||w==="fail");if(v?.outcome==="fail"&&v.unresolved_ids.length>0){let w=await je({paths:e.paths,state:u}),y=new Map((w?.children??[]).map(({name:N,status:x})=>[N,x])),b=new Set(a.contract.children.filter(({name:N})=>{let x=y.get(N);return x!=="done"&&x!=="integrated"&&x!=="archived"}).flatMap(({covers:N})=>N)),S=v.unresolved_ids.filter(N=>!b.has(N));if(S.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${S.join(", ")}`)}}let f=null,d=a?.contract.schema==="comet.native.children.v2"?await O(e.paths,t.name):null,p=null,m=null;if(a?.contract.schema==="comet.native.children.v2"){if(p=o.workspace.change_branch??o.workspace.target_branch,!p)throw new Error("Native Supervisor v2 requires a target branch");if(m=ar(e.paths.projectRoot,p),!m)throw new Error(`Native Supervisor target branch has no commit: ${p}`);d||(d=await Po({paths:e.paths,parent:t.name,targetBranch:p,contract:a.contract})),d||(f=await zp({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:p,sourceConfig:await _e(e.paths.projectRoot)}))}let h=a?.contract.schema==="comet.native.children.v2"&&p&&m?d?_f({state:d,contract:a.contract}):f?Ja({parent:u.name,targetBranch:p,targetCommit:m,integrationBranch:f.binding.changeBranch,integrationWorktree:f.projectRoot,contract:a.contract}):null:null;if(a?.contract.schema==="comet.native.children.v2"&&!h)throw new Error("Native Supervisor integration state is unavailable");let g=await ce({paths:e.paths,previous:t,next:u});return await F(D(e.paths,t.name),re({portableState:g,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),h&&await q(e.paths,h),g})}import{randomUUID as Z$}from"node:crypto";import tu from"node:path";le();Ma();mi();function Db(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function eO(e){let{state:t,local:r,envelope:i}=e;if(!Ac(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function tO(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function yh(e){return _(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(await Je({paths:e.paths,state:t}),await Fe({changeDir:se(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:dt(t)})||t.children_contract_hash){let a=await je({paths:e.paths,state:t});if(!a?.confirmed||!a.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=VN({state:t,input:e.input}),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Nh(e){return _(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Je({paths:e.paths,state:t});let i=(await Ll({file:D(e.paths,t.name),portableState:t,projectRoot:r,branch:ve(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");ei({local:i,projectRoot:r,supplied:e.checks});let n=MN(t),a=await ce({paths:e.paths,previous:t,next:n}),o=D(e.paths,t.name),s=Z$();return await F(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function bh(e){return _(e.paths,`confirm portable verifier start ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier start confirmation requires an active Verifier attempt");let r=D(e.paths,e.name),i=await Se(r),n=i?.execution;if(i===null||i.change!==t.name||i.basedOnStateVersion!==t.state_version||!n||n.stage!=="verifying"||n.actor!=="verifier"||n.status!=="running"||n.executionId===null||n.executionId!==e.verifierExecutionRef)throw new Error("Native Verifier start confirmation is stale for the current attempt");if(t.builder_handoff?.candidate_id!==e.candidateId)throw new Error("Native Verifier start confirmation is stale for the current candidate");return n.verifierStartedAt===void 0&&await F(r,{...i,execution:{...n,verifierStartedAt:new Date().toISOString()}},{containedRoot:e.paths.runtimeDir}),t})}async function kh(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await _(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await $(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Je({paths:e.paths,state:r});let n=await ti({paths:e.paths,state:r}),a=eO({state:r,local:n,envelope:e.envelope}),o;try{o=Va(a.payload)}catch(f){let d=`Native Verifier response was invalid: ${f.message}`,p=await Wo({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${p.loop.execution_failure_count}/${Ao} was recorded`,{cause:f})}let s=tO(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=ei({local:n,projectRoot:i,supplied:e.checks}));let f=WN({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(f.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await Ob({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:f.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:f.response,reservation:d}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=f}catch(f){let d=`Native Verifier response was invalid: ${f.message}`,p=await Wo({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${p.loop.execution_failure_count}/${Ao} was recorded`,{cause:f})}let u=await ce({paths:e.paths,previous:r,next:l.state});return await F(D(e.paths,r.name),u.loop.next_action==="resolve-verifier-blocker"||u.loop.next_action==="run-final-full-verification"?Oi({local:n,state:u,projectRoot:i}):re({portableState:u,projectRoot:i,branch:ve(i)}),{containedRoot:e.paths.runtimeDir}),u.verification!==null&&await Xr({file:tu.join(se(e.paths,r.name),"verification.md"),state:u}),{kind:"final-result",result:{state:u,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await Hb({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await _(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await $(e.paths,e.name);return a.state_version!==t.state.state_version?null:Wo({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Ao} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function Sh(e){return _(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await $(e.paths,e.name),r=await ti({paths:e.paths,state:t});if(Db({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return Wo({paths:e.paths,state:t,summary:e.summary})})}async function Eh(e){return _(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);await Je({paths:e.paths,state:t});let r=await ti({paths:e.paths,state:t}),i=Db({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=ei({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=JN({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await ce({paths:e.paths,previous:t,next:a});return await F(D(e.paths,t.name),Oi({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await Xr({file:tu.join(se(e.paths,t.name),"verification.md"),state:o}),o})}async function xh(e){return _(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Je({paths:e.paths,state:t});let r=GN({state:t,summary:e.summary}),i=await ce({paths:e.paths,previous:t,next:r});return await F(D(e.paths,t.name),re({portableState:i,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Xr({file:tu.join(se(e.paths,t.name),"verification.md"),state:i}),i})}async function Ch(e){return _(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Je({paths:e.paths,state:t});let r=await ti({paths:e.paths,state:t}),i=UN(t,{reason:e.reason}),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),Oi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Rh(e){return _(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await ti({paths:e.paths,state:t}),i=YN(t),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),Oi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Hi(e){return _(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await $(e.paths,e.name);if(Tt({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=e.preserveLocalChecks?await ti({paths:e.paths,state:t}):null,i=Yr({state:t,reason:e.reason,...e.failureBudget?{failureBudget:e.failureBudget}:{}}),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),e.preserveLocalChecks?Oi({local:r,state:n,projectRoot:e.paths.projectRoot}):re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Jo(e){if(e.state.verification===null)return"not-applicable";let t=tu.join(se(e.paths,e.state.name),"verification.md");return await fb({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Xr({file:t,state:e.state}),"rebuilt")}import rO from"node:path";lr();le();async function Ph(e){return _(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Je({paths:e.paths,state:t});let r=await O(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(Ii(r).stateVersion!==r.stateVersion)return Hn({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await q(e.paths,Ti(r,t))}let i=zN(t),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Xr({file:rO.join(se(e.paths,t.name),"verification.md"),state:n}),n})}import{promises as Bb}from"node:fs";lr();le();cl();async function Go(e){let t=await $(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await je({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选可以提交并进入验证":"All Children are complete; the Supervisor parent candidate can be submitted for verification.";return{state:t,parentAdvance:{...r,message:n}}}async function Lb(e){let t=await $(e.paths,e.name),r=await sl(e.paths,{kind:"archive",change:e.name}),i=r?.kind==="archive"?r:null;if(!i&&(t.archived||t.verification===null||t.verification_result!=="pass"))return{state:t,action:"none"};let n=await O(e.paths,e.name);if(i&&n?.finalVerification.status==="pending"){if(i.journal.status!=="prepared"||i.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await Bb.rm(i.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||n?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=Ii(n);if(i||a.stateVersion!==n.stateVersion){let o=await Hn({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return i&&await Bb.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await q(e.paths,Ti(n,t)),{state:t,action:"recorded-final-verification"}}async function ru(e){return _(e.paths,`recover Supervisor final verification ${e.name}`,()=>Lb(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}var uJ=16*1024;kn();Bc();var Fb="comet.native.workspace-finish.v1",iO="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Wb=new RegExp(`^${iO}$`,"u"),nO=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;function aO(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==Fb||typeof t.name!="string"||!Wb.test(t.name)||typeof t.transactionId!="string"||!nO.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Mb.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(i=>typeof i!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(i=>typeof i!="string")))throw new Error("Native workspace finish journal result is invalid")}return{schema:Fb,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt}}function oO(e,t){if(!Wb.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Mb.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function zb(e,t,r={}){let i=oO(e,t);try{let n=await qb.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=aO(JSON.parse(await qb.readFile(i,"utf8")));if(a.name!==t)throw new Error("Native workspace finish journal name is invalid");return a}catch(n){if(n.code==="ENOENT")return null;if(r.onError)return r.onError(t,n instanceof Error?n.message:String(n)),null;throw n}}import{randomUUID as sO}from"node:crypto";import{promises as Uo}from"node:fs";import cO from"node:path";ne();nt();le();lp();cl();il();ut();te();var Jb=["evidence.md","repair.md","archive.md","checkpoint.md"],lO="verification.md";async function uO(e,t){let r=await sl(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Gb(e,t){await Uo.mkdir(e.transactionsDir,{recursive:!0}),await we(ol(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Ub(e,t,r={}){let i=r.removeVerificationReport===!1?Jb:[...Jb,lO];await Promise.all([Uo.rm(pe(e,t),{recursive:!0,force:!0}),Uo.rm(gf(e,t),{recursive:!0,force:!0}),...i.map(n=>Uo.rm(cO.join(At(e,t),n),{force:!0}))])}async function Kb(e,t){await F(D(e,t.name),re({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Yb(e,t){try{let r=await Oo(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function Xb(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=ie(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function dO(e){let t=At(e.paths,e.state.name),r=await Q({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Q({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return rl({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Qb(e,t){let r=await sb(e,t);if(r.status==="runtime-incompatible")throw new Vt(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Zb(e){return _(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await uO(e.paths,e.name),r=await $n(e.paths,e.name)?await lt(Qe(e.paths,e.name)):null;if(!t&&r)return await Ub(e.paths,e.name,{removeVerificationReport:!1}),await Kb(e.paths,r),r;let i=null,n=null;for(t||(i=await Qb(e.paths,e.name),n=await Yb(e.paths,e.name),Xb(e.paths,n),t={schema:nl,id:sO(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Gb(e.paths,t));;){let a=gy(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await Qb(e.paths,e.name),n??=await Yb(e.paths,e.name),Xb(e.paths,n),r=vy({state:i,acceptance:await dO({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await La(Qe(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Ub(e.paths,e.name):a.action==="commit-transaction"&&(r??=await lt(Qe(e.paths,e.name)),await Kb(e.paths,r)),t={...t,status:a.nextStatus},await Gb(e.paths,t)}return await Uo.rm(ol(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??lt(Qe(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as tk}from"node:fs";import rk from"node:path";le();import{promises as _h}from"node:fs";import fO from"node:path";fe();var pO=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),hO=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),mO=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),vO=new Set(["status","summary"]);function iu(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function nu(e,t,r,i=new Set){let n=new Set(Object.keys(e)),a=[...t].filter(s=>!n.has(s)&&!i.has(s)),o=[...n].filter(s=>!t.has(s));return a.length===0&&o.length===0?null:`${r} fields must be exact (missing: ${a.join(", ")||"none"}; unexpected: ${o.join(", ")||"none"})`}function gO(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function Di(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function wO(e,t,r,i){let n=iu(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=nu(n,pO,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=iu(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=nu(o,hO,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=iu(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=nu(c,vO,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,f]of n.children.entries()){let d=iu(f,`Native Supervisor child ${u}`);if(!d)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:p,contractHash:m,...h}=d,g=nu(h,mO,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(g)return g;let v=r.children[u],w=v.covers.length>0?v.covers.map(b=>({id:b,source:r.acceptance_index?.[b]?.source??"brief.md",text:r.acceptance_index?.[b]?.text??b})):[{id:`child:${v.name}`,source:"children.yaml",text:v.summary??v.name}];if(p!==void 0&&JSON.stringify(p)!==JSON.stringify(w)||m!==void 0&&m!==T("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${v.name} acceptance scope does not match the legacy contract`;if(d.name!==v.name||d.summary!==v.summary||!gO(d.dependsOn,v.depends_on))return`Native Supervisor child ${v.name} does not match the legacy children contract`;let y=v.depends_on.length===0?"ready":"pending";if(d.status!==y)return`Native Supervisor child ${v.name} has progressed beyond its initial ${y} status`;if(d.baseCommit!==null||d.candidateCommit!==null||d.verifiedCommit!==null||d.integrationCommit!==null||d.verification!==null||d.blocker!==null||d.projectRoot!==null||d.task!==null)return`Native Supervisor child ${v.name} contains execution progress`;if((d.builderFailureCount??0)!==0)return`Native Supervisor child ${v.name} contains Builder failure progress`;if(!Array.isArray(d.checks)||d.checks.length!==0)return`Native Supervisor child ${v.name} contains integration checks`}return null}async function qn(e){let t=wi(e.paths,e.state.name),r;try{let c=await _h.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Di(t,"","Native Supervisor overlay is not a regular file");r=await _h.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Di(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return Di(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=fO.join(e.paths.changesDir,e.state.name),a;try{a=await Fe({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Di(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await O(e.paths,e.state.name)}catch(c){return Di(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Di(t,r,"Native Supervisor overlay disappeared during inspection");let s=wO(i,e.state,a.contract,o);return s?Di(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}async function ek(e){let t=await qn({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await _h.rm(t.file,{force:!1})}ut();Fr();function Ah(e,t){let r=ie(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function yO(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function NO(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:ye(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(t),completed_at:i});return B({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?yO(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function bO(e){try{let t=await Se(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Ih(e){return _(e.paths,`recover portable change ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(t.status==="done")return await Jo({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=Ah(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await qn({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await ek({paths:e.paths,state:t,expected:i}),n=!0);let a=D(e.paths,e.name),o=await bO(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason,c=s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed";if(c&&o.local?.execution?.status==="running"){let h=o.local.execution,g=await Ql(o.local),v=h.stage==="verifying"&&h.actor==="verifier"&&h.executionId!==null,w=g==="unknown"&&e.recoverUnknownRuntimeCheck===!0&&h.stage==="checking"&&h.actor==="runtime";if(v||g!=="orphaned"&&!w)return{state:t,local:o.local,action:"await-user",reason:"execution-active",message:v?h.verifierStartedAt===void 0&&h.requestCheckRounds===0?`Native Verifier execution ${h.executionId} is registered but never confirmed startup; if the task did not start, record an explicit Verifier failure before retrying it.`:`Native Verifier execution ${h.executionId} remains owned by its host task; record an explicit Verifier failure before retrying it.`:g==="unknown"?"The Native Runtime check owner could not be proven to have exited; inspect the overlay or run Doctor with --repair to take over explicitly.":"The Native Runtime check operation is still owned by a live process; wait for it to finish before recovering it."}}if(c&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(h=>h.status==="planned"||h.status==="running"?{...h,status:"interrupted"}:h)},await F(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Jo({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(h=>h.status==="interrupted"&&!h.repeatable):void 0;if(l){let h=Yr({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await dn({file:Qe(e.paths,t.name),expectedStateVersion:t.state_version,next:h,containedRoot:e.paths.nativeRoot}),await tk.rm(rk.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let g=re({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await F(a,g,{containedRoot:e.paths.runtimeDir}),{state:t,local:g,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let u=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",f=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",d=u||f;if(d){let h=NO(t,f?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",f);t=await dn({file:Qe(e.paths,t.name),expectedStateVersion:t.state_version,next:h,containedRoot:e.paths.nativeRoot})}let p=re({portableState:t,projectRoot:e.paths.projectRoot,branch:ie(e.paths.projectRoot).currentBranch});await tk.mkdir(rk.dirname(D(e.paths,t.name)),{recursive:!0}),await F(a,p,{containedRoot:e.paths.runtimeDir}),await Jo({paths:e.paths,state:t});let m=s==="stale"&&o.local?`Local execution overlay was recorded for state version ${String(o.local.basedOnStateVersion)} of ${o.local.change} but the current state version is ${String(t.state_version)} of ${t.name}; a state transition moved on, so the overlay was rebuilt from the stable boundary.`:null;return{state:t,local:p,action:d?"reverify":"resume-stable-boundary",reason:s,message:m??(d?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`)}})}import ik from"node:path";function nk(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function xe(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:nk(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:nk(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>ik.relative(t.projectRoot,ik.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}_c();function Th(e){return e.charCodeAt(0)===65279?e.slice(1):e}kn();rt();import{randomUUID as dk}from"node:crypto";import{promises as ak}from"node:fs";import Ko from"node:path";gn();Wp();Ma();le();mi();function Mn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function V(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function Fn(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>V(r,`${t}[${i}]`))}function kO(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=Mn(t,`Native Builder check ${r}`);if(ee(i,["name","result","note"],`Native Builder check ${r}`,`/checks/${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:V(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function au(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=Mn(t,`Native Runtime check ${r}`);if(ee(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`,`/checks/${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:V(i.id,`Native Runtime check ${r} id`),name:V(i.name,`Native Runtime check ${r} name`),executable:V(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:V(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function ok(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:V(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function SO(e){let t=Mn(e,"Native Supervisor evidence");return ee(t,["summary","checks","acceptance","receiptRef"],"Native Supervisor evidence","/evidence"),{summary:V(t.summary,"Native Supervisor evidence summary"),checks:Fn(t.checks,"Native Supervisor evidence checks"),acceptance:Tc(t.acceptance,"/evidence/acceptance"),...t.receiptRef===null?{}:{receiptRef:V(t.receiptRef,"Native Supervisor receipt ref")}}}function EO(e){let t=Mn(e,"Native Runner input");if(t.kind==="builder-handoff"){let r=["kind","summary","addressed_acceptance_ids","checks","known_limits"];Object.hasOwn(t,"verification_checks")&&r.push("verification_checks"),ee(t,Object.hasOwn(t,"review")?[...r,"review"]:r,"Native Runner Builder input");let i=null;if(t.review!==void 0&&t.review!==null){let n=Mn(t.review,"Native Builder review");if(ee(n,["status","summary","reviewer_execution_ref"],"Native Builder review","/review"),n.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");i={status:"passed",summary:V(n.summary,"Native Builder review summary"),reviewer_execution_ref:V(n.reviewer_execution_ref,"Native Builder reviewer execution ref")}}return{kind:"builder-handoff",summary:V(t.summary,"Native Builder summary"),addressed_acceptance_ids:Fn(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:kO(t.checks),...Object.hasOwn(t,"verification_checks")?{verification_checks:au(t.verification_checks)}:{},known_limits:Fn(t.known_limits,"Native Builder known limits"),review:i}}if(t.kind==="dispatch-verifier")return ee(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:au(t.checks)};if(t.kind==="retry-checks")return ee(t,["kind","check_ids"],"Native Runner check retry input"),{kind:"retry-checks",check_ids:Fn(t.check_ids,"Native check retry IDs")};if(t.kind==="verifier-response")return ee(t,["kind","candidateId","verifierExecutionRef","response"],"Native Runner Verifier input"),{kind:"verifier-response",candidateId:V(t.candidateId,"Native Runner Verifier candidateId"),verifierExecutionRef:V(t.verifierExecutionRef,"Native Runner Verifier verifierExecutionRef"),response:Va(t.response,"/response")};if(t.kind==="verifier-started")return ee(t,["kind","candidateId","verifierExecutionRef"],"Native Runner started input"),{kind:"verifier-started",candidateId:V(t.candidateId,"Native Runner started candidateId"),verifierExecutionRef:V(t.verifierExecutionRef,"Native Runner started verifierExecutionRef")};if(t.kind==="verifier-execution-error")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:V(t.summary,"Native Verifier execution error summary"),...ok(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:V(t.summary,"Native unavailable Verifier summary"),...ok(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return ee(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),candidateCommit:V(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return ee(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),reason:V(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-retry-builder"){if(ee(t,["kind","child","stateVersion"],"Native Supervisor Builder retry input"),!Number.isSafeInteger(t.stateVersion)||t.stateVersion<1)throw new Error("Native Supervisor Builder retry stateVersion is invalid");return{kind:"supervisor-retry-builder",child:V(t.child,"Native Supervisor child"),stateVersion:t.stateVersion}}if(t.kind==="supervisor-reconnect")return ee(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return ee(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),reason:V(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(ee(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:SO(t.evidence)}}if(t.kind==="supervisor-checks"){let r=["kind","child","runId","checks","materials"];if(ee(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor checks"),!Array.isArray(t.materials))throw new Error("Native Supervisor materials must be an array");return{kind:"supervisor-checks",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),checks:au(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:Fn(t.retry_check_ids,"Native Supervisor retry IDs")},materials:t.materials.map((i,n)=>{let a=Mn(i,"Native Supervisor material");return ee(a,["name","content"],"Native Supervisor material",`/materials/${n}`),{name:V(a.name,"Native Supervisor material name"),content:V(a.content,"Native Supervisor material content")}})}}if(t.kind==="supervisor-integrate"){let r=["kind","child","checks"];return ee(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor integration input"),{kind:"supervisor-integrate",child:V(t.child,"Native Supervisor child"),checks:au(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:Fn(t.retry_check_ids,"Native Supervisor retry IDs")}}}throw new Error("Native Runner input kind is invalid")}async function Hh(e,t){let r=Ko.resolve(t,e),i=await ak.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(Th(await ak.readFile(r,"utf8")))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return EO(n)}function xO(e){return e.kind==="builder-handoff"||e.kind==="dispatch-verifier"||e.kind==="retry-checks"||e.kind==="verifier-response"||e.kind==="verifier-started"||e.kind==="verifier-execution-error"||e.kind==="verifier-unavailable"}function CO(e){return e.kind.startsWith("supervisor-")}function RO(e){return e.response.kind!=="request-checks"?[]:e.response.checks.map(({id:t,name:r,executable:i,argv:n,cwdRef:a,timeoutMs:o,repeatable:s})=>({id:t,name:r,executable:i,argv:[...n],cwdRef:a,timeoutMs:o,repeatable:s}))}function sk(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.stage!=="verify-ready")throw new Error("Native Runner check input requires an active Verify-ready candidate")}function jh(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result")throw new Error("Native Runner Verifier input requires an active Verifier attempt")}function PO(e,t){if(new Set(t).size!==t.length)throw new Error("Native Builder addressed acceptance IDs contain duplicates");let r=new Set(e.acceptance.map(({id:n})=>n)),i=t.filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native Builder addressed acceptance IDs contain unknown IDs: ${i.join(", ")}`)}async function $h(e){let t=await Se(D(e.paths,e.state.name)),r=t?.execution;if(t===null||t.basedOnStateVersion!==e.state.state_version||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null)throw new Error("Native Runner Verifier input requires an active Runtime Verifier execution");return r}async function Dh(e){let t=await qn({paths:e.paths,state:e.state});if(t.status==="incompatible")throw new Error(t.message);let r=t.status==="repairable-legacy-overlay"?null:await O(e.paths,e.name),i=r!==null&&e.state.phase==="verify"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),n=r!==null&&e.state.phase==="build"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),a=await je({paths:e.paths,state:e.state}),o=(i||n)&&r?r.integration.worktree:e.projectRoot;if(CO(e.input)&&r===null)throw new Error("Native Supervisor Runner input requires a current Supervisor state");if(r&&xO(e.input)&&!i&&!(e.input.kind==="builder-handoff"&&n))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(e.input.kind==="builder-handoff"){if(e.state.phase!=="build"||e.state.status!=="active")throw new Error("Native Builder input requires an active Build boundary");if(PO(e.state,e.input.addressed_acceptance_ids),a&&(!a.confirmed||!a.allDone))throw new Error("Native parent Build advances child changes and does not accept a Builder handoff");if(n&&e.state.loop.stage==="repairing"&&e.state.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first");e.input.verification_checks!==void 0&&Ye(o,e.input.verification_checks);return}if(e.input.kind==="dispatch-verifier"){if(sk(e.state),i&&e.input.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");Ye(o,e.input.checks);return}if(e.input.kind==="retry-checks"){if(sk(e.state),e.input.check_ids.length===0||new Set(e.input.check_ids).size!==e.input.check_ids.length)throw new Error("Native check retry list must contain unique IDs");let c=await Se(D(e.paths,e.name));for(let l of e.input.check_ids){let u=c?.checks.find(f=>f.id===l);if(!u||u.status!=="interrupted")throw new Error(`Native check retry ID is not an interrupted current check: ${l}`);if(!u.repeatable)throw new Error(`Native check ${l} is not repeatable and cannot be retried`);if(u.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${l}`)}return}if(e.input.kind==="verifier-response"){jh(e.state);let c=await $h({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");Ye(o,RO(e.input));return}if(e.input.kind==="verifier-started"){jh(e.state);let c=await $h({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner started input is stale for the current candidate or execution");return}if(e.input.kind==="verifier-execution-error"||e.input.kind==="verifier-unavailable"){jh(e.state);let c=await $h({paths:e.paths,state:e.state});if(e.input.stateVersion!==e.state.state_version||e.input.iteration!==e.state.loop.iteration||e.input.attempt!==e.state.loop.attempt||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current attempt");return}let s=e.input;if(s.kind==="supervisor-retry-builder"){if(!r)throw new Error("Native Supervisor Builder retry requires a current Supervisor state");let c=r.children.find(({name:l})=>l===s.child);if(!c)throw new Error(`Native Supervisor child ${s.child} does not exist`);if(s.stateVersion!==r.stateVersion||c.status!=="blocked"||c.task!==null||(c.builderFailureCount??0)<cr)throw new Error("Native Supervisor Builder retry input is stale or not currently required");return}if(e.input.kind==="supervisor-checks"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:u})=>u)).size!==c.checks.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(c.checks.some(({repeatable:u})=>!u))throw new Error("Native Supervisor checks must be repeatable for safe recovery");let l=r?.children.find(({name:u})=>u===c.child)?.task;if(!l||l.role!=="verifier"||l.runId!==c.runId)throw new Error("Native Supervisor check runId is not current");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");Ye(l.projectRoot,c.checks);return}if(e.input.kind==="supervisor-integrate"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:l})=>l)).size!==c.checks.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(c.checks.some(({repeatable:l})=>!l))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");Ye(r.integration.worktree,c.checks)}}function ck(e){return`${Ne}:${e}:${dk()}`}function lk(e,t,r,i){if(Ko.resolve(I(e.projectRoot,["rev-parse","--show-toplevel"]))!==Ko.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(I(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!zt(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(I(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function _O(e,t){let r=ie(e.projectRoot),i=Ko.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==Ko.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=I(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!zt(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function Vn(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Ne)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");return e.builder_handoff}function AO(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function uk(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=Vn(r),s=AO(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:Ne,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:se(t,r.name),supervisorStateRef:a?wi(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:l,operation:u,source:f})=>({capability:l,operation:u,ref:f})),acceptanceCount:r.acceptance.length,scopeCount:c.length,scopeIds:c,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:o.review?{status:o.review.status,summary:o.review.summary}:null,runtimeChecks:i.map(l=>({...l})),builderReportedChecks:o.checks.map(l=>({...l})),builderKnownLimits:o.known_limits.map(l=>({...l})),startupInstruction:'As this Verifier, submit the startup receipt first: save {"kind":"verifier-started","candidateId":"<candidateId above>","verifierExecutionRef":"<verifierExecutionRef above>"} as a temporary JSON file and run comet native next <change> --runner-input <file> --project-root <projectRoot above>. It only records that this Verifier actually started; a repeat submission is accepted without side effects. Then read the scenarios and proceed.',evidenceInstruction:"Independently inspect the current candidate against every scenario in scopeIds exactly once. Runtime checks are bound evidence; Builder-reported checks and review are claims to corroborate, not Runtime receipts. Reuse applicable completed evidence, request only missing or invalidated checks, and do not repeat full suites by default. Use one Verifier for this dispatch; keep it running across wait-tool timeouts. Return the actual scoped findings, risks, and incomplete checks without omitting limitations. Keep using the same CLI executable that produced this dispatch; do not switch to a different PATH installation.",responseInstruction:"Return one acceptance entry for each ID in scopeIds and no other acceptance IDs. Runtime safely filters a known already-passed superset only when every extra entry still reports passed; nonexistent IDs and conflicting out-of-scope results remain invalid."}}async function Oh(e){Vn(e.state);let t=await Se(D(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function fk(e){let t=e.input,r=await $(e.paths,e.name),i=await qn({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await O(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:m})=>m==="integrated"||m==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:m})=>m==="integrated"||m==="archived");if(n&&t.kind==="supervisor-checks"){let m=await Mp({paths:e.paths,parent:e.name,child:t.child,runId:t.runId,plans:t.checks,materials:t.materials,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),h=await O(e.paths,e.name),g=h?.children.find(({name:v})=>v===t.child)?.task;return{state:r,supervisorState:h,supervisorTask:g&&g.runId===t.runId?Lr(g,e.name,e.paths.projectRoot):null,checks:[],checkExecution:m,requestChecks:null,verifierDispatch:null,continuation:K(r)}}if(n&&t.kind==="supervisor-builder-result")return _(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:b})=>b===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{lk(h.task,t.candidateCommit,"builder",`comet/supervisor/${m.parent}/${t.child}`)}catch(b){throw await q(e.paths,Ua(m,{child:t.child,runId:t.runId,reason:b.message})),b}let g=h.task.projectRoot,v=If(m,t),w=Ga(v,{role:"verifier",child:t.child,projectRoot:g,runId:dk()});await q(e.paths,w.state);let y=await $(e.paths,e.name);return{state:y,supervisorTask:Lr(w.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:K(y)}});if(n&&t.kind==="supervisor-builder-failure")return _(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:w})=>w===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let g=jc(m,{child:t.child,runId:t.runId,reason:t.reason});await q(e.paths,g);let v=await $(e.paths,e.name);return{state:v,supervisorState:g,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(v)}});if(n&&t.kind==="supervisor-retry-builder")return _(e.paths,`retry Native Supervisor Builder task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=jf(m,{child:t.child,expectedStateVersion:t.stateVersion});await q(e.paths,h);let g=await $(e.paths,e.name);return{state:g,supervisorState:h,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(g)}});if(n&&t.kind==="supervisor-reconnect")return _(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:w})=>w===t.child)?.task;if(!h||h.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{_O(h,`comet/supervisor/${m.parent}/${t.child}`)}catch(w){throw await q(e.paths,Ua(m,{child:t.child,runId:t.runId,reason:w.message})),w}let g=Af(m,{child:t.child,runId:t.runId});await q(e.paths,g.state);let v=await $(e.paths,e.name);return{state:v,supervisorState:g.state,supervisorTask:Lr(g.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:K(v)}});if(n&&t.kind==="supervisor-cancel")return _(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=jc(m,{child:t.child,runId:t.runId,reason:t.reason});await q(e.paths,h);let g=await $(e.paths,e.name);return{state:g,supervisorState:h,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(g)}});if(n&&t.kind==="supervisor-verifier-result")return _(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:y})=>y===t.child);if(!h?.task||h.task.role!=="verifier"||!h.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{lk(h.task,h.candidateCommit,"verifier",`comet/supervisor/${m.parent}/${t.child}`)}catch(y){throw await q(e.paths,Ua(m,{child:t.child,runId:t.runId,reason:y.message})),y}let g=t.evidence.receiptRef||t.verdict==="pass"?await _n({paths:e.paths,parent:e.name,task:h.task,receiptRef:t.evidence.receiptRef??""}):null;if(t.verdict==="pass"&&(!g||g.checks.some(({status:y,exitCode:b})=>y!=="passed"||b!==0)))throw new Error("Native Supervisor verification cannot pass before every Runtime check succeeds");let v=Tf(m,{...t,evidence:{...t.evidence,checks:g?.checks.map(({name:y,status:b})=>`${y}: ${b}`)??[],execution:structuredClone(h.task)}});await q(e.paths,v);let w=await $(e.paths,e.name);return{state:w,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(w)}});if(n&&t.kind==="supervisor-integrate"){let m=await Gp({paths:e.paths,state:n,name:t.child,checks:[],checkPlans:t.checks,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),h=await Go({paths:e.paths,name:e.name,trigger:"v2-integrate"}),g=h.state;return{state:g,supervisorState:m,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:h.parentAdvance,continuation:K(g)}}if(n&&(t.kind==="builder-handoff"||t.kind==="dispatch-verifier"||t.kind==="retry-checks"||t.kind==="verifier-response"||t.kind==="verifier-started"||t.kind==="verifier-execution-error"||t.kind==="verifier-unavailable"||t.kind==="supervisor-builder-result"||t.kind==="supervisor-builder-failure"||t.kind==="supervisor-reconnect"||t.kind==="supervisor-cancel"||t.kind==="supervisor-verifier-result")&&!a&&!(t.kind==="builder-handoff"&&o))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(t.kind==="builder-handoff"){let h=Cf().captureExecutionIdentity({identityProvider:Ne,executionRef:ck("builder")}),g=await yh({paths:e.paths,name:e.name,input:{identity:h,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,checks:t.checks,knownLimits:t.known_limits,review:t.review?{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}:null}});if(t.verification_checks!==void 0){let v=await zo({paths:e.paths,name:e.name,plans:t.verification_checks,...o&&n?{projectRoot:n.integration.worktree}:{}}),w=v.checks.filter(({status:S})=>S==="failed").map(({id:S})=>S),y=v.checks.filter(({status:S})=>S==="interrupted").map(({id:S})=>S),b=t.verification_checks.filter(({id:S,repeatable:N})=>y.includes(S)&&!N).map(({id:S})=>S);if(w.length>0||b.length>0){let S=w.length>0?`Builder handoff Runtime checks failed: ${w.join(", ")}`:`Builder handoff Runtime checks were interrupted and cannot be repeated: ${b.join(", ")}`,N=await Hi({paths:e.paths,name:e.name,reason:S,failureBudget:{maxVerifyFailures:e.maxVerifyFailures}});return{state:N,checks:v.checks,runtimeCheckExecution:{disposition:v.disposition},requestChecks:null,verifierDispatch:null,continuation:K(N)}}return{state:v.state,checks:v.checks,runtimeCheckExecution:{disposition:v.disposition},continuationCheckPlans:t.verification_checks,...y.length>0?{continuationRetryCheckIds:y}:{},requestChecks:null,verifierDispatch:null,continuation:K(v.state,void 0,{...y.length>0?{retryCheckIds:y}:{verificationCheckPlans:t.verification_checks}})}}return{state:g,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(g)}}if(t.kind==="retry-checks"){if(n&&!a)throw new Error("Native Supervisor check retry is only valid after every Child is integrated");let m=await $(e.paths,e.name);Vn(m);let h=await gh({paths:e.paths,name:e.name,checkIds:t.check_ids,...a&&n?{projectRoot:n.integration.worktree}:{}}),g=h.checks.filter(({status:v})=>v==="interrupted").map(({id:v})=>v);if(g.length>0){let w=((await Se(D(e.paths,e.name)))?.checks??[]).filter(({id:y,status:b,executionCount:S})=>g.includes(y)&&b==="interrupted"&&S>=3).map(({id:y})=>y);if(w.length>0){let y=await Hi({paths:e.paths,name:e.name,reason:`Native Runtime checks reached the retry limit after repeated interruptions: ${w.join(", ")}`,failureBudget:{maxVerifyFailures:e.maxVerifyFailures},preserveLocalChecks:!0});return{state:y,checks:h.checks,requestChecks:null,verifierDispatch:null,continuation:K(y)}}}return{state:h.state,checks:h.checks,...g.length>0?{continuationRetryCheckIds:g}:{},requestChecks:null,verifierDispatch:null,continuation:K(h.state,void 0,{retryCheckIds:g.length>0?g:void 0})}}if(t.kind==="dispatch-verifier"){if(a&&t.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let m=await $(e.paths,e.name);if(m.builder_handoff!==null&&m.builder_handoff.identity_provider!==Ne){let b=await Hi({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:b,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(b)}}Vn(m);let h=await zo({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}}),g=h.checks,v=g.filter(({status:b})=>b==="interrupted").map(({id:b})=>b);if(v.length>0){let b=t.checks.filter(({id:N,repeatable:x})=>v.includes(N)&&!x).map(({id:N})=>N);if(b.length>0)throw new Error(`Native non-repeatable checks were interrupted and require a new Builder candidate: ${b.join(", ")}`);let S=await $(e.paths,e.name);return{state:S,checks:g,runtimeCheckExecution:{disposition:h.disposition},continuationRetryCheckIds:v,requestChecks:null,verifierDispatch:null,continuation:K(S,void 0,{retryCheckIds:v})}}let w=ck("verifier"),y=await Nh({paths:e.paths,name:e.name,checks:g,verifierExecutionId:w,...a&&n?{projectRoot:n.integration.worktree}:{}});return{state:y,checks:g,runtimeCheckExecution:{disposition:h.disposition},requestChecks:null,verifierDispatch:uk({paths:e.paths,state:y,checks:g,verifierExecutionRef:w,supervisor:a?n:null}),continuation:K(y,void 0,{verifierExecutionRef:w})}}if(t.kind==="verifier-started"){let m=await bh({paths:e.paths,name:e.name,candidateId:t.candidateId,verifierExecutionRef:t.verifierExecutionRef});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(m)}}if(t.kind==="verifier-execution-error"){let m=await $(e.paths,e.name);Vn(m),await Oh({paths:e.paths,state:m});let h=await Sh({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:h,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(h)}}if(t.kind==="verifier-unavailable"){let m=await Eh({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:m,checks:m.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:K(m)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await $(e.paths,e.name),c=Vn(s),l=await Oh({paths:e.paths,state:s});if(t.candidateId!==c.candidate_id||t.verifierExecutionRef!==l)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");let u=Cf(),f=u.captureExecutionIdentity({identityProvider:Ne,executionRef:l}),d=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let m=await O(e.paths,e.name);if(!m)throw new Error("Native Supervisor state disappeared before final verification");d=Ii(m)}let p=await kh({paths:e.paths,name:e.name,envelope:u.envelopeVerifierResponse({candidateId:c.candidate_id,identity:f,payload:t.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...a&&n?{projectRoot:n.integration.worktree}:{}});if(a&&p.response.kind==="final-result"){if(p.state.verification_result==="pass"&&(p.checks.length===0||p.checks.some(({status:g})=>g!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let m=d??await O(e.paths,e.name);if(!m)throw new Error("Native Supervisor state disappeared during verification");let h=Ti(m,p.state);return await q(e.paths,h),{...p,supervisorState:h,verifierDispatch:null,continuation:K(p.state)}}return{...p,verifierDispatch:p.requestChecks===null?null:uk({paths:e.paths,state:p.state,checks:p.checks,verifierExecutionRef:await Oh({paths:e.paths,state:p.state}),supervisor:a?n:null}),continuation:K(p.state,void 0,{verifierExecutionRef:l})}}mi();cn();Ta();import Xo from"path";import{realpathSync as m0}from"fs";function pk(e,t){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},i=r(e),n=r(i.entry),a=r(i.state??n.state??i),o=r(i.preparation??i.workspace??n.workspace),s=r(i.continuation??n.continuation),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var wr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function hk(e){return e?e.command?`${wr.next} ${e.command}`:e.ask_user?`${wr.next} ${e.ask_user}`:null:null}function mk(e,t){let r=[e.summary],i=hk(e.next);return i&&r.push(i),e.user_message&&r.push("",wr.relay,e.user_message),t!==void 0&&r.push("",wr.details,JSON.stringify(t,null,2)),`${r.join(`
374
+ `)}async function Em(e){let t=le(e.paths,e.state.name),r=e.state.document_constraints_version,i=r===2||r===3,n=r===3,a=[...(await Nm(t,e.state.brief,{strict:!0,compact:i,structure:n})).findings],o="";try{o=(await Z({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1})).text}catch{}let s=e.specChanges??e.state.spec_changes,c=s.filter(({operation:d})=>d!=="remove"),l=e.state.spec_changes.filter(({operation:d})=>d!=="remove"),u=new Set(c.map(({capability:d})=>d));if(e.specChanges!==void 0)for(let d of l)u.has(d.capability)||a.push({code:"spec-document-missing",message:`Previously declared target Spec is missing: specs/${d.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${d.capability}/spec.md`});let p=s.length>0&&s.every(({operation:d})=>d==="remove");c.length===0&&l.length===0&&!p&&!tD(o)&&a.push({code:"spec-exemption-missing",message:"This change declares no target Spec. Add a complete target Spec, or record a concrete reason such as “No product behavior change: documentation-only wording.” in brief.md.",path:e.state.brief});for(let d of c){let f=`specs/${d.capability}/spec.md`;if(d.source!==f){a.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${f}.`,path:d.source??f});continue}try{let h=(await Z({root:t,ref:f,maxBytes:null,includeHash:!1})).text;a.push(...cS(h,f).findings)}catch(h){a.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${h.message}. Restore the complete file at ${f}.`,path:f})}}return{valid:a.length===0,findings:a}}async function Hu(e){let t=await Em(e);if(!t.valid)throw new la(hS(t.findings,{change:e.state.name,phase:e.state.phase}),t.findings,e.state.name)}function Mt(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale: the change moved on since the referenced response (current phase ${e.state.phase}, next action ${e.state.loop.next_action}, state version ${e.state.state_version}). Run comet native status ${e.state.name} --json and execute its commandAlternatives with --expected-state-version ${e.state.state_version} --expected-action ${e.state.loop.next_action}.`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}async function Du(e){let t=le(e.paths,e.state.name),r=nn.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await ju.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!em.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=nn.join(t,...s.split("/")),l=await ju.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=nn.join(e.paths.specsDir,o.name,"spec.md"),p="create",d=null;try{let v=await ju.lstat(u);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);p="modify",d=Sr((await Z({root:e.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(v){if(v.code!=="ENOENT")throw v}let f=`specs/${o.name}/${fb}`,h=nn.join(t,...f.split("/")),m={};try{let v=await ju.lstat(h);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${f}`);let g=await Z({root:t,ref:f,maxBytes:null,includeHash:!1}),w=Do(g.text);if(w.capability!==o.name)throw new Error(`Native delta capability ${w.capability} does not match directory ${o.name}`);let N=d??Sr(""),y=e.state.spec_changes.find(E=>E.capability===o.name);if(y?.delta_source!==void 0){if(y.base_hash!==w.base_hash)throw new Error(`Native delta base changed for ${o.name}; explicit conversion is required`)}else if(w.base_hash!==N)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);m={delta_source:f,base_hash:w.base_hash}}catch(v){if(v.code!=="ENOENT")throw v}a.push({capability:o.name,operation:p,source:s,...m})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Bu(e){let t=le(e.paths,e.state.name),r=await Z({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(bm(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let o of e.specChanges){if(o.source===null){n.push({...o,contentHash:null});continue}let s=await Z({root:t,ref:o.source,maxBytes:null,includeHash:!1}),c=s.text,l=null;if(o.delta_source){let u=await Z({root:t,ref:o.delta_source,maxBytes:null,includeHash:!1}),p=Do(u.text);c=gb(s.text,p);let d="";try{d=(await Z({root:e.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(f){if(f.code!=="ENOENT")throw f}if(Sr(d)===p.base_hash){let f=yb({baselineMarkdown:d,delta:p,allowAlreadyApplied:!0});if(Sr(s.text)!==f.result_hash)throw new Error(`Native full target Spec does not match delta result for ${o.capability}; update the complete target before confirming Shape`)}l=$("comet.native.shape-artifact-content.v1",Ou(u.text))}i.push({capability:o.capability,source:s.ref,markdown:c}),n.push({...o,contentHash:$("comet.native.shape-artifact-content.v1",Ou(s.text,e.state.document_constraints_version!==void 0&&e.state.document_constraints_version!==1)),...l===null?{}:{deltaContentHash:l}})}let a=null;try{let o=await Z({root:t,ref:fS,maxBytes:65536,includeHash:!1}),s=pS(o.text);if(s.workflow!=="native")throw new Error("Native capability association must use the native workflow");if(!e.specChanges.some(({capability:u})=>u===s.capability))throw new Error(`Native capability association ${s.capability} is not declared by this change`);let l=nn.relative(e.paths.projectRoot,nn.join(e.paths.specsDir,s.capability,"spec.md")).replaceAll(nn.sep,"/");if(s.current_spec!==l)throw new Error(`Native capability association points to ${s.current_spec}, expected ${l}`);a=$("comet.native.shape-artifact-content.v1",Ou(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:Ll({briefMarkdown:r.text,specs:i,resolveBriefReferences:e.state.document_constraints_version!==void 0&&e.state.document_constraints_version!==1}),formalHash:$("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:$("comet.native.shape-artifact-content.v1",Ou(r.text,e.state.document_constraints_version!==void 0&&e.state.document_constraints_version!==1))},specs:n,association:{source:fS,contentHash:a}})}}function Ss(e){return $("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function xm(e){return A(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"prepare-shape-confirmation"}),t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");let r=e.enforceDocumentConstraints===!0?{...t,document_constraints_version:3}:t,i=await Du({paths:e.paths,state:t});e.enforceDocumentConstraints===!0&&await Hu({paths:e.paths,state:r,specChanges:i});let n=await Bu({paths:e.paths,state:r,specChanges:i}),{acceptance:a}=n,o=await Je({changeDir:le(e.paths,t.name),acceptanceIds:a.map(({id:f})=>f),validation:bt({...t,acceptance:a})}),s=t;if(o&&t.workspace.change_branch===null){await Nl(e.paths,t.name);let f=Ru(t.workspace,e.paths.projectRoot);if(f===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");s=ke({...t,workspace:f},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${f.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let c=await ls(le(e.paths,t.name))||o?.contract.schema==="comet.native.children.v2"&&o.contract.children.length>=2;if(c&&!o)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");let l=c?e.coordinationMode??t.coordination_mode:void 0;if(!c&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let u={...s,...r.document_constraints_version===void 0?{}:{document_constraints_version:r.document_constraints_version},spec_changes:i,shape_confirmation_hash:Ss({formalHash:n.formalHash,childrenHash:o?.hash??null,coordinationMode:l})};delete u.children_contract_hash,delete u.coordination_mode,c&&(u.coordination_mode=l);let p=Sk({state:u,acceptance:a.map(f=>({...f}))});o&&(p.children_contract_hash=ta({acceptance:p.acceptance,children:o.contract}));let d=await fe({paths:e.paths,previous:t,next:p});return await M(L(e.paths,t.name),ae({portableState:d,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),d})}async function Es(e){if(e.state.document_constraints_version!==void 0){let l=await Em(e);if(!l.valid){let u=l.findings[0];return{drifted:!0,reason:u?`Native formal documents are invalid (${u.code}${u.path?`: ${u.path}`:""})`:"Native formal documents are invalid"}}}let t=await Du(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,u)=>{let p=e.state.spec_changes[u];return p!==void 0&&l.capability===p.capability&&l.source===p.source&&l.delta_source===p.delta_source&&l.base_hash===p.base_hash&&(l.operation===p.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await Bu({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:u})=>({source:l,text:u}));if(!Wb(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Je({changeDir:le(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:bt({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&Ss({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?ta({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Ze(e){let t=await Es(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Rs({paths:e.paths,state:e.state,reason:r,keepFailureBudget:!0}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function xs(e){return A(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:Rs({paths:e.paths,state:t,reason:e.reason,...e.keepFailureBudget?{keepFailureBudget:!0}:{}})})}async function Rs(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...ke(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:e.keepFailureBudget?t.loop.failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await fe({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}function Mu(e,t){let r=O.relative(O.resolve(e),O.resolve(t));if(O.isAbsolute(r)||r===".."||r.startsWith(`..${O.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(O.sep).join("/");return To(e,i),i}function rD(e){return e.split("\0").some(t=>t.startsWith("160000 "))}function Lu(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return qn({id:e.id,name:e.name,executable:r,argv:i,cwdRef:Mu(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function yS(e,t=e.workspace.projectRoot){return e.checks.map(r=>{let[i,...n]=r.argv;if(!i)throw new Error(`Native local check ${r.id} has no executable`);return{id:r.id,name:r.name,executable:i,argv:n,cwdRef:Mu(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function bS(e,t,r,i,n,a){return e.candidateId!==i.builder_handoff?.candidate_id||e.inputFingerprint!==n||O.resolve(e.workspace.projectRoot)!==O.resolve(r)||O.resolve(e.workspace.worktreeRoot)!==O.resolve(r)||e.workspace.branch!==a||e.workspace.machineId!==Tr.hostname()||e.checks.length!==t.length?!1:e.checks.every((o,s)=>Lu(o,r)===qn(t[s]))}function Cm(e,t,r){return e.checks.length===t.length&&e.checks.every((i,n)=>Lu(i,r)===qn(t[n]))}async function Fu(e){let t=e.execution;if(t===null||t.status!=="running")return"not-running";if(t.ownerPid===void 0)return"unknown";let r=await Ln(t.ownerPid,t.ownerIdentity);if(r==="alive")return"running";let i=r==="unknown";for(let n of e.checks){if(n.status!=="running")continue;let a=n.activeProcess;if(!a||a.status==="starting"){i=!0;continue}let o=await Ln(a.pid,a.identity);if(o==="alive")return"running";o==="unknown"&&(i=!0)}return i?"unknown":"orphaned"}function mS(e){return{...e,execution:e.execution===null?null:{...e.execution,status:"interrupted"},checks:e.checks.map(t=>t.status==="planned"||t.status==="running"?{...t,status:"interrupted",activeProcess:null}:t)}}function qu(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:To(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`,activeProcess:null}}function iD(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return _m(e,t,r,i)}function _m(e,t,r,i){return{...qu(t,r,i),executionCount:e.executionCount}}function NS(e){return gS("sha256").update(e).digest("hex")}async function _s(e){let t=await ur.lstat(e);if(!t.isFile())throw new Error("Native check input must be a regular file");let r=gS("sha256"),i=await ur.open(e,"r"),n=0;try{let o=Buffer.allocUnsafe(nD);for(;;){let{bytesRead:s}=await i.read(o,0,o.length,null);if(s===0)break;n+=s,r.update(o.subarray(0,s).toString("base64"))}}finally{await i.close()}let a=await ur.lstat(e);if(a.size!==t.size||a.mtimeMs!==t.mtimeMs)throw new Error("Native check input changed while reading");return{digest:r.digest("hex"),size:n}}var kS=2e4,SS=1024*1024*1024,nD=65535,ES=["build","dist","gen","generated","out","target",".next",".nuxt",".output",".svelte-kit"],aD=new Set([".agents",".cache",".claude",".codex",".comet",".git",".idea",".next",".nuxt",".output",".parcel-cache",".svelte-kit",".tmp",".turbo",".vscode",".worktrees","coverage","logs","node_modules","temp","tmp"]),Rm=[":(exclude).comet/runtime/**",":(exclude).comet/current-change.json"],xS=new Set(["comet-state.yaml","children.yaml","verification.md"]);function RS(e,t){if(!t)return[...Rm];let r=O.relative(e,t).replaceAll("\\","/");if(O.isAbsolute(r)||r===".."||r.startsWith("../"))return[...Rm];let i=r===""?"":`${r}/`;return[...Rm,...["changes","archive"].flatMap(n=>[...xS].map(a=>`:(exclude)${i}comet/${n}/**/${a}`))]}function Am(e,t,r){let i=e.replaceAll("\\","/").replace(/^\.\//u,"");if(i===".comet/current-change.json"||i.startsWith(".comet/runtime/"))return!0;if(!t||!r||!xS.has(O.basename(i)))return!1;let n=O.resolve(t,...i.split("/")),a=O.relative(O.resolve(r),n);if(O.isAbsolute(a)||a===".."||a.startsWith(`..${O.sep}`))return!1;let[,o]=a.split(O.sep);return a.startsWith(`comet${O.sep}`)&&(o==="changes"||o==="archive")}function da(){return{complete:!1,files:[]}}function oD(e){let t=e==="."?"":`${e}/`;return ES.flatMap(r=>[`:(glob)${t}${r}/**`,`:(glob)${t}**/${r}/**`])}function CS(e){return/(?:^|\/)(?:\.env(?:\..*)?|[^/]+\.(?:key|pem|p12|pfx))$/iu.test(e)}async function PS(e,t,r,i=new Set){let n=[...new Set(t.map(({cwdRef:c})=>c))];if(n.length===0)return{complete:!0,files:[]};let a;try{a=[...new Set(I(e,["ls-files","--others","--ignored","--exclude-standard","-z","--",...n.flatMap(oD)]).split("\0").filter(Boolean).map(c=>c.replaceAll("\\","/")))].sort()}catch{return da()}if(a.length>kS)return da();let o=[],s=0;for(let c of a){if(i.has(c)||Am(c,e,r))continue;let l=O.resolve(e,...c.split("/"));if(!Ee(e,l)||CS(c))return da();try{let u=await ur.lstat(l);if(!u.isFile()||s+u.size>SS)return da();let{digest:p,size:d}=await _s(l);s+=d,o.push({path:c,digest:p,size:d})}catch{return da()}}return{complete:!0,files:o}}async function sD(e,t,r,i=new Set){let n=[...new Set(t.map(({cwdRef:l})=>l))],a=new Map,o=0,s=l=>ES.includes(l),c=async(l,u,p)=>{let d;try{d=await ur.readdir(l,{withFileTypes:!0})}catch{return!1}d.sort((f,h)=>f.name.localeCompare(h.name,"en"));for(let f of d){let h=u?`${u}/${f.name}`:f.name;if(i.has(h)||Am(h,e,r)||f.isDirectory()&&aD.has(f.name))continue;let m=O.join(l,f.name);if(f.isDirectory()){if(!await c(m,h,p||s(f.name)))return!1;continue}if(p){if(CS(h)||!f.isFile())return!1;try{let v=await ur.lstat(m);if(o+v.size>SS)return!1;let{digest:g,size:w}=await _s(m);if(o+=w,a.set(h,{path:h,digest:g,size:w}),a.size>kS)return!1}catch{return!1}}}return!0};for(let l of n){let u=To(e,l);if(!await c(u,l==="."?"":l,s(O.basename(u))))return da()}return{complete:!0,files:[...a.values()].sort((l,u)=>l.path.localeCompare(u.path,"en"))}}function Im(e,t){return $("comet.native.local-check-evidence.v1",{id:e.id,name:e.name,status:e.status,repeatable:e.repeatable,timeoutMs:e.timeoutMs,argv:e.argv,cwd:O.resolve(e.cwd),exitCode:e.exitCode,startedAt:e.startedAt,completedAt:e.completedAt,log:e.log,logDigest:NS(t)})}async function _S(e){let t=await zh(e.projectRoot),r=[...RS(e.projectRoot,e.managedArtifactRoot),...[...t].map(a=>`:(exclude,literal)${a}`)],i={complete:!0,capture:"git",head:null,branch:null,status:null,diff:null,stagedDiff:null,submodules:null,untracked:[],ignored:{complete:!0,files:[]},physical:{complete:!0,files:[]},reuseNonce:null},n=!1;try{i.head=I(e.projectRoot,["rev-parse","HEAD"]),n=!0,i.branch=I(e.projectRoot,["branch","--show-current"]),i.status=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...r]);let a=I(e.projectRoot,["diff","--name-only","-z","HEAD","--",...r]).split("\0").filter(Boolean).sort();i.diff=await Zh(a,4,async c=>{let l=O.resolve(e.projectRoot,...c.split("/"));try{let{digest:u}=await _s(l);return{path:c,digest:u}}catch{return{path:c,digest:null}}}),i.diff.some(({digest:c})=>c===null)&&(i.complete=!1);let o=I(e.projectRoot,["ls-files","--stage","-z","--",...r]);i.stagedDiff=NS(o),i.submodules=rD(o)?I(e.projectRoot,["submodule","status","--recursive"]):"";let s=I(e.projectRoot,["ls-files","--others","--exclude-standard","-z","--",...r]).split("\0").filter(Boolean).sort();i.untracked=await Zh(s,4,async c=>{let l=O.resolve(e.projectRoot,...c.split("/"));try{let{digest:u,size:p}=await _s(l);return{path:c,digest:u,size:p}}catch{return{path:c,digest:null,size:null}}}),i.untracked.some(({digest:c})=>c===null)&&(i.complete=!1),i.ignored=await PS(e.projectRoot,e.plans,e.managedArtifactRoot,t),i.ignored.complete||(i.complete=!1)}catch{n?i.complete=!1:(i.capture="physical-tree",i.physical=await sD(e.projectRoot,e.plans,e.managedArtifactRoot,t),i.complete=i.physical.complete)}return $("comet.native.check-input.v1",{candidateId:e.state.builder_handoff?.candidate_id??null,shapeConfirmationHash:e.state.shape_confirmation_hash??null,acceptance:e.state.acceptance.map(({id:a,source:o,text:s})=>({id:a,source:o,text:s})),git:i,projectRoot:O.resolve(e.projectRoot),machineId:Tr.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,path:process.env.PATH??null,pathext:process.env.PATHEXT??null,boundEnvironment:Object.entries(process.env).filter(([a])=>AS.has(a.toUpperCase())).map(([a,o])=>[a,o??null]).sort(([a],[o])=>a.localeCompare(o))})}var AS=new Set(["PATH","PATHEXT","NODE_OPTIONS","NODE_ENV","NODE_PATH","LANG","LC_ALL","HOME","USERPROFILE","SYSTEMROOT","COMSPEC","SHELL","TMPDIR","TEMP","TMP","HTTP_PROXY","HTTPS_PROXY","NO_PROXY"]);function cD(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function lD(){return Object.entries(process.env).filter(([e])=>AS.has(e.toUpperCase())).map(([e,t])=>[e,t??null]).sort(([e],[t])=>e.localeCompare(t))}async function IS(e){try{let t=await zh(e.projectRoot),r=[...RS(e.projectRoot,e.managedArtifactRoot),...[...t].map(c=>`:(exclude,literal)${c}`)],i=I(e.projectRoot,["rev-parse","HEAD"]),n=I(e.projectRoot,["branch","--show-current"]),a=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...r]),o=I(e.projectRoot,["ls-files","--stage","-z","--",...r]);if(i===null||a===null)return null;let s=[];for(let c of Za(e.projectRoot).filter(l=>!t.has(l)&&!Am(l,e.projectRoot,e.managedArtifactRoot))){let l=O.resolve(e.projectRoot,...c.split("/")),u=null;try{u=(await _s(l)).digest}catch{return null}s.push({path:c,digest:u})}return s.sort((c,l)=>c.path.localeCompare(l.path,"en")),{runnerInputs:t,binding:{candidateId:e.candidateId,head:i,branch:n,status:a,staged:o,workingTree:s,projectRoot:O.resolve(e.projectRoot),machineId:Tr.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,boundEnvironment:lD()}}}catch{return null}}async function Pm(e,t){if(t===null)return null;try{let r=await PS(e.projectRoot,e.plans??[],e.managedArtifactRoot,t.runnerInputs);return r.complete?$("comet.native.check-input-gate.v1",{...t.binding,ignored:r}):null}catch{return null}}async function vS(e){return Pm(e,await IS(e))}async function TS(e){let t=await IS(e);return{branch:t===null?ge(e.projectRoot):t.binding.branch||null,gate:await Pm(e,t),candidateGate:await Pm({...e,plans:[]},t)}}function vi(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);if(r.status==="passed"&&(r.evidence!=="runtime"||!r.evidenceDigest))throw new Error(`Native Runtime check ${r.id} has no Runtime execution evidence`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:J(i),argv_display:$o(r.argv.slice(1)).map(n=>J(n)),argv_truncated:!1,cwd_ref:Mu(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:cD(r)}})}function uD(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function gi(e){if(e.local===null||e.local.change!==e.state.name)return ae({portableState:e.state,projectRoot:e.projectRoot,branch:ge(e.projectRoot)});let t=e.local.execution?.operationId??wS();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function $r(e){try{let t=await Ce(L(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}async function Tm(e){let t=await $r({paths:e.paths,state:e.state}),r=Ik({state:e.state,summary:e.summary}),i=await fe({paths:e.paths,previous:e.state,next:r});return await M(L(e.paths,e.state.name),gi({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}async function $S(e,t){for(let r of e.checks)if(r.status==="passed"){if(r.evidence!=="runtime")return!1;try{let i=await G(t,O.resolve(t,...r.log.split(/[\\/]/u)));if(!(await ur.stat(i)).isFile())return!1;let n=await ur.readFile(i,"utf8");if(!r.evidenceDigest||r.evidenceDigest!==Im(r,n))return!1}catch{return!1}}return!0}async function jS(e){let{local:t,previous:r,next:i,plans:n,paths:a}=e;if(!t||!t.checks.length||t.checks.some(({status:s})=>s!=="passed")||t.basedOnStateVersion!==r.state_version||t.candidateId!==r.builder_handoff?.candidate_id||t.workspace.machineId!==Tr.hostname()||t.inputFingerprint==null||t.inputFingerprintGate==null||t.execution?.stage==="checking"&&t.execution.status==="running"||r.shape_confirmation_hash!==i.shape_confirmation_hash||JSON.stringify(r.acceptance.map(({id:s,source:c,text:l})=>({id:s,source:c,text:l})))!==JSON.stringify(i.acceptance.map(({id:s,source:c,text:l})=>({id:s,source:c,text:l}))))return null;let o=t.workspace.worktreeRoot;if(O.resolve(t.workspace.projectRoot)!==O.resolve(e.projectRoot??a.projectRoot)||O.resolve(o)!==O.resolve(e.projectRoot??a.projectRoot))return null;try{if(t.workspace.branch!==ge(o)||!Cm(t,n,o)||!await $S(t,me(a,i.name)))return null;let s={projectRoot:o,candidateId:t.candidateId??null,plans:n,managedArtifactRoot:a.artifactRoot},c=await vS(s);if(c===null||c!==t.inputFingerprintGate)return null;let l=await _S({state:i,projectRoot:o,plans:n,managedArtifactRoot:a.artifactRoot}),u=await TS({...s,candidateId:i.builder_handoff.candidate_id});return u.gate===null||u.candidateGate===null||await vS(s)!==c?null:{...gi({local:t,state:i,projectRoot:a.projectRoot}),candidateId:i.builder_handoff.candidate_id,inputFingerprint:l,inputFingerprintGate:u.gate,candidateInputFingerprintGate:u.candidateGate}}catch{return null}}async function dD(e){return A(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Ze({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let{gate:r,candidateGate:i,branch:n}=await TS({projectRoot:e.projectRoot,candidateId:t.builder_handoff?.candidate_id??null,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),a=n,o=L(e.paths,t.name),s=(await Eu({file:o,portableState:t,projectRoot:e.projectRoot,branch:a,containedRoot:e.paths.runtimeDir})).state;a!==null&&s.workspace.branch===`heads/${a}`&&(a=ge(e.projectRoot));let c=r===null,u=r!==null&&s.inputFingerprint!==null&&s.inputFingerprintGate===r&&s.candidateInputFingerprintGate===i&&s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.machineId===Tr.hostname()?s.inputFingerprint:await _S({state:t,projectRoot:e.projectRoot,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),p=me(e.paths,t.name),d=await $S(s,p),f=s.checks.every(S=>S.status==="passed"),h=e.retryCheckIds===void 0?null:new Set(e.retryCheckIds),m=s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.branch===a&&s.workspace.machineId===Tr.hostname()&&s.inputFingerprint===u,v=i!==null&&s.candidateInputFingerprintGate===i&&s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.branch===a&&s.workspace.machineId===Tr.hostname(),g=v&&s.inputFingerprint!==null&&s.inputFingerprint!==u,w=bS(s,e.plans,e.projectRoot,t,u,a)||v&&Cm(s,e.plans,e.projectRoot),N=s.candidateId===t.builder_handoff?.candidate_id&&O.resolve(s.workspace.projectRoot)===O.resolve(e.projectRoot)&&O.resolve(s.workspace.worktreeRoot)===O.resolve(e.projectRoot)&&s.workspace.branch===a&&s.workspace.machineId===Tr.hostname(),y=m&&f&&!d;if(h&&h.size===0)throw new Error("Native check retry list must contain at least one ID");if(!m&&s.execution?.stage==="checking"&&s.execution.actor==="runtime"&&s.execution.status==="running"){let S=await Fu(s);if(S!=="orphaned")throw new Error(S==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before changing its binding":"Native check plan is already in progress on another workspace binding");s=mS(s),await M(o,s,{containedRoot:e.paths.runtimeDir})}if(!m&&N&&s.inputFingerprint!==null&&(s.execution!==null||s.checks.length>0)){let S=s.inputFingerprint!==u;if(!(c&&!S||g)){let C=pi({state:t,reason:"Native check input changed after the candidate was built; a new Builder candidate is required before checks can run again."}),P=await fe({paths:e.paths,previous:t,next:C});throw await M(o,ae({portableState:P,projectRoot:e.paths.projectRoot,branch:a}),{containedRoot:e.paths.runtimeDir}),new Error("Native check input changed after the candidate was built; the change returned to Build for a new candidate")}}if(!m&&!v){let S=ae({portableState:t,projectRoot:e.projectRoot,branch:a});await M(o,S,{containedRoot:e.paths.runtimeDir}),s=S}let E=Cm(s,e.plans,e.projectRoot);if(s.execution?.stage==="checking"&&s.execution.actor==="runtime"&&E&&w){let S=s.execution;if(S.status==="running"){let P=await Fu(s);if(P!=="orphaned")throw new Error(P==="unknown"?"Native check plan owner could not be proven to have exited; inspect the Runtime overlay before retrying":"Native check plan is already in progress");s=mS(s),await M(o,s,{containedRoot:e.paths.runtimeDir}),S=s.execution}let C=s.checks.filter(P=>P.status==="interrupted");if(C.length===0&&S.status==="completed"&&f&&!y&&!g){let P=new Map(e.plans.map(({id:_,name:j})=>[_,j]));return{kind:"reuse",state:t,checks:vi({local:s,projectRoot:e.projectRoot,supplied:[],requestedNames:P})}}if(C.length===0&&S.status==="completed"&&!f&&!y&&!g)throw new Error(`Native check plan contains a failed check (${s.checks.filter(({status:P})=>P==="failed").map(({id:P})=>P).join(", ")}); submit a new Builder candidate`);if(C.length>0&&C.some(P=>!P.repeatable)&&!y){let P=pi({state:t,reason:`A non-repeatable Runtime check was interrupted (${C.filter(j=>!j.repeatable).map(({id:j})=>j).join(", ")}); a new Builder candidate is required before it can run again.`}),_=await fe({paths:e.paths,previous:t,next:P});throw await M(L(e.paths,t.name),ae({portableState:_,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${C.find(j=>!j.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}if(C.length>0&&h===null&&!y&&!g){let P=new Map(e.plans.map(({id:_,name:j})=>[_,j]));return{kind:"reuse",state:t,checks:vi({local:s,projectRoot:e.projectRoot,supplied:[],requestedNames:P})}}if(h){let P=[...h].filter(j=>!C.some(ue=>ue.id===j));if(P.length>0)throw new Error(`Native check retry IDs must refer to interrupted checks: ${P.join(", ")}`);let _=C.filter(j=>h.has(j.id)&&j.executionCount>=3);if(_.length>0)throw new Error(`Native check retry limit (3) reached: ${_.map(({id:j})=>j).join(", ")}`)}}if(s.execution!==null&&s.checks.length>0){if(!(s.execution.stage==="checking"&&s.execution.actor==="runtime"&&s.checks.some(C=>C.status==="interrupted")&&E)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan")}else if((s.execution!==null||s.checks.length>0)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan");let b=wS(),x=await ct(process.pid),k={...s,candidateId:t.builder_handoff?.candidate_id??null,inputFingerprint:u,inputFingerprintGate:r,candidateInputFingerprintGate:i,workspace:{...s.workspace,projectRoot:O.resolve(e.projectRoot),worktreeRoot:O.resolve(e.projectRoot),branch:ge(e.projectRoot),machineId:Tr.hostname()},execution:{operationId:b,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0,ownerPid:process.pid,...x?{ownerIdentity:x}:{}},checks:e.plans.map(S=>{let C=s.checks.find(P=>P.id===S.id);return g&&C?qu(S,b,e.projectRoot):y&&C?_m(C,S,b,e.projectRoot):C?.status==="interrupted"&&(h===null||h.has(C.id))?iD(C,S,b,e.projectRoot):C?{...C,operationId:b,activeProcess:null}:qu(S,b,e.projectRoot)})};return await M(o,k,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:k,plans:e.plans.filter(S=>{let C=s.checks.find(P=>P.id===S.id);return y||g||C===void 0||C.status==="interrupted"&&(h===null||h.has(C.id))})}})}async function Cs(e){return A(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await H(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=L(e.paths,t.name),i=await Ce(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await M(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function As(e){let t=e.projectRoot??e.paths.projectRoot;lt(t,e.plans);let r=[],i=new Set;for(let c of e.plans){jo(t,c);let l=qn(c);i.has(l)||(i.add(l),r.push(c))}let n=await dD({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return{...n,disposition:"reused"};let a=n.local.execution.operationId,o=me(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await Cs({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(f=>f.id===c.id?{...f,status:"running",executionCount:f.executionCount+1,startedAt:l,activeProcess:{status:"starting"}}:f)})});let u=await Bi({projectRoot:t,runtimeDir:o,operationId:a,plan:c,onSpawn:async({pid:d})=>{let f=await ct(d);await Cs({paths:e.paths,state:n.state,operationId:a,update:h=>({...h,checks:h.checks.map(m=>m.id===c.id?{...m,activeProcess:{status:"running",pid:d,...f?{identity:f}:{}}}:m)})})}}),p=await ur.readFile(O.resolve(o,...u.logRef.split("/")),"utf8");await Cs({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(f=>{if(f.id!==c.id)return f;let h={...f,status:u.status,exitCode:u.exitCode,startedAt:u.startedAt,completedAt:u.completedAt,log:u.logRef,activeProcess:null,evidence:"runtime"};return{...h,evidenceDigest:Im(h,p)}})})})}await Cs({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await Cs({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted",activeProcess:null}:u)})})}catch{}throw c}let s=await Ce(L(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:vi({local:s,projectRoot:t,supplied:[]}),disposition:"executed"}}async function $m(e){if(e.checkIds.length===0)throw new Error("Native check retry list must contain at least one ID");let t=e.projectRoot??e.paths.projectRoot,r=await H(e.paths,e.name);if(r.phase!=="verify"||r.status!=="active"||r.loop.stage!=="verify-ready"||r.builder_handoff===null)throw new Error("Native check retry requires an active Verify-ready candidate");let i=await Ce(L(e.paths,e.name));if(i===null||i.change!==r.name||i.basedOnStateVersion!==r.state_version||i.execution===null||i.execution.stage!=="checking"||i.execution.actor!=="runtime")throw new Error("Native check retry has no current Runtime check execution");let n=new Set(e.checkIds);if(n.size!==e.checkIds.length)throw new Error("Native check retry list contains duplicate IDs");let a=i.checks.filter(c=>n.has(c.id)),o=e.checkIds.filter(c=>!a.some(l=>l.id===c));if(o.length>0)throw new Error(`Native check retry IDs are unknown: ${o.join(", ")}`);for(let c of a){if(c.status!=="interrupted")throw new Error(`Native check ${c.id} is not interrupted and cannot be retried`);if(!c.repeatable)throw new Error(`Native check ${c.id} is not repeatable and cannot be retried`);if(c.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${c.id}`)}let s=i.checks.map(c=>{let[l,...u]=c.argv;if(!l)throw new Error(`Native local check ${c.id} has no executable`);return{id:c.id,name:c.name,executable:l,argv:u,cwdRef:Mu(t,c.cwd),timeoutMs:c.timeoutMs,repeatable:c.repeatable}});return As({paths:e.paths,name:e.name,plans:s,projectRoot:t,retryCheckIds:e.checkIds})}async function OS(e){let t=L(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=Jh)throw new Error(`Native Verifier request-checks exceeded ${Jh} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let f of r.checks){let h=Lu(f,e.projectRoot);n.set(h,f),f.status==="passed"&&i.set(h,f),a.set(f.id,h)}let o=new Map,s=new Map;for(let f of e.response.checks){let h=uD(f);jo(e.projectRoot,h);let m=qn(h),v=s.get(h.id);if(v!==void 0&&v!==m)throw new Error(`Native Verifier check ID ${h.id} refers to conflicting commands`);let g=a.get(h.id);if(g!==void 0&&g!==m)throw new Error(`Native Verifier check ID ${h.id} conflicts with a Runtime check`);s.set(h.id,m);let w=n.get(m);if(w&&w.status!=="passed"&&!w.repeatable)throw new Error(`Native check ${w.id} did not pass and is not repeatable; user resolution is required`);if(w&&w.status!=="passed"&&w.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${w.id}`);o.has(m)||o.set(m,h)}lt(e.projectRoot,[...o.values()]);let c=[...o.entries()],l=c.filter(([f])=>!i.has(f));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let u=r.execution.requestCheckRounds+1,p=new Map(c.map(([,f])=>[f.id,f.name])),d={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:u},checks:[...r.checks.map(f=>{let h=Lu(f,e.projectRoot),m=o.get(h);return m&&f.status!=="passed"?_m(f,m,r.execution.operationId,e.projectRoot):f}),...l.filter(([f])=>!n.has(f)).map(([,f])=>qu(f,r.execution.operationId,e.projectRoot))]};return await M(t,d,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:d,verifierExecutionRef:e.envelope.verifierExecutionRef,round:u,novelPlans:l.map(([,f])=>f),requestedNames:p,reusedCheckIds:c.filter(([f])=>i.has(f)).map(([,f])=>f.id),suppliedChecks:e.suppliedChecks}}async function Ps(e){return A(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await H(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=L(e.paths,t.name),i=await Ce(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await M(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function HS(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await Ps({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>c.id===r.id?{...c,status:"running",executionCount:c.executionCount+1,startedAt:i,activeProcess:{status:"starting"}}:c)})});let n=me(e.paths,e.reservation.state.name),a=await Bi({projectRoot:e.projectRoot,runtimeDir:n,operationId:e.reservation.local.execution.operationId,plan:r,onSpawn:async({pid:s})=>{let c=await ct(s);await Ps({paths:e.paths,reservation:e.reservation,update:l=>({...l,checks:l.checks.map(u=>u.id===r.id?{...u,activeProcess:{status:"running",pid:s,...c?{identity:c}:{}}}:u)})})}}),o=await ur.readFile(await G(n,O.resolve(n,...a.logRef.split(/[\\/]/u))),"utf8");t=await Ps({paths:e.paths,reservation:e.reservation,update:s=>({...s,checks:s.checks.map(c=>{if(c.id!==r.id)return c;let l={...c,status:a.status,exitCode:a.exitCode,startedAt:a.startedAt,completedAt:a.completedAt,log:a.logRef,activeProcess:null,evidence:"runtime"};return{...l,evidenceDigest:Im(l,o)}})})})}t=await Ps({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await Ps({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted",activeProcess:null}:n)})})}catch{}throw r}return{checks:vi({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}import{accessSync as C6,constants as P6,promises as FS}from"node:fs";import fa from"node:path";ne();var pD=hr(Gt(),1);We();pe();rt();at();bn();We();gt();ve();gt();ve();Hi();kr();at();ni();async function jm(e){return A(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"confirm-shape"}),t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native Shape can only be confirmed from the persisted user confirmation boundary");if(e.coordinationMode!==void 0&&t.coordination_mode!==void 0&&e.coordinationMode!==t.coordination_mode)throw new Error("--coordination-mode is already bound to this Shape confirmation; revise Shape before changing it");await Ze({paths:e.paths,state:t});let r=await Du({paths:e.paths,state:t}),i=await Bu({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Je({changeDir:le(e.paths,t.name),acceptanceIds:n.map(({id:g})=>g),validation:bt({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await Nl(e.paths,t.name);let g=Ru(t.workspace,e.paths.projectRoot);if(g===null)throw new Error("Native parent changes require a Git integration branch; initialize Git, commit to a branch, then rerun the latest continuation to bind the workspace");o=ke({...t,workspace:g},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${g.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await ls(le(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2,c=e.coordinationMode??t.coordination_mode;if(!s&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");if(s&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(s&&c===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");let l=Ss({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:t.coordination_mode});if(t.shape_confirmation_hash===void 0||l!==t.shape_confirmation_hash){let g=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await Rs({paths:e.paths,state:t,reason:g,keepFailureBudget:!0}),new Error(`${g}; Native change returned to Shape and requires confirmation`)}let u=kk({state:{...o,spec_changes:r,shape_confirmation_hash:Ss({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:c})},acceptance:n.map(g=>({...g}))});if(delete u.children_contract_hash,delete u.coordination_mode,a){u.children_contract_hash=ta({acceptance:u.acceptance,children:a.contract}),s&&(u.coordination_mode=c);let g=[...t.history].reverse().find(({outcome:w})=>w==="pass"||w==="fail");if(g?.outcome==="fail"&&g.unresolved_ids.length>0){let w=await Le({paths:e.paths,state:u}),N=new Map((w?.children??[]).map(({name:b,status:x})=>[b,x])),y=new Set(a.contract.children.filter(({name:b})=>{let x=N.get(b);return x!=="done"&&x!=="integrated"&&x!=="archived"}).flatMap(({covers:b})=>b)),E=g.unresolved_ids.filter(b=>!y.has(b));if(E.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${E.join(", ")}`)}}let p=null,d=a?.contract.schema==="comet.native.children.v2"?await D(e.paths,t.name):null,f=null,h=null;if(a?.contract.schema==="comet.native.children.v2"){if(f=o.workspace.change_branch??o.workspace.target_branch,!f)throw new Error("Native Supervisor v2 requires a target branch");if(h=wr(e.paths.projectRoot,f),!h)throw new Error(`Native Supervisor target branch has no commit: ${f}`);d||(d=await cs({paths:e.paths,parent:t.name,targetBranch:f,contract:a.contract})),d||(p=await Fh({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:f,sourceConfig:await Oe(e.paths.projectRoot)}))}let m=a?.contract.schema==="comet.native.children.v2"&&f&&h?d?Ef({state:d,contract:a.contract}):p?Ro({parent:u.name,targetBranch:f,targetCommit:h,integrationBranch:p.binding.changeBranch,integrationWorktree:p.projectRoot,contract:a.contract}):null:null;if(a?.contract.schema==="comet.native.children.v2"&&!m)throw new Error("Native Supervisor integration state is unavailable");let v=await fe({paths:e.paths,previous:t,next:u});return await M(L(e.paths,t.name),ae({portableState:v,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),m&&await q(e.paths,m),v})}import{randomUUID as fD}from"node:crypto";import Vu from"node:path";ve();So();ji();function DS(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function hD(e){let{state:t,local:r,envelope:i}=e;if(!ml(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function mD(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function Om(e){return A(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(await Ze({paths:e.paths,state:t}),await Je({changeDir:le(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:o})=>o),validation:bt(t)})||t.children_contract_hash){let o=await Le({paths:e.paths,state:t});if(!o?.confirmed||!o.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=Ek({state:t,input:e.input}),n=e.verificationChecks===void 0?null:await jS({paths:e.paths,previous:t,next:i,plans:e.verificationChecks,projectRoot:e.projectRoot,local:await $r({paths:e.paths,state:t})}),a=await fe({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),n??ae({portableState:a,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a})}async function Hm(e){return A(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Ze({paths:e.paths,state:t});let i=(await Eu({file:L(e.paths,t.name),portableState:t,projectRoot:r,branch:ge(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");vi({local:i,projectRoot:r,supplied:e.checks});let n=xk(t),a=await fe({paths:e.paths,previous:t,next:n}),o=L(e.paths,t.name),s=fD();return await M(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function Dm(e){return A(e.paths,`confirm portable verifier start ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier start confirmation requires an active Verifier attempt");let r=L(e.paths,e.name),i=await Ce(r),n=i?.execution;if(i===null||i.change!==t.name||i.basedOnStateVersion!==t.state_version||!n||n.stage!=="verifying"||n.actor!=="verifier"||n.status!=="running"||n.executionId===null||n.executionId!==e.verifierExecutionRef)throw new Error("Native Verifier start confirmation is stale for the current attempt");if(t.builder_handoff?.candidate_id!==e.candidateId)throw new Error("Native Verifier start confirmation is stale for the current candidate");return n.verifierStartedAt===void 0&&await M(r,{...i,execution:{...n,verifierStartedAt:new Date().toISOString()}},{containedRoot:e.paths.runtimeDir}),t})}async function Bm(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await A(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await H(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Ze({paths:e.paths,state:r});let n=await $r({paths:e.paths,state:r}),a=hD({state:r,local:n,envelope:e.envelope}),o;try{o=ko(a.payload)}catch(p){throw new Error(`Native Verifier response was rejected: ${p.message}; correct the response and continue the same active Verifier`,{cause:p})}let s=mD(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=vi({local:n,projectRoot:i,supplied:e.checks}));let p=Rk({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(p.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await OS({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:p.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:p.response,reservation:d}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=p}catch(p){throw new Error(`Native Verifier response was rejected: ${p.message}; correct the response or request missing checks using the same active Verifier`,{cause:p})}let u=await fe({paths:e.paths,previous:r,next:l.state});return await M(L(e.paths,r.name),gi({local:n,state:u,projectRoot:i}),{containedRoot:e.paths.runtimeDir}),u.verification!==null&&await hi({file:Vu.join(le(e.paths,r.name),"verification.md"),state:u}),{kind:"final-result",result:{state:u,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await HS({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier-requested check execution failed: ${r.message}`,n=await A(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await H(e.paths,e.name);return a.state_version!==t.state.state_version?null:Tm({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Gh} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function Lm(e){return A(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await H(e.paths,e.name),r=await $r({paths:e.paths,state:t});if(DS({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return Tm({paths:e.paths,state:t,summary:e.summary})})}async function Fm(e){return A(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);await Ze({paths:e.paths,state:t});let r=await $r({paths:e.paths,state:t}),i=DS({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=vi({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=Pk({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await fe({paths:e.paths,previous:t,next:a});return await M(L(e.paths,t.name),gi({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await hi({file:Vu.join(le(e.paths,t.name),"verification.md"),state:o}),o})}async function qm(e){return A(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);Mt({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Ze({paths:e.paths,state:t});let r=_k({state:t,summary:e.summary}),i=await fe({paths:e.paths,previous:t,next:r});return await M(L(e.paths,t.name),ae({portableState:i,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await hi({file:Vu.join(le(e.paths,t.name),"verification.md"),state:i}),i})}async function Mm(e){return A(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await H(e.paths,e.name);Mt({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Ze({paths:e.paths,state:t});let r=await $r({paths:e.paths,state:t}),i=Ak(t,{reason:e.reason}),n=await fe({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),gi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Vm(e){return A(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await H(e.paths,e.name);Mt({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await $r({paths:e.paths,state:t}),i=Tk(t),n=await fe({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),gi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function an(e){return A(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=e.preserveLocalChecks!==!1,i=r?await $r({paths:e.paths,state:t}):null,n=pi({state:t,reason:e.reason,...e.failureBudget?{failureBudget:e.failureBudget}:{}}),a=await fe({paths:e.paths,previous:t,next:n});return await M(L(e.paths,t.name),r?gi({local:i,state:a,projectRoot:e.paths.projectRoot}):ae({portableState:a,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a})}async function Is(e){if(e.state.verification===null)return"not-applicable";let t=Vu.join(le(e.paths,e.state.name),"verification.md");return await lS({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await hi({file:t,state:e.state}),"rebuilt")}import vD from"node:path";kr();ve();async function Wm(e){return A(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(Mt({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Ze({paths:e.paths,state:t}),e.finish!==void 0&&!["keep","merge","push","pull-request"].includes(e.finish))throw new Error("Native workspace finish must be keep, merge, push, or pull-request");if(e.finish!==void 0&&t.workspace.isolation==="current")throw new Error("A workspace finish choice requires an isolated Native workspace");let r=await D(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(Yi(r).stateVersion!==r.stateVersion)return ua({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await q(e.paths,Xi(r,t))}let i=Ck(t);e.finish!==void 0&&(i.workspace={...i.workspace,finish:e.finish});let n=await fe({paths:e.paths,previous:t,next:i});return await M(L(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:ge(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await hi({file:vD.join(le(e.paths,t.name),"verification.md"),state:n}),n})}import{promises as BS}from"node:fs";kr();ve();zl();async function Ts(e){let t=await H(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await Le({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选可以提交并进入验证":"All Children are complete; the Supervisor parent candidate can be submitted for verification.";return{state:t,parentAdvance:{...r,message:n}}}async function LS(e){let t=await H(e.paths,e.name),r=await Wl(e.paths,{kind:"archive",change:e.name}),i=r?.kind==="archive"?r:null;if(!i&&(t.archived||t.verification===null||t.verification_result!=="pass"))return{state:t,action:"none"};let n=await D(e.paths,e.name);if(i&&n?.finalVerification.status==="pending"){if(i.journal.status!=="prepared"||i.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await BS.rm(i.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||n?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=Yi(n);if(i||a.stateVersion!==n.stateVersion){let o=await ua({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return i&&await BS.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await q(e.paths,Xi(n,t)),{state:t,action:"recorded-final-verification"}}async function Wu(e){return A(e.paths,`recover Supervisor final verification ${e.name}`,()=>LS(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}var g6=16*1024;Jn();bn();var qS="comet.native.workspace-finish.v1",wD="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",WS=new RegExp(`^${wD}$`,"u"),yD=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,$s=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function MS(e,t){if(!e.trim()||e.includes("\0"))throw new Error(`${t} must contain non-whitespace text and no NUL character`)}function bD(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==qS||typeof t.name!="string"||!WS.test(t.name)||typeof t.transactionId!="string"||!yD.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!fa.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(i=>typeof i!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(i=>typeof i!="string")))throw new Error("Native workspace finish journal result is invalid")}if(t.plan!==void 0){let r=t.plan;if(!r||typeof r!="object"||!["keep","merge","push","pull-request"].includes(r.finish)||!["current","branch","worktree"].includes(r.isolation)||![r.changeRoot,r.primaryRoot].every(i=>typeof i=="string"&&fa.isAbsolute(i))||![r.changeBranch,r.targetBranch].every(i=>typeof i=="string"&&i.length>0)||r.targetRoot!==null&&(typeof r.targetRoot!="string"||!fa.isAbsolute(r.targetRoot))||r.remote!==null&&typeof r.remote!="string"||typeof r.commitMessage!="string"||r.mergeMessage!==null&&typeof r.mergeMessage!="string")throw new Error("Native workspace finish journal plan is invalid");MS(r.commitMessage,"commit-message"),r.mergeMessage!==null&&MS(r.mergeMessage,"merge-message")}if(t.createdAt!==void 0&&(typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))))throw new Error("Native workspace finish journal creation identity is invalid");if(t.commit!==void 0){let r=t.commit;if(!r||!$s.test(r.parent)||!Array.isArray(r.paths)||!r.paths.every(i=>typeof i=="string"&&i.length>0&&!fa.posix.isAbsolute(i)&&!fa.win32.isAbsolute(i)&&!i.split("/").includes(".."))||!Array.isArray(r.entries)||!r.entries.every(i=>typeof i=="string")||r.sha!==null&&!$s.test(r.sha))throw new Error("Native workspace finish journal commit is invalid")}if(t.merge!==void 0){let r=t.merge;if(!r||!$s.test(r.target)||!$s.test(r.source)||r.sha!==null&&!$s.test(r.sha))throw new Error("Native workspace finish journal merge is invalid")}return{schema:qS,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt,...t.createdAt===void 0?{}:{createdAt:t.createdAt},...t.plan===void 0?{}:{plan:t.plan},...t.commit===void 0?{}:{commit:t.commit},...t.merge===void 0?{}:{merge:t.merge}}}function ND(e,t){if(!WS.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return fa.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function zS(e,t,r={}){let i=ND(e,t);try{let n=await FS.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=bD(JSON.parse(await FS.readFile(i,"utf8")));if(a.name!==t)throw new Error("Native workspace finish journal name is invalid");return a}catch(n){if(n.code==="ENOENT")return null;if(r.onError)return r.onError(t,n instanceof Error?n.message:String(n)),null;throw n}}import{randomUUID as kD}from"node:crypto";import{promises as js}from"node:fs";import SD from"node:path";ne();rt();ve();nh();zl();Fl();at();ie();var GS=["evidence.md","repair.md","archive.md","checkpoint.md"],ED="verification.md";async function xD(e,t){let r=await Wl(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function JS(e,t){await js.mkdir(e.transactionsDir,{recursive:!0}),await he(Vl(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function US(e,t,r={}){let i=r.removeVerificationReport===!1?GS:[...GS,ED];await Promise.all([js.rm(me(e,t),{recursive:!0,force:!0}),js.rm(df(e,t),{recursive:!0,force:!0}),...i.map(n=>js.rm(SD.join(Ft(e,t),n),{force:!0}))])}async function KS(e,t){await M(L(e,t.name),ae({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function YS(e,t){try{let r=await ws(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function XS(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=oe(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function RD(e){let t=Ft(e.paths,e.state.name),r=await Z({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Z({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Ll({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function QS(e,t){let r=await oS(e,t);if(r.status==="runtime-incompatible")throw new Qt(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function ZS(e){return A(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await xD(e.paths,e.name),r=await aa(e.paths,e.name)?await yt(dt(e.paths,e.name)):null;if(!t&&r)return await US(e.paths,e.name,{removeVerificationReport:!1}),await KS(e.paths,r),r;let i=null,n=null;for(t||(i=await QS(e.paths,e.name),n=await YS(e.paths,e.name),XS(e.paths,n),t={schema:ql,id:kD(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await JS(e.paths,t));;){let a=Gb(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await QS(e.paths,e.name),n??=await YS(e.paths,e.name),XS(e.paths,n),r=zb({state:i,acceptance:await RD({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await bo(dt(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await US(e.paths,e.name):a.action==="commit-transaction"&&(r??=await yt(dt(e.paths,e.name)),await KS(e.paths,r)),t={...t,status:a.nextStatus},await JS(e.paths,t)}return await js.rm(Vl(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??yt(dt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as tE}from"node:fs";import rE from"node:path";ve();import{promises as zm}from"node:fs";import CD from"node:path";pe();var PD=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),_D=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),AD=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),ID=new Set(["status","summary"]);function zu(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Gu(e,t,r,i=new Set){let n=new Set(Object.keys(e)),a=[...t].filter(s=>!n.has(s)&&!i.has(s)),o=[...n].filter(s=>!t.has(s));return a.length===0&&o.length===0?null:`${r} fields must be exact (missing: ${a.join(", ")||"none"}; unexpected: ${o.join(", ")||"none"})`}function TD(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function on(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function $D(e,t,r,i){let n=zu(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Gu(n,PD,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=zu(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Gu(o,_D,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=zu(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Gu(c,ID,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,p]of n.children.entries()){let d=zu(p,`Native Supervisor child ${u}`);if(!d)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:f,contractHash:h,...m}=d,v=Gu(m,AD,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let g=r.children[u],w=g.covers.length>0?g.covers.map(y=>({id:y,source:r.acceptance_index?.[y]?.source??"brief.md",text:r.acceptance_index?.[y]?.text??y})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(f!==void 0&&JSON.stringify(f)!==JSON.stringify(w)||h!==void 0&&h!==$("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(d.name!==g.name||d.summary!==g.summary||!TD(d.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let N=g.depends_on.length===0?"ready":"pending";if(d.status!==N)return`Native Supervisor child ${g.name} has progressed beyond its initial ${N} status`;if(d.baseCommit!==null||d.candidateCommit!==null||d.verifiedCommit!==null||d.integrationCommit!==null||d.verification!==null||d.blocker!==null||d.projectRoot!==null||d.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if((d.builderFailureCount??0)!==0)return`Native Supervisor child ${g.name} contains Builder failure progress`;if(!Array.isArray(d.checks)||d.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function ha(e){let t=Di(e.paths,e.state.name),r;try{let c=await zm.lstat(t);if(!c.isFile()||c.isSymbolicLink())return on(t,"","Native Supervisor overlay is not a regular file");r=await zm.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:on(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return on(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=CD.join(e.paths.changesDir,e.state.name),a;try{a=await Je({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return on(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await D(e.paths,e.state.name)}catch(c){return on(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return on(t,r,"Native Supervisor overlay disappeared during inspection");let s=$D(i,e.state,a.contract,o);return s?on(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}async function eE(e){let t=await ha({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await zm.rm(t.file,{force:!1})}at();ni();function Gm(e,t){let r=oe(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function jD(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function OD(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:ke(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(t),completed_at:i});return B({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?jD(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function HD(e){try{let t=await Ce(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Jm(e){return A(e.paths,`recover portable change ${e.name}`,async()=>{let t=await H(e.paths,e.name);if(t.status==="done")return await Is({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=Gm(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await ha({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await eE({paths:e.paths,state:t,expected:i}),n=!0);let a=L(e.paths,e.name),o=await HD(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason,c=s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed";if(c&&o.local?.execution?.status==="running"){let m=o.local.execution,v=await Fu(o.local),g=m.stage==="verifying"&&m.actor==="verifier"&&m.executionId!==null,w=v==="unknown"&&e.recoverUnknownRuntimeCheck===!0&&m.stage==="checking"&&m.actor==="runtime";if(g||v!=="orphaned"&&!w)return{state:t,local:o.local,action:"await-user",reason:"execution-active",message:g?m.verifierStartedAt===void 0&&m.requestCheckRounds===0?`Native Verifier execution ${m.executionId} is registered but never confirmed startup; if the task did not start, record an explicit Verifier failure before retrying it.`:`Native Verifier execution ${m.executionId} remains owned by its host task; record an explicit Verifier failure before retrying it.`:v==="unknown"?"The Native Runtime check owner could not be proven to have exited; inspect the overlay or run Doctor with --repair to take over explicitly.":"The Native Runtime check operation is still owned by a live process; wait for it to finish before recovering it."}}if(c&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(m=>m.status==="planned"||m.status==="running"?{...m,status:"interrupted"}:m)},await M(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Is({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(m=>m.status==="interrupted"&&!m.repeatable):void 0;if(l){let m=pi({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Bn({file:dt(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot}),await tE.rm(rE.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let v=ae({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await M(a,v,{containedRoot:e.paths.runtimeDir}),{state:t,local:v,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let u=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",p=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",d=u||p;if(d){let m=OD(t,p?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",p);t=await Bn({file:dt(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot})}let f=ae({portableState:t,projectRoot:e.paths.projectRoot,branch:oe(e.paths.projectRoot).currentBranch});await tE.mkdir(rE.dirname(L(e.paths,t.name)),{recursive:!0}),await M(a,f,{containedRoot:e.paths.runtimeDir}),await Is({paths:e.paths,state:t});let h=s==="stale"&&o.local?`Local execution overlay was recorded for state version ${String(o.local.basedOnStateVersion)} of ${o.local.change} but the current state version is ${String(t.state_version)} of ${t.name}; a state transition moved on, so the overlay was rebuilt from the stable boundary.`:null;return{state:t,local:f,action:d?"reverify":"resume-stable-boundary",reason:s,message:h??(d?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`)}})}import iE from"node:path";function nE(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function Pe(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:nE(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:nE(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>iE.relative(t.projectRoot,iE.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}vo();go();function Ju(e){return e.charCodeAt(0)===65279?e.slice(1):e}Wo();Jn();pe();import{randomUUID as lE}from"node:crypto";import{promises as aE}from"node:fs";import Os from"node:path";We();Mn();Lh();So();ve();ji();function ga(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function W(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function ma(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>W(r,`${t}[${i}]`))}function DD(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=ga(t,`Native Builder check ${r}`);if(ee(i,["name","result","note"],`Native Builder check ${r}`,`/checks/${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:W(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function Uu(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=ga(t,`Native Runtime check ${r}`);if(ee(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`,`/checks/${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:W(i.id,`Native Runtime check ${r} id`),name:W(i.name,`Native Runtime check ${r} name`),executable:W(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:W(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function oE(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:W(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function BD(e){let t=ga(e,"Native Supervisor evidence");return ee(t,["summary","checks","acceptance","receiptRef"],"Native Supervisor evidence","/evidence"),{summary:W(t.summary,"Native Supervisor evidence summary"),checks:ma(t.checks,"Native Supervisor evidence checks"),acceptance:gl(t.acceptance,"/evidence/acceptance"),...t.receiptRef===null?{}:{receiptRef:W(t.receiptRef,"Native Supervisor receipt ref")}}}function uE(e){let t=ga(e,"Native Runner input");if(t.kind==="builder-handoff"){let r=["kind","summary","addressed_acceptance_ids","checks","known_limits"];Object.hasOwn(t,"acceptance_review")&&r.push("acceptance_review"),Object.hasOwn(t,"verification_checks")&&r.push("verification_checks"),ee(t,Object.hasOwn(t,"review")?[...r,"review"]:r,"Native Runner Builder input");let i=null;if(t.review!==void 0&&t.review!==null){let n=ga(t.review,"Native Builder review");if(ee(n,["status","summary","reviewer_execution_ref"],"Native Builder review","/review"),n.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");i={status:"passed",summary:W(n.summary,"Native Builder review summary"),reviewer_execution_ref:W(n.reviewer_execution_ref,"Native Builder reviewer execution ref")}}return{kind:"builder-handoff",summary:W(t.summary,"Native Builder summary"),...Object.hasOwn(t,"acceptance_review")?{acceptance_review:$n(t.acceptance_review)}:{},addressed_acceptance_ids:ma(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:DD(t.checks),...Object.hasOwn(t,"verification_checks")?{verification_checks:Uu(t.verification_checks)}:{},known_limits:ma(t.known_limits,"Native Builder known limits"),review:i}}if(t.kind==="dispatch-verifier")return ee(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:Uu(t.checks)};if(t.kind==="retry-checks")return ee(t,["kind","check_ids"],"Native Runner check retry input"),{kind:"retry-checks",check_ids:ma(t.check_ids,"Native check retry IDs")};if(t.kind==="verifier-response")return ee(t,["kind","candidateId","verifierExecutionRef","response"],"Native Runner Verifier input"),{kind:"verifier-response",candidateId:W(t.candidateId,"Native Runner Verifier candidateId"),verifierExecutionRef:W(t.verifierExecutionRef,"Native Runner Verifier verifierExecutionRef"),response:ko(t.response,"/response")};if(t.kind==="verifier-started")return ee(t,["kind","candidateId","verifierExecutionRef"],"Native Runner started input"),{kind:"verifier-started",candidateId:W(t.candidateId,"Native Runner started candidateId"),verifierExecutionRef:W(t.verifierExecutionRef,"Native Runner started verifierExecutionRef")};if(t.kind==="verifier-execution-error")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:W(t.summary,"Native Verifier execution error summary"),...oE(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:W(t.summary,"Native unavailable Verifier summary"),...oE(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return ee(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),candidateCommit:W(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return ee(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),reason:W(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-retry-builder"){if(ee(t,["kind","child","stateVersion"],"Native Supervisor Builder retry input"),!Number.isSafeInteger(t.stateVersion)||t.stateVersion<1)throw new Error("Native Supervisor Builder retry stateVersion is invalid");return{kind:"supervisor-retry-builder",child:W(t.child,"Native Supervisor child"),stateVersion:t.stateVersion}}if(t.kind==="supervisor-reconnect")return ee(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return ee(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),reason:W(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(ee(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:BD(t.evidence)}}if(t.kind==="supervisor-checks"){let r=["kind","child","runId","checks","materials"];if(ee(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor checks"),!Array.isArray(t.materials))throw new Error("Native Supervisor materials must be an array");return{kind:"supervisor-checks",child:W(t.child,"Native Supervisor child"),runId:W(t.runId,"Native Supervisor runId"),checks:Uu(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:ma(t.retry_check_ids,"Native Supervisor retry IDs")},materials:t.materials.map((i,n)=>{let a=ga(i,"Native Supervisor material");return ee(a,["name","content"],"Native Supervisor material",`/materials/${n}`),{name:W(a.name,"Native Supervisor material name"),content:W(a.content,"Native Supervisor material content")}})}}if(t.kind==="supervisor-integrate"){let r=["kind","child","checks"];return ee(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor integration input"),{kind:"supervisor-integrate",child:W(t.child,"Native Supervisor child"),checks:Uu(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:ma(t.retry_check_ids,"Native Supervisor retry IDs")}}}throw new Error("Native Runner input kind is invalid")}async function Qm(e,t){let r=Os.resolve(t,e),i=await aE.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(Ju(await aE.readFile(r,"utf8")))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return uE(n)}async function Zm(e){await A(e.paths,"register-runner-input",async()=>{await bk({paths:e.paths,file:e.file,validateContent:t=>{let r=uE(JSON.parse(Ju(t)));if($("comet.native.runner-input.v1",r)!==$("comet.native.runner-input.v1",e.input))throw new Error("Native Runner input changed after parsing")}})})}function LD(e){return e.kind==="builder-handoff"||e.kind==="dispatch-verifier"||e.kind==="retry-checks"||e.kind==="verifier-response"||e.kind==="verifier-started"||e.kind==="verifier-execution-error"||e.kind==="verifier-unavailable"}function FD(e){return e.kind.startsWith("supervisor-")}function qD(e){return e.response.kind!=="request-checks"?[]:e.response.checks.map(({id:t,name:r,executable:i,argv:n,cwdRef:a,timeoutMs:o,repeatable:s})=>({id:t,name:r,executable:i,argv:[...n],cwdRef:a,timeoutMs:o,repeatable:s}))}function sE(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.stage!=="verify-ready")throw new Error("Native Runner check input requires an active Verify-ready candidate")}function Um(e){if(e.phase!=="verify"||e.status!=="active"||e.loop.next_action!=="await-verifier-result")throw new Error("Native Runner Verifier input requires an active Verifier attempt")}function MD(e,t){if(new Set(t).size!==t.length)throw new Error("Native Builder addressed acceptance IDs contain duplicates");let r=new Set(e.acceptance.map(({id:n})=>n)),i=t.filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native Builder addressed acceptance IDs contain unknown IDs: ${i.join(", ")}`)}async function Km(e){let t=await Ce(L(e.paths,e.state.name)),r=t?.execution;if(t===null||t.basedOnStateVersion!==e.state.state_version||!r||r.stage!=="verifying"||r.actor!=="verifier"||r.status!=="running"||r.executionId===null)throw new Error("Native Runner Verifier input requires an active Runtime Verifier execution");return r}async function ev(e){let t=await ha({paths:e.paths,state:e.state});if(t.status==="incompatible")throw new Error(t.message);let r=t.status==="repairable-legacy-overlay"?null:await D(e.paths,e.name),i=r!==null&&e.state.phase==="verify"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),n=r!==null&&e.state.phase==="build"&&r.children.every(({status:c})=>c==="integrated"||c==="archived"),a=await Le({paths:e.paths,state:e.state}),o=(i||n)&&r?r.integration.worktree:e.projectRoot;if(FD(e.input)&&r===null)throw new Error("Native Supervisor Runner input requires a current Supervisor state");if(r&&LD(e.input)&&!i&&!(e.input.kind==="builder-handoff"&&n))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(e.input.kind==="builder-handoff"){if(e.state.phase!=="build"||e.state.status!=="active")throw new Error("Native Builder input requires an active Build boundary");if(MD(e.state,e.input.addressed_acceptance_ids),jn(e.state.acceptance,e.input.acceptance_review),a&&(!a.confirmed||!a.allDone))throw new Error("Native parent Build advances child changes and does not accept a Builder handoff");if(n&&e.state.loop.stage==="repairing"&&e.state.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first");e.input.verification_checks!==void 0&&lt(o,e.input.verification_checks);return}if(e.input.kind==="dispatch-verifier"){if(sE(e.state),i&&e.input.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");lt(o,e.input.checks);return}if(e.input.kind==="retry-checks"){if(sE(e.state),e.input.check_ids.length===0||new Set(e.input.check_ids).size!==e.input.check_ids.length)throw new Error("Native check retry list must contain unique IDs");let c=await Ce(L(e.paths,e.name));for(let l of e.input.check_ids){let u=c?.checks.find(p=>p.id===l);if(!u||u.status!=="interrupted")throw new Error(`Native check retry ID is not an interrupted current check: ${l}`);if(!u.repeatable)throw new Error(`Native check ${l} is not repeatable and cannot be retried`);if(u.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${l}`)}return}if(e.input.kind==="verifier-response"){Um(e.state);let c=await Km({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");lt(o,qD(e.input));return}if(e.input.kind==="verifier-started"){Um(e.state);let c=await Km({paths:e.paths,state:e.state});if(e.input.candidateId!==e.state.builder_handoff?.candidate_id||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner started input is stale for the current candidate or execution");return}if(e.input.kind==="verifier-execution-error"||e.input.kind==="verifier-unavailable"){Um(e.state);let c=await Km({paths:e.paths,state:e.state});if(e.input.stateVersion!==e.state.state_version||e.input.iteration!==e.state.loop.iteration||e.input.attempt!==e.state.loop.attempt||e.input.verifierExecutionRef!==c.executionId)throw new Error("Native Runner Verifier input is stale for the current attempt");return}let s=e.input;if(s.kind==="supervisor-retry-builder"){if(!r)throw new Error("Native Supervisor Builder retry requires a current Supervisor state");let c=r.children.find(({name:l})=>l===s.child);if(!c)throw new Error(`Native Supervisor child ${s.child} does not exist`);if(s.stateVersion!==r.stateVersion||c.status!=="blocked"||c.task!==null||(c.builderFailureCount??0)<Nr)throw new Error("Native Supervisor Builder retry input is stale or not currently required");return}if(e.input.kind==="supervisor-checks"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:u})=>u)).size!==c.checks.length)throw new Error("Native Supervisor checks require a non-empty plan with unique IDs");if(c.checks.some(({repeatable:u})=>!u))throw new Error("Native Supervisor checks must be repeatable for safe recovery");let l=r?.children.find(({name:u})=>u===c.child)?.task;if(!l||l.role!=="verifier"||l.runId!==c.runId)throw new Error("Native Supervisor check runId is not current");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");lt(l.projectRoot,c.checks);return}if(e.input.kind==="supervisor-integrate"){let c=e.input;if(c.checks.length===0||new Set(c.checks.map(({id:l})=>l)).size!==c.checks.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(c.checks.some(({repeatable:l})=>!l))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(c.retry_check_ids!==void 0&&(c.retry_check_ids.length===0||new Set(c.retry_check_ids).size!==c.retry_check_ids.length))throw new Error("Native Supervisor retry IDs must be non-empty and unique");lt(r.integration.worktree,c.checks)}}function dE(e){return`${Se}:${e}:${lE()}`}function cE(e,t,r,i){if(Os.resolve(I(e.projectRoot,["rev-parse","--show-toplevel"]))!==Os.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(I(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!tr(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(I(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function VD(e,t){let r=oe(e.projectRoot),i=Os.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==Os.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=I(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!tr(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function va(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Se)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");return e.builder_handoff}function WD(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function pE(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=va(r),s=WD(r),c=r.acceptance.filter(({result:p})=>p==="pending").map(({id:p})=>p),l=r.acceptance.filter(({id:p})=>c.includes(p)).map(({id:p,source:d,text:f})=>({id:p,source:d,text:f})),u=l.length<=eh.maxItems&&Buffer.byteLength(JSON.stringify(l),"utf8")<=eh.maxSerializedBytes;return{coordination:Se,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:le(t,r.name),supervisorStateRef:a?Di(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:p,operation:d,source:f})=>({capability:p,operation:d,ref:f})),acceptanceCount:r.acceptance.length,scopeCount:c.length,scopeIds:c,...u?{acceptance:l}:{},startupInput:{kind:"verifier-started",candidateId:o.candidate_id,verifierExecutionRef:n},detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:o.review?{status:o.review.status,summary:o.review.summary}:null,builderSummary:o.summary.text,runtimeChecks:i.map(p=>({...p})),builderReportedChecks:o.checks.map(p=>({...p})),builderKnownLimits:o.known_limits.map(p=>({...p})),startupInstruction:"As this Verifier, submit the startup receipt first: copy startupInput into a temporary JSON file and run comet native next <change> --runner-input <file> --project-root <projectRoot above>. It records that this Verifier actually started; a repeat submission is accepted without side effects. Read acceptance when included; otherwise follow detailsPageArgs until every scopeId has been read. Then inspect the linked brief and Spec and proceed.",evidenceInstruction:"Independently inspect the current candidate against every scenario in scopeIds exactly once. Runtime checks are bound evidence; Builder-reported checks and review are claims to corroborate, not Runtime receipts. Reuse applicable completed evidence, request only missing or invalidated checks, and do not repeat full suites by default. Use one Verifier for this dispatch; keep it running across wait-tool timeouts. Return the actual scoped findings, risks, and incomplete checks without omitting limitations. Keep using the same CLI executable that produced this dispatch; do not switch to a different PATH installation.",responseInstruction:"Return one acceptance entry for each ID in scopeIds and no other acceptance IDs. Runtime safely filters a known already-passed superset only when every extra entry still reports passed; nonexistent IDs and conflicting out-of-scope results remain invalid."}}async function Ym(e){let t=dE("verifier"),r=await Hm({paths:e.paths,name:e.name,checks:e.checks,verifierExecutionId:t,...e.supervisor?{projectRoot:e.supervisor.integration.worktree}:{}});return{state:r,checks:e.checks,runtimeCheckExecution:{disposition:e.disposition},requestChecks:null,verifierDispatch:pE({paths:e.paths,state:r,checks:e.checks,verifierExecutionRef:t,supervisor:e.supervisor}),continuation:Y(r,void 0,{verifierExecutionRef:t,verifierStartup:"unconfirmed"})}}async function Xm(e){va(e.state);let t=await Ce(L(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function fE(e){let t=e.input;e.inputFile&&await Zm({paths:e.paths,file:e.inputFile,input:t});let r=await H(e.paths,e.name),i=await ha({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await D(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:h})=>h==="integrated"||h==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:h})=>h==="integrated"||h==="archived");if(n&&t.kind==="supervisor-checks"){let h=await Bh({paths:e.paths,parent:e.name,child:t.child,runId:t.runId,plans:t.checks,materials:t.materials,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),m=await D(e.paths,e.name),v=m?.children.find(({name:g})=>g===t.child)?.task;return{state:r,supervisorState:m,supervisorTask:v&&v.runId===t.runId?ri(v,e.name,e.paths.projectRoot):null,checks:[],checkExecution:h,requestChecks:null,verifierDispatch:null,continuation:Y(r)}}if(n&&t.kind==="supervisor-builder-result")return A(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let h=await D(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:y})=>y===t.child);if(!m?.task||m.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{cE(m.task,t.candidateCommit,"builder",`comet/supervisor/${h.parent}/${t.child}`)}catch(y){throw await q(e.paths,Po(h,{child:t.child,runId:t.runId,reason:y.message})),y}let v=m.task.projectRoot,g=Rf(h,t),w=Co(g,{role:"verifier",child:t.child,projectRoot:v,runId:lE()});await q(e.paths,w.state);let N=await H(e.paths,e.name);return{state:N,supervisorTask:ri(w.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(N)}});if(n&&t.kind==="supervisor-builder-failure")return A(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let h=await D(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:w})=>w===t.child);if(!m?.task||m.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let v=wl(h,{child:t.child,runId:t.runId,reason:t.reason});await q(e.paths,v);let g=await H(e.paths,e.name);return{state:g,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(g)}});if(n&&t.kind==="supervisor-retry-builder")return A(e.paths,`retry Native Supervisor Builder task ${t.child}`,async()=>{let h=await D(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=Pf(h,{child:t.child,expectedStateVersion:t.stateVersion});await q(e.paths,m);let v=await H(e.paths,e.name);return{state:v,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(v)}});if(n&&t.kind==="supervisor-reconnect")return A(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let h=await D(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:w})=>w===t.child)?.task;if(!m||m.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{VD(m,`comet/supervisor/${h.parent}/${t.child}`)}catch(w){throw await q(e.paths,Po(h,{child:t.child,runId:t.runId,reason:w.message})),w}let v=xf(h,{child:t.child,runId:t.runId});await q(e.paths,v.state);let g=await H(e.paths,e.name);return{state:g,supervisorState:v.state,supervisorTask:ri(v.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(g)}});if(n&&t.kind==="supervisor-cancel")return A(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let h=await D(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=wl(h,{child:t.child,runId:t.runId,reason:t.reason});await q(e.paths,m);let v=await H(e.paths,e.name);return{state:v,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(v)}});if(n&&t.kind==="supervisor-verifier-result")return A(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let h=await D(e.paths,e.name);if(!h)throw new Error(`Native Supervisor state is missing for ${e.name}`);let m=h.children.find(({name:N})=>N===t.child);if(!m?.task||m.task.role!=="verifier"||!m.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{cE(m.task,m.candidateCommit,"verifier",`comet/supervisor/${h.parent}/${t.child}`)}catch(N){throw await q(e.paths,Po(h,{child:t.child,runId:t.runId,reason:N.message})),N}let v=t.evidence.receiptRef||t.verdict==="pass"?await ea({paths:e.paths,parent:e.name,task:m.task,receiptRef:t.evidence.receiptRef??""}):null;if(t.verdict==="pass"&&(!v||v.checks.some(({status:N,exitCode:y})=>N!=="passed"||y!==0)))throw new Error("Native Supervisor verification cannot pass before every Runtime check succeeds");let g=Cf(h,{...t,evidence:{...t.evidence,checks:v?.checks.map(({name:N,status:y})=>`${N}: ${y}`)??[],execution:structuredClone(m.task)}});await q(e.paths,g);let w=await H(e.paths,e.name);return{state:w,supervisorState:g,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(w)}});if(n&&t.kind==="supervisor-integrate"){let h=await Mh({paths:e.paths,state:n,name:t.child,checks:[],checkPlans:t.checks,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),m=await Ts({paths:e.paths,name:e.name,trigger:"v2-integrate"}),v=m.state;return{state:v,supervisorState:h,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:m.parentAdvance,continuation:Y(v)}}if(n&&(t.kind==="builder-handoff"||t.kind==="dispatch-verifier"||t.kind==="retry-checks"||t.kind==="verifier-response"||t.kind==="verifier-started"||t.kind==="verifier-execution-error"||t.kind==="verifier-unavailable"||t.kind==="supervisor-builder-result"||t.kind==="supervisor-builder-failure"||t.kind==="supervisor-reconnect"||t.kind==="supervisor-cancel"||t.kind==="supervisor-verifier-result")&&!a&&!(t.kind==="builder-handoff"&&o))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(t.kind==="builder-handoff"){if(o&&t.verification_checks?.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let m=Nf().captureExecutionIdentity({identityProvider:Se,executionRef:dE("builder")}),v=await Om({paths:e.paths,name:e.name,verificationChecks:t.verification_checks,...o&&n?{projectRoot:n.integration.worktree}:{},input:{identity:m,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,acceptanceReview:t.acceptance_review,checks:t.checks,knownLimits:t.known_limits,review:t.review?{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}:null}});if(t.verification_checks!==void 0){let g=await As({paths:e.paths,name:e.name,plans:t.verification_checks,...o&&n?{projectRoot:n.integration.worktree}:{}}),w=g.checks.filter(({status:E})=>E==="failed").map(({id:E})=>E),N=g.checks.filter(({status:E})=>E==="interrupted").map(({id:E})=>E),y=t.verification_checks.filter(({id:E,repeatable:b})=>N.includes(E)&&!b).map(({id:E})=>E);if(w.length>0||y.length>0){let E=w.length>0?`Builder handoff Runtime checks failed: ${w.join(", ")}`:`Builder handoff Runtime checks were interrupted and cannot be repeated: ${y.join(", ")}`,b=await an({paths:e.paths,name:e.name,reason:E,failureBudget:{maxVerifyFailures:e.maxVerifyFailures}});return{state:b,checks:g.checks,runtimeCheckExecution:{disposition:g.disposition},requestChecks:null,verifierDispatch:null,continuation:Y(b)}}return N.length===0?Ym({paths:e.paths,name:e.name,checks:g.checks,disposition:g.disposition,supervisor:o?n:null}):{state:g.state,checks:g.checks,runtimeCheckExecution:{disposition:g.disposition},continuationCheckPlans:t.verification_checks,...N.length>0?{continuationRetryCheckIds:N}:{},requestChecks:null,verifierDispatch:null,continuation:Y(g.state,void 0,{...N.length>0?{retryCheckIds:N}:{verificationCheckPlans:t.verification_checks}})}}return{state:v,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(v)}}if(t.kind==="retry-checks"){if(n&&!a)throw new Error("Native Supervisor check retry is only valid after every Child is integrated");let h=await H(e.paths,e.name);va(h);let m=await $m({paths:e.paths,name:e.name,checkIds:t.check_ids,...a&&n?{projectRoot:n.integration.worktree}:{}}),v=m.checks.filter(({status:g})=>g==="interrupted").map(({id:g})=>g);if(v.length>0){let w=((await Ce(L(e.paths,e.name)))?.checks??[]).filter(({id:N,status:y,executionCount:E})=>v.includes(N)&&y==="interrupted"&&E>=3).map(({id:N})=>N);if(w.length>0){let N=await an({paths:e.paths,name:e.name,reason:`Native Runtime checks reached the retry limit after repeated interruptions: ${w.join(", ")}`,failureBudget:{maxVerifyFailures:e.maxVerifyFailures},preserveLocalChecks:!0});return{state:N,checks:m.checks,requestChecks:null,verifierDispatch:null,continuation:Y(N)}}}return v.length===0&&m.checks.every(({status:g})=>g==="passed")?Ym({paths:e.paths,name:e.name,checks:m.checks,disposition:"executed",supervisor:a?n:null}):{state:m.state,checks:m.checks,...v.length>0?{continuationRetryCheckIds:v}:{},requestChecks:null,verifierDispatch:null,continuation:Y(m.state,void 0,{retryCheckIds:v.length>0?v:void 0})}}if(t.kind==="dispatch-verifier"){if(a&&t.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let h=await H(e.paths,e.name);if(h.builder_handoff!==null&&h.builder_handoff.identity_provider!==Se){let w=await an({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:w,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(w)}}va(h);let m=await As({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}}),v=m.checks,g=v.filter(({status:w})=>w==="interrupted").map(({id:w})=>w);if(g.length>0){let w=t.checks.filter(({id:y,repeatable:E})=>g.includes(y)&&!E).map(({id:y})=>y);if(w.length>0)throw new Error(`Native non-repeatable checks were interrupted and require a new Builder candidate: ${w.join(", ")}`);let N=await H(e.paths,e.name);return{state:N,checks:v,runtimeCheckExecution:{disposition:m.disposition},continuationRetryCheckIds:g,requestChecks:null,verifierDispatch:null,continuation:Y(N,void 0,{retryCheckIds:g})}}return Ym({paths:e.paths,name:e.name,checks:v,disposition:m.disposition,supervisor:a?n:null})}if(t.kind==="verifier-started"){let h=await Dm({paths:e.paths,name:e.name,candidateId:t.candidateId,verifierExecutionRef:t.verifierExecutionRef});return{state:h,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(h,void 0,{verifierExecutionRef:t.verifierExecutionRef,verifierStartup:"confirmed"})}}if(t.kind==="verifier-execution-error"){let h=await H(e.paths,e.name);va(h),await Xm({paths:e.paths,state:h});let m=await Lm({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:Y(m)}}if(t.kind==="verifier-unavailable"){let h=await Fm({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:h,checks:h.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:Y(h)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await H(e.paths,e.name),c=va(s),l=await Xm({paths:e.paths,state:s});if(t.candidateId!==c.candidate_id||t.verifierExecutionRef!==l)throw new Error("Native Runner Verifier input is stale for the current candidate or execution");let u=Nf(),p=u.captureExecutionIdentity({identityProvider:Se,executionRef:l}),d=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let h=await D(e.paths,e.name);if(!h)throw new Error("Native Supervisor state disappeared before final verification");d=Yi(h)}let f=await Bm({paths:e.paths,name:e.name,envelope:u.envelopeVerifierResponse({candidateId:c.candidate_id,identity:p,payload:t.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...a&&n?{projectRoot:n.integration.worktree}:{}});if(a&&f.response.kind==="final-result"){if(f.state.verification_result==="pass"&&(f.checks.length===0||f.checks.some(({status:v})=>v!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let h=d??await D(e.paths,e.name);if(!h)throw new Error("Native Supervisor state disappeared during verification");let m=Xi(h,f.state);return await q(e.paths,m),{...f,supervisorState:m,verifierDispatch:null,continuation:Y(f.state)}}return{...f,verifierDispatch:f.requestChecks===null?null:pE({paths:e.paths,state:f.state,checks:f.checks,verifierExecutionRef:await Xm({paths:e.paths,state:f.state}),supervisor:a?n:null}),continuation:Y(f.state,void 0,{verifierExecutionRef:l,verifierStartup:"confirmed"})}}ji();On();lo();import Ds from"path";import{realpathSync as _B}from"fs";function hE(e,t){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},i=r(e),n=r(i.entry),a=r(i.state??n.state??i),o=r(i.preparation??i.workspace??n.workspace),s=r(i.continuation??n.continuation),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var jr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function mE(e){return e?e.command?`${jr.next} ${e.command}`:e.ask_user?`${jr.next} ${e.ask_user}`:null:null}function vE(e,t){let r=[e.summary],i=mE(e.next);return i&&r.push(i),e.user_message&&r.push("",jr.relay,e.user_message),t!==void 0&&r.push("",jr.details,JSON.stringify(t,null,2)),`${r.join(`
290
375
  `)}
291
- `}function vk(e,t,r){let i=[e.summary],n=hk(e.next);return n&&i.push(n),e.user_message&&i.push("",wr.relay,e.user_message),i.push("",`${wr.detail} ${t}`),r!==void 0&&i.push("",wr.details,JSON.stringify(r,null,2)),i.join(`
292
- `)}fe();nt();fe();var IO=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});Gr();Mt();st();te();ne();Jt();ro();le();te();Mt();qr();fe();fe();Al();Cn();Jt();var gk={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},TO=Xe("comet-native-runtime:v3:scope-reopen"),kU=[{skillVersion:"3",skillHash:Xe("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Xe("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Xe("comet-native-runtime:v1")}];Jt();Jt();no();var yk=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],rK=new Set(yk),LO=new Set([...yk,"minimum_runtime_version","revision"]),iK=new Set([...LO,"operation"]),qO=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),nK=new Set([...qO,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);tl();nt();nt();tl();fe();var lK={maxAcceptanceCriteria:el.maxCriteria};Gr();po();Cn();Al();import{execFile as KO}from"node:child_process";Dc();Vf();import{promisify as YO}from"node:util";ne();Jt();te();Mt();Sa();qr();le();ne();Ip();te();Dt();Gr();le();qr();var Yo=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};po();Tl();Cn();var lY=64*1024;var uY=3600*1e3;var dY=YO(KO);Tl();var ou=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};Jt();Mt();ne();Dt();te();Mt();ml();ne();xi();Gr();var o6=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Jt();ro();le();te();Mt();ml();var su=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},cu=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};te();st();function L(e,t,r){return e==="zh-CN"?r:t}var Bh={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function bk(e,t){return typeof e=="string"&&Bh[e]?L(t,Bh[e].en,Bh[e].zh):typeof e=="string"?e:""}function Lh(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function e0(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function kk(e,t){let r=[];e.failed>0&&r.push(L(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(L(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(L(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=L(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Sk(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function qh(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function t0(e,t,r){return e==="done"?L(r,"complete","已完成"):e==="await-user"?L(r,"waiting for a user decision","等待用户决定"):e==="blocked"?L(r,"paused: needs attention","已暂停,需要处理"):t?L(r,"waiting for a user decision","等待用户决定"):L(r,"ready to continue","可继续推进")}function r0(e,t,r){let i=qh(e),n=[];r&&n.push(r);let a=L(i,`Change ${e.change}`,`需求 ${e.change}`),o=bk(e.phase,i),s=t0(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(kk(t,i));let c=e.userCommunication,l=Ek(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Ek(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:L(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:L(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:L(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function i0(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function n0(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=bk(e.phase,t),n=e.status==="await-user"?L(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?L(t,"paused","已暂停"):e.status==="done"?L(t,"complete","已完成"):L(t,"in progress","进行中"),a=Lh(e.acceptance)?`${L(t,", ",",")}${kk(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function a0(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function o0(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function s0(e){if(e.healthy){let i=e.repaired?L("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):L("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=c0(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:L("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:L("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function c0(e){return Sk(e)?Ek(e,qh(e)):void 0}function xk(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(o0(t))return s0(t);if(i0(t)){let i=a0(t.items);return{summary:[t.total===t.items.length?L(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):L(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>n0(a,i))].join(`
293
- `)}}let r=t.continuation;if(Sk(r)){let i=qh(r),n=r0(r,l0(t),d0(t,i));return u0(t)==="unconfirmed"?{...n,summary:`${n.summary}${L(i,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:n}if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:L(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function l0(e){if(Lh(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Lh(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return e0(r.acceptance)}return null}function u0(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function d0(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return L(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?L(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Ck(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:L("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:L("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:L("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:L("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:L("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:L("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:L("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:L("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:L("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}_c();var Rk=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],Fh=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","In `agent.workspace.cwd`, execute the exact `agent.continuation.commandArgs` returned by Runtime.","Use `agent.continuation.inputOptions` templates for JSON input; do not reconstruct fields from memory."],subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec disassociate Revoke a capability association through Runtime.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:Rk,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--task <text>] [--capability <id>] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--task <text> Search Project Knowledge for an existing capability and save a revocable association draft.","--capability <id> Directly validate and associate an existing capability without retrieval.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, canonical artifact paths, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:`comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
376
+ `}function gE(e,t,r){let i=[e.summary],n=mE(e.next);return n&&i.push(n),e.user_message&&i.push("",jr.relay,e.user_message),i.push("",`${jr.detail} ${t}`),r!==void 0&&i.push("",jr.details,JSON.stringify(r,null,2)),i.join(`
377
+ `)}pe();rt();pe();var zD=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});ui();Zt();gt();ie();ne();rr();Ho();ve();ie();Zt();ii();pe();pe();fu();Xn();rr();var wE={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},GD=ut("comet-native-runtime:v3:scope-reopen"),O9=[{skillVersion:"3",skillHash:ut("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ut("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ut("comet-native-runtime:v1")}];rr();rr();Bo();var bE=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],m4=new Set(bE),ZD=new Set([...bE,"minimum_runtime_version","revision"]),v4=new Set([...ZD,"operation"]),eB=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),g4=new Set([...eB,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);Wo();rt();rt();Wo();pe();var k4={maxAcceptanceCriteria:Bl.maxCriteria};ui();Jo();Xn();fu();import{execFile as lB}from"node:child_process";yn();Xa();Of();import{promisify as uB}from"node:util";ne();rr();ie();Zt();eo();ii();ve();ne();Rh();ie();Jt();ui();ve();ii();var Hs=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Jo();mu();Xn();var S3=64*1024;var E3=3600*1e3;var x3=uB(lB);mu();var Ku=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};rr();Zt();ne();Jt();ie();Zt();Ql();ne();Wi();ui();var b8=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});rr();Ho();ve();ie();Zt();Ql();var Yu=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Xu=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};ie();gt();function F(e,t,r){return e==="zh-CN"?r:t}var tv={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function kE(e,t){return typeof e=="string"&&tv[e]?F(t,tv[e].en,tv[e].zh):typeof e=="string"?e:""}function rv(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function hB(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function SE(e,t){let r=[];e.failed>0&&r.push(F(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(F(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(F(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=F(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function EE(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function iv(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function mB(e,t,r){return e==="done"?F(r,"complete","已完成"):e==="await-user"?F(r,"waiting for a user decision","等待用户决定"):e==="blocked"?F(r,"paused: needs attention","已暂停,需要处理"):t?F(r,"waiting for a user decision","等待用户决定"):F(r,"ready to continue","可继续推进")}function vB(e,t,r){let i=iv(e),n=[];r&&n.push(r);let a=F(i,`Change ${e.change}`,`需求 ${e.change}`),o=kE(e.phase,i),s=mB(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(SE(t,i));let c=e.userCommunication,l=xE(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function xE(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:F(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:F(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:F(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function gB(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function wB(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=kE(e.phase,t),n=e.status==="await-user"?F(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?F(t,"paused","已暂停"):e.status==="done"?F(t,"complete","已完成"):F(t,"in progress","进行中"),a=rv(e.acceptance)?`${F(t,", ",",")}${SE(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function yB(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function bB(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function NB(e){if(e.healthy){let i=e.repaired?F("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):F("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=kB(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:F("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:F("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function kB(e){return EE(e)?xE(e,iv(e)):void 0}function RE(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(bB(t))return NB(t);if(gB(t)){let i=yB(t.items);return{summary:[t.total===t.items.length?F(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):F(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>wB(a,i))].join(`
378
+ `)}}let r=t.continuation;if(EE(r)){let i=iv(r),n=vB(r,SB(t),xB(t,i));return EB(t)==="unconfirmed"?{...n,summary:`${n.summary}${F(i,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:n}if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:F(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function SB(e){if(rv(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(rv(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return hB(r.acceptance)}return null}function EB(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function xB(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return F(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?F(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function CE(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"document-invalid":return{summary:e.message,...typeof r.change=="string"?{next:{command:`comet native next ${r.change} --summary <summary>`}}:{}};case"conflict":return{summary:F("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:F("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:F("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:F("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:F("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:F("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:F("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:F("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:F("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}vo();go();var PE=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],nv=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","In `agent.workspace.cwd`, execute the exact `agent.continuation.commandArgs` returned by Runtime.","Use `agent.continuation.inputOptions` templates for JSON input; do not reconstruct fields from memory."],subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec disassociate Revoke a capability association through Runtime.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:PE,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--task <text>] [--capability <id>] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--task <text> Search Project Knowledge for an existing capability and save a revocable association draft.","--capability <id> Directly validate and associate an existing capability without retrieval.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, canonical artifact paths, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:`comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
294
379
  comet native spec remove <change-name> <capability>
295
380
  comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["disassociate <change-name> Revoke a capability association and return to Shape.","remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections without changing prose or acceptance."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},"spec disassociate":{usage:"comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability",purpose:"Revoke a capability association through Runtime without hand-editing artifacts.",options:["--expected-state-version <n> State version returned by the latest status response.","--expected-action <action> Must be disassociate-capability."],output:"The updated portable state and continuation with the next Runner action."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Sync local Markdown link destinations in an already confirmed target spec; semantic edits require Shape.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"The audited portable state, preserved unaffected acceptance results and Build continuation for re-verification."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"A compact summary and NEXT action by default. Use --json to read canonical artifact paths, the portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required. Fill command-template placeholders before executing NEXT commands."},check:{usage:"comet native check <change-name>",purpose:"Legacy-only verification command; not supported for current portable changes.",output:"For current changes, run comet native status <change-name> --json and follow the continuation to dispatch verification through comet native next."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with canonical artifact paths and local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
296
381
  comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--expected-state-version <n>] [--expected-action <action>]
297
- comet native next <change-name> --runner-input <json-file> [--validate-only]`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Select how a multi-child Supervisor proceeds while preparing its Shape confirmation; final Shape confirmation is a later, separate step.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, retry-checks, verifier-response, verifier-started, verifier-execution-error, or verifier-unavailable. Builder/dispatch identity fields are rejected; verifier responses must echo the current candidateId and verifierExecutionRef from the Verifier dispatch.","--validate-only Validate the Runner JSON shape and current boundary without writing state or starting a process; requires --runner-input."," Choose one object template from an inputOptions exclusiveGroup and save it as UTF-8 JSON (BOM accepted). Field errors return issues with JSON pointer, missingFields and unknownFields. Execute agent.continuation in agent.workspace.cwd; Supervisor results use task.returnAction."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, verification_checks, known_limits, optional review. checks summarize development feedback. verification_checks is an optional Runtime plan executed after the candidate is frozen; a passing plan is reused without executing the same plan twice when dispatch-verifier receives the unchanged plan. If review is supplied, its fields are status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," retry-checks fields: kind, check_ids for repeatable interrupted Runtime checks from the current candidate; each check can be retried at most three times."," verifier-response fields: kind, candidateId, verifierExecutionRef, response (request-checks or final-result); copy the two binding fields from the current continuation."," verifier-started fields: kind, candidateId, verifierExecutionRef copied from verifierDispatch; the dispatched Verifier submits it as its first Runtime action so status can distinguish a registered dispatch from a Verifier that actually started. Repeating it is accepted without side effects."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."," supervisor-checks fields: kind, child, runId, checks (non-empty repeatable Runtime check plans), materials [{name,content}], and optional retry_check_ids for interrupted checks from the same candidate, machine and workspace. Returns per-check execution state plus operationId, status and receiptRef. Repeated running plans return the same handle."," supervisor-verifier-result evidence fields: summary, checks (informal notes), acceptance [{id,result,reason}], receiptRef. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once. Runtime receipts determine formal check status; receiptRef may be null for fail or blocked."," supervisor-integrate checks are non-empty Runtime check plans executed after the merge in the integration worktree, not declared statuses."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
298
- comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness, every blocker, and the exact next continuation, or the completed Archive transaction and workspace finish result. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function lu(e,t){return`${e}:
382
+ comet native next <change-name> --runner-input <json-file> [--validate-only]`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Choose how a multi-child Supervisor proceeds. Supply it with --confirmed at the persisted Shape boundary to confirm the full plan and mode together, or select it during preparation and confirm the plan afterward.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--finish keep|merge|push|pull-request With --accept-result, record the explicitly chosen isolated-workspace finish in the same guarded decision.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, retry-checks, verifier-response, verifier-started, verifier-execution-error, or verifier-unavailable. Builder/dispatch identity fields are rejected; verifier responses must echo the current candidateId and verifierExecutionRef from the Verifier dispatch.","--validate-only Validate the Runner JSON shape and current boundary without writing state or starting a process; requires --runner-input."," Choose one object template from an inputOptions exclusiveGroup and save it as UTF-8 JSON (BOM accepted). Field errors return issues with JSON pointer, missingFields and unknownFields. Execute agent.continuation in agent.workspace.cwd; Supervisor results use task.returnAction."," builder-handoff fields: kind, summary, addressed_acceptance_ids, acceptance_review, checks, verification_checks, known_limits, optional review. acceptance_review must cover every confirmed ID exactly once with id, status, evidence (concrete references or observations), and note. Only implemented-with-evidence with nonempty evidence is ready for handoff; implemented-no-evidence, not-implemented, and known-fail remain in Build. This Builder declaration does not replace independent verification. checks summarize development feedback. verification_checks is an optional Runtime plan executed after the candidate is frozen; a passing plan returns the Verifier dispatch immediately. Completed Runtime checks can carry to a new candidate only when the implementation, confirmed documents, plan, workspace, environment, and saved evidence still match. If review is supplied, its fields are status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," retry-checks fields: kind, check_ids for repeatable interrupted Runtime checks from the current candidate; each check can be retried at most three times."," verifier-response fields: kind, candidateId, verifierExecutionRef, response (request-checks or final-result); copy the two binding fields from the current continuation."," verifier-started fields: kind, candidateId, verifierExecutionRef copied from verifierDispatch; the dispatched Verifier submits it as its first Runtime action so status can distinguish a registered dispatch from a Verifier that actually started. Repeating it is accepted without side effects."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."," supervisor-checks fields: kind, child, runId, checks (non-empty repeatable Runtime check plans), materials [{name,content}], and optional retry_check_ids for interrupted checks from the same candidate, machine and workspace. Returns per-check execution state plus operationId, status and receiptRef. Repeated running plans return the same handle."," supervisor-verifier-result evidence fields: summary, checks (informal notes), acceptance [{id,result,reason}], receiptRef. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once. Runtime receipts determine formal check status; receiptRef may be null for fail or blocked."," supervisor-integrate checks are non-empty Runtime check plans executed after the merge in the integration worktree, not declared statuses."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep] [--commit-message <text>] [--merge-message <text>]
383
+ comet native archive <change-name> [--confirmed] [--serial-first <current-change>] [--commit-message <text>] [--merge-message <text>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--expected-state-version <n> Preserve this continuation-issued guard when confirming a new finish choice; stale choices are rejected before it is recorded.","--commit-message <text> Set the archive commit message; Unicode and multiline text are supported. Git hooks still run.","--merge-message <text> Set the local merge commit message; requires merge finish. Omit it to use Git defaults.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness, every blocker, actual prepared commitMessages (mergeMessage is null when no merge is planned), and the exact next continuation, or the completed Archive transaction and workspace finish result. Messages are retained for retries. After a Git hook rejects a message, provide a corrected message with --confirmed for the unfinished step; completed commits are never rewritten. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Qu(e,t){return`${e}:
299
384
  ${t.map(r=>` ${r}`).join(`
300
- `)}`}function f0(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Fh[r]||t.length>1&&Fh[t[0]]?.subcommands?r:t[0]}function p0(e=[]){let t=f0(e),r=Fh[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",lu("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",lu("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...Rk];return n&&n.length>0&&i.push("",lu("Options",n)),i.push("",`Output:
301
- ${r.output}`),r.examples&&i.push("",lu("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
385
+ `)}`}function RB(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return nv[r]||t.length>1&&nv[t[0]]?.subcommands?r:t[0]}function CB(e=[]){let t=RB(e),r=nv[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",Qu("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",Qu("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...PE];return n&&n.length>0&&i.push("",Qu("Options",n)),i.push("",`Output:
386
+ ${r.output}`),r.examples&&i.push("",Qu("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
302
387
  `)}
303
- `}}var h0=p0().usage;var p9=10*1024*1024,X=class extends Error{};function jt(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new X(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function yr(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new X(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new X(`${t} requires a value`);return e.splice(i,2),n}function _k(e){if(e.length>0)throw new X(`Unexpected argument: ${e[0]}`)}function Ak(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new X(`${t} is required`);return r}function Vh(e,t){let r=Xo.normalize(Pk(e)),i=Xo.normalize(Pk(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Pk(e){let t=Xo.resolve(e);try{return m0.native(t)}catch{return t}}function v0(e){let t=Xo.resolve(e),r=ie(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=ie(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Vh(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Vh(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Vh(process.cwd(),r.currentWorktreeRoot)?Xo.resolve(process.cwd()):r.currentWorktreeRoot}async function Ik(e){return e?v0(e):mc(process.cwd())}async function Tk(e){let t=await rw({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function jk(e){return JSON.stringify(e,null,2)+`
304
- `}function Ze(e,t,r){return{command:e,exitCode:0,data:t,text:r??jk(t)}}function g0(e,t){if(t instanceof qa)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof X)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof su)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof cu)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Vl)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof Do)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof Vr)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Ml)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof ou)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Yo)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Wn(e,t){let r=g0(e,t),i=r.error;if(!i)return r;let n=Ck({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function w0(e,t,r=!1){let i=e.envelope??xk(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:pk(e.data,e.executionCwd),...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
305
- `}:e.error?{exitCode:e.exitCode,stderr:i?vk(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:mk(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==jk(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
306
- ${wr.details}
388
+ `}}var PB=CB().usage;var _5=10*1024*1024,X=class extends Error{};function Vt(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new X(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function dr(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new X(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new X(`${t} requires a value`);return e.splice(i,2),n}function AE(e){if(e.length>0)throw new X(`Unexpected argument: ${e[0]}`)}function IE(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new X(`${t} is required`);return r}function av(e,t){let r=Ds.normalize(_E(e)),i=Ds.normalize(_E(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function _E(e){let t=Ds.resolve(e);try{return _B.native(t)}catch{return t}}function AB(e,t){let r=Ds.resolve(t,e),i=oe(t);if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return r;let n=oe(r);return!n.isGitWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null||!av(i.primaryWorktreeRoot,n.primaryWorktreeRoot)||av(i.currentWorktreeRoot,n.currentWorktreeRoot)?r:av(t,i.currentWorktreeRoot)?Ds.resolve(t):i.currentWorktreeRoot}async function TE(e,t=process.cwd()){return e?AB(e,t):tl(t)}function $E(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}async function jE(e){let t=await Sy({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function OE(e){return JSON.stringify(e,null,2)+`
389
+ `}function et(e,t,r){return{command:e,exitCode:0,data:t,text:r??OE(t)}}function IB(e,t){if(t instanceof la)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof Tn)return{command:e,exitCode:65,data:{builderReadiness:{ready:!1,missingIds:t.missingIds,incompleteIds:t.incompleteIds}},error:{code:"invalid-data",message:t.message}};if(t instanceof mo)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof X)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Yu)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof Xu)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Tu)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof bs)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof ai)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof $u)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof Ku)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Hs)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function sn(e,t){let r=IB(e,t),i=r.error;if(!i)return r;let n=CE({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function TB(e,t,r=!1){let i=e.envelope??RE(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:hE(e.data,e.executionCwd),...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
390
+ `}:e.error?{exitCode:e.exitCode,stderr:i?gE(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:vE(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==OE(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
391
+ ${jr.details}
307
392
  ${JSON.stringify(e.data,null,2)}
308
- `}:{exitCode:e.exitCode,stdout:e.text}}function y0(e,t,r=!1){let i=w0(e,t,r),n=!1;if(i.stdout?.trim())try{let a=JSON.parse(i.stdout);n=!!a&&typeof a=="object"&&!Array.isArray(a)}catch{n=!1}return{output:i,structuredDataVisible:n}}function $k(e,t,r=!1){return y0(e,t,r).output}var N0=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function b0(e){let t=yr(e,"--expected-state-version"),r=yr(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new X("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new X("--expected-state-version must be a positive integer");if(!N0.has(r))throw new X("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function Nr(e,t,r,i,n){let a=await ih({paths:e,name:t.name});a.local&&(r??=QN(t,a.local),i===void 0&&(i=Sb(a.local,a.local.workspace.projectRoot)));let o=await je({paths:e,state:t}),s=o?.confirmed?await O(e,t.name,{diagnostics:!0}):null,c=s?.children.flatMap(({task:f})=>f?[f.child]:[])??[],l=s?.integration.checkExecution,u=l?.status==="interrupted"?(l.checkStates??[]).filter(({status:f})=>f==="interrupted").map(({id:f})=>f):void 0;return{...o?{childSummary:o.children.reduce((f,d)=>({...f,[d.status]:(f[d.status]??0)+1}),{total:o.children.length}),readyChildren:c.length>0?c:o.readyChildren}:{},continuation:K(t,o,{verifierExecutionRef:r,verificationCheckPlans:i,retryCheckIds:n,supervisorIntegrationRetryIds:u})}}function k0(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"&&t!=="continuationCheckPlans"&&t!=="continuationRetryCheckIds"))}function Ok(e){return{action:e.action,reason:e.reason,message:e.message}}async function Dk(e,t){let r=Ak(e,"change name"),i=yr(e,"--summary"),n=yr(e,"--runner-input"),a=jt(e,"--validate-only"),o=jt(e,"--confirmed"),s=jt(e,"--accept-result"),c=jt(e,"--revise-implementation"),l=jt(e,"--revise-requirements"),u=jt(e,"--retry-verifier"),f=jt(e,"--resolve-verifier-blocker"),d=yr(e,"--coordination-mode"),p=d;if(d!==void 0&&!Nc.includes(d))throw new X("--coordination-mode must be multi-session or single-session");if(a&&n===void 0)throw new X("--validate-only requires --runner-input");let m=yr(e,"--max-parallel"),h=m===void 0?2:Number(m);if(!Number.isSafeInteger(h)||h<1)throw new X("--max-parallel must be a positive integer");let g=b0(e);if([o,s,c,l,u,f].filter(Boolean).length>1)throw new X("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");if(p!==void 0&&(o||s||c||l||u||f||n!==void 0))throw new X("--coordination-mode is only valid when preparing a Supervisor Shape confirmation");_k(e);let v=await Tk(t),w=await zb(v.paths,r);if(!await $n(v.paths,r)){if(w){let H={schema:"comet.native.continuation.v2",skill:"comet-native",change:r,phase:"archive",status:"blocked",disposition:"blocked",action:"archive",commandArgs:w.result?.recoveryArgs??["comet","native","archive",r,"--confirmed"],requiredInputs:[],inputOptions:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0},userCommunication:{required:!0,message:w.result?.message??"Native Archive completed, but workspace finish is still pending.",suggestedReply:"Retry workspace finish",agentInstruction:"Retry the recorded Native workspace finish command after resolving the Git blocker; do not treat this change as complete until it succeeds."}};return{command:"next",exitCode:73,data:{change:r,archived:!0,workspaceFinishResult:w.result,continuation:H},error:{code:"conflict",message:w.result?.message??"Native Archive completed, but workspace finish is still pending"}}}if(n)throw new X("--runner-input is only valid for portable Native changes");if(!i)throw new X("--summary is required");let C=await Zb({paths:v.paths,name:r});return Ze("next",{state:xe(C,v.paths),migration:{completed:!0,summary:i},continuation:K(C)})}let y=await $(v.paths,r);if(a){if(i||o||s||c||l||u||f||g||p!==void 0)throw new X("--validate-only cannot be combined with --summary, continuation expectations, or coordination mode");let C;try{C=await Hh(n,t)}catch(H){return{...Wn("next",H),data:{state:xe(y,v.paths),continuation:K(y)}}}try{await Dh({paths:v.paths,name:r,state:y,input:C,projectRoot:t})}catch(H){return{...Wn("next",H),data:{state:xe(y,v.paths),continuation:K(y)}}}return Ze("next",{validation:{valid:!0,kind:C.kind},state:xe(y,v.paths),continuation:K(y)})}if(n!==void 0||!i||y.phase==="verify"||y.phase==="archive"||y.verification_result==="pass"){let C=Ah(v.paths,y);if(C)return Hk(v.paths,y,r,C)}if(n){if(i||o||s||c||l||u||f||p!==void 0||g)throw new X("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let C;try{C=await Hh(n,t),await Dh({paths:v.paths,name:r,state:y,input:C,projectRoot:t}),y.document_constraints_version===1&&await Gl({paths:v.paths,state:y})}catch(Ce){return{...Wn("next",Ce),data:{state:xe(y,v.paths),continuation:K(y)}}}let H=await ru({paths:v.paths,name:r});if(H.action==="rerun-final-verification")return Ze("next",{state:xe(H.state,v.paths),...await Nr(v.paths,H.state)});let P=await Ih({paths:v.paths,name:r,preserveRunningExecution:!0}),W=P.state;if(P.action==="await-user"||P.action==="done"||P.reason!=="available")return Ze("next",{state:xe(W,v.paths),recovery:Ok(P),...await Nr(v.paths,W)});if(W.phase==="build"){let Ce=await Bo({paths:v.paths,state:W});if(Ce.drifted){let zn=await Lo({paths:v.paths,name:r,reason:Ce.reason??"Native confirmed requirements changed",keepFailureBudget:!0});return Ze("next",{state:xe(zn,v.paths),...await Nr(v.paths,zn)})}let Zt=await O(v.paths,r),et=await je({paths:v.paths,state:W});if(et&&!et.allDone&&!Zt)throw new X("Native parent Build advances child changes and does not accept a Builder handoff")}let ue=await fk({paths:v.paths,name:r,input:C,maxVerifyFailures:v.config.native.max_verify_failures}),$t="continuationCheckPlans"in ue?ue.continuationCheckPlans:void 0,ri="continuationRetryCheckIds"in ue?ue.continuationRetryCheckIds:void 0;return Ze("next",{...k0(ue),state:xe(ue.state,v.paths),...await Nr(v.paths,ue.state,ue.verifierDispatch?.verifierExecutionRef,$t,ri),coordination:Ne})}if(!i)throw new X("--summary is required");let S=await ru({paths:v.paths,name:r});if(S.action==="rerun-final-verification")return Ze("next",{state:xe(S.state,v.paths),...await Nr(v.paths,S.state)});let N=await Ih({paths:v.paths,name:r}),x=N.state;if(N.reason==="workspace-mismatch")return Hk(v.paths,x,r,N.message);if(p!==void 0&&x.phase!=="shape")throw new X("--coordination-mode is only valid when confirming Shape");let k,E=null;if(o)if(x.phase==="shape"&&x.status==="await-user"&&x.loop.next_action==="confirm-shape"){if(!g)throw new X("--expected-state-version and --expected-action are required for Shape confirmation");k=await wh({paths:v.paths,name:r,expectedContinuation:g})}else{if(x.phase==="shape")throw new X("--confirmed is only valid from the persisted Shape user confirmation boundary");if(x.phase==="verify"&&x.status==="await-user"&&x.loop.next_action==="confirm-verifier-unavailable")k=await xh({paths:v.paths,name:r,summary:i,expectedContinuation:g});else throw new X("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(s){if(!g&&(x.phase!=="verify"||x.status!=="await-user"||x.loop.next_action!=="confirm-skill-coordinated-pass"))throw new X("--accept-result is only valid for a pending Verify pass decision");k=await Ph({paths:v.paths,name:r,expectedContinuation:g})}else if(c){if(x.phase!=="verify")throw new X("--revise-implementation is only valid from Verify");k=await Hi({paths:v.paths,name:r,reason:i,expectedContinuation:g})}else if(l){if(!g&&x.phase!=="verify"&&x.phase!=="archive")throw new X("--revise-requirements is only valid from Verify or Archive");k=await Lo({paths:v.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:g})}else if(u)k=await Rh({paths:v.paths,name:r,expectedContinuation:g});else if(f)k=await Ch({paths:v.paths,name:r,reason:i,expectedContinuation:g});else{if(N.reason!=="available"){let W=((await je({paths:v.paths,state:x}))?.confirmed?await O(v.paths,x.name,{diagnostics:!0}):null)?.children.flatMap(({task:ue})=>ue?[Lr(ue,x.name,v.paths.projectRoot)]:[])??[];return Ze("next",{state:xe(x,v.paths),recovery:Ok(N),...await Nr(v.paths,x),...W.length>0?{supervisorTasks:W}:{}})}if(x.phase==="build"){let H=await Bo({paths:v.paths,state:x});if(H.drifted)k=await Lo({paths:v.paths,name:r,reason:H.reason??"Native confirmed requirements changed",keepFailureBudget:!0});else{let P=await je({paths:v.paths,state:x});if(P){let W=P,ue=[],$t=[],ri=null,Ce=await O(v.paths,r);if(Ce&&!P.allDone){let Zt=await Up({paths:v.paths,parent:r,maxParallel:x.coordination_mode==="single-session"?1:h});ue=Zt.state.children.flatMap(({task:et})=>et?[Lr(et,r,v.paths.projectRoot)]:[]),ri=Zt.tasks.map(({child:et})=>et),$t=Zt.state.children.flatMap(({name:et,blocker:zn})=>zn?[{child:et,message:zn}]:[]),(ue.length>0||Zt.state.stateVersion!==Ce.stateVersion)&&(W=await je({paths:v.paths,state:x})??W)}if(W.allDone&&!(x.loop.stage==="repairing"&&x.verification_result==="fail"))E=await Go({paths:v.paths,name:r,trigger:"recovery"}),k=E.state;else return Ze("next",{state:xe(x,v.paths),childSummary:W.children.reduce((Zt,et)=>({...Zt,[et.status]:(Zt[et.status]??0)+1}),{total:W.children.length}),readyChildren:ri??W.readyChildren,...ue.length>0?{supervisorTasks:ue}:{},...$t.length>0?{supervisorBlockers:$t}:{},continuation:K(x,W)})}}}if(x.phase==="shape"&&(k=await ph({paths:v.paths,name:r,enforceDocumentConstraints:!0,...p===void 0?{}:{coordinationMode:p},expectedContinuation:g})),k)return Ze("next",{state:xe(k,v.paths),...E?{parentAdvance:E.parentAdvance}:{},...await Nr(v.paths,k)});let C=x.phase==="shape"?await je({paths:v.paths,state:x}):null;return{command:"next",exitCode:65,data:{state:xe(x,v.paths),continuation:K(x,C)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return Ze("next",{state:xe(k,v.paths),...p===void 0?{}:{coordinationMode:p},...await Nr(v.paths,k)})}async function Hk(e,t,r,i){let n=K(t),a=t.language==="zh-CN"?`先恢复此需求绑定的工作区和分支,再运行 comet native status ${r} --json 获取下一步;当前操作未推进状态,不要重复请求验收确认。`:`Restore the workspace and branch bound to this change, then run comet native status ${r} --json for the next action. No transition occurred; do not request acceptance again.`;return Ze("next",{state:xe(t,e),...await Nr(e,t),recovery:{action:"await-user",reason:"workspace-mismatch",message:i},continuation:{...n,disposition:"blocked",requiresUserDecision:!1,action:"repair",commandArgs:null,commandAlternatives:[],requiredInputs:[],inputOptions:[],runnerAction:{...n.runnerAction,kind:"none"},userCommunication:{required:!0,message:`${i}. ${a}`,suggestedReply:null,agentInstruction:a}}})}async function Bk(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{jt(n,"--json"),jt(n,"--verbose"),c=yr(n,"--project-root");let f=[...n,...a],d=await Ik(c);l={executionCwd:d,...await t(f,d)}}catch(f){l=Wn(e,f)}let u=$k(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
393
+ `}:{exitCode:e.exitCode,stdout:e.text}}function $B(e,t,r=!1){let i=TB(e,t,r),n=!1;if(i.stdout?.trim())try{let a=JSON.parse(i.stdout);n=!!a&&typeof a=="object"&&!Array.isArray(a)}catch{n=!1}return{output:i,structuredDataVisible:n}}function HE(e,t,r=!1){return $B(e,t,r).output}var jB=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function OB(e){let t=dr(e,"--expected-state-version"),r=dr(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new X("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new X("--expected-state-version must be a positive integer");if(!jB.has(r))throw new X("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function pr(e,t,r,i,n){let a=await tm({paths:e,name:t.name});a.local&&(r??=Qh(t,a.local),i===void 0&&(i=yS(a.local,a.local.workspace.projectRoot)));let o=await Le({paths:e,state:t}),s=o?.confirmed?await D(e,t.name,{diagnostics:!0}):null,c=s?.children.flatMap(({task:p})=>p?[p.child]:[])??[],l=s?.integration.checkExecution,u=l?.status==="interrupted"?(l.checkStates??[]).filter(({status:p})=>p==="interrupted").map(({id:p})=>p):void 0;return{...o?{childSummary:o.children.reduce((p,d)=>({...p,[d.status]:(p[d.status]??0)+1}),{total:o.children.length}),readyChildren:c.length>0?c:o.readyChildren}:{},continuation:Y(t,o,{verifierExecutionRef:r,verifierStartup:jk(t,a.localStatus==="available"?a.local:null),verificationCheckPlans:i,retryCheckIds:n,supervisorIntegrationRetryIds:u})}}function HB(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"&&t!=="continuationCheckPlans"&&t!=="continuationRetryCheckIds"))}function DE(e){return{action:e.action,reason:e.reason,message:e.message}}async function LE(e,t){let r=IE(e,"change name"),i=dr(e,"--summary"),n=dr(e,"--runner-input"),a=Vt(e,"--validate-only"),o=Vt(e,"--confirmed"),s=Vt(e,"--accept-result"),c=dr(e,"--finish");if(c!==void 0&&(!s||!["keep","merge","push","pull-request"].includes(c)))throw new X("--finish requires --accept-result and must be keep, merge, push, or pull-request");let l=Vt(e,"--revise-implementation"),u=Vt(e,"--revise-requirements"),p=Vt(e,"--retry-verifier"),d=Vt(e,"--resolve-verifier-blocker"),f=dr(e,"--coordination-mode"),h=f;if(f!==void 0&&!ol.includes(f))throw new X("--coordination-mode must be multi-session or single-session");if(a&&n===void 0)throw new X("--validate-only requires --runner-input");let m=dr(e,"--max-parallel"),v=m===void 0?2:Number(m);if(!Number.isSafeInteger(v)||v<1)throw new X("--max-parallel must be a positive integer");let g=OB(e);if([o,s,l,u,p,d].filter(Boolean).length>1)throw new X("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");if(h!==void 0&&(s||l||u||p||d||n!==void 0))throw new X("--coordination-mode is only valid when preparing or confirming a Supervisor Shape");AE(e);let w=await jE(t),N=await zS(w.paths,r);if(!await aa(w.paths,r)){if(N){let _={schema:"comet.native.continuation.v2",skill:"comet-native",change:r,phase:"archive",status:"blocked",disposition:"blocked",requiresUserDecision:!1,action:"archive",commandArgs:N.result?.recoveryArgs??["comet","native","archive",r,"--confirmed"],requiredInputs:[],inputOptions:[],runnerAction:{kind:"none",candidateId:null,iteration:0,attempt:0},userCommunication:{required:!0,message:N.result?.message??"Native Archive completed, but workspace finish is still pending.",suggestedReply:null,agentInstruction:"Report the blocker and resolve it within the recorded delivery authorization, then retry the recorded command. Ask only if new information or authorization is needed; a retry of the same finish does not need another confirmation."}};return{command:"next",exitCode:73,data:{change:r,archived:!0,workspaceFinishResult:N.result,continuation:_},error:{code:"conflict",message:N.result?.message??"Native Archive completed, but workspace finish is still pending"}}}if(n)throw new X("--runner-input is only valid for portable Native changes");if(!i)throw new X("--summary is required");let P=await ZS({paths:w.paths,name:r});return et("next",{state:Pe(P,w.paths),migration:{completed:!0,summary:i},continuation:Y(P)})}let y=await H(w.paths,r);if(a){if(i||o||s||l||u||p||d||g||h!==void 0)throw new X("--validate-only cannot be combined with --summary, continuation expectations, or coordination mode");let P;try{P=await Qm(n,t)}catch(_){let j=sn("next",_);return{...j,data:{...j.data&&typeof j.data=="object"?j.data:{},state:Pe(y,w.paths),continuation:Y(y)}}}try{await ev({paths:w.paths,name:r,state:y,input:P,projectRoot:t})}catch(_){let j=sn("next",_);return{...j,data:{...j.data&&typeof j.data=="object"?j.data:{},state:Pe(y,w.paths),continuation:Y(y)}}}return et("next",{validation:{valid:!0,kind:P.kind},state:Pe(y,w.paths),continuation:Y(y)})}if(n!==void 0||!i||y.phase==="verify"||y.phase==="archive"||y.verification_result==="pass"){let P=Gm(w.paths,y);if(P)return BE(w.paths,y,r,P)}if(n){if(i||o||s||l||u||p||d||h!==void 0||g)throw new X("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let P;try{P=await Qm(n,t),await Zm({paths:w.paths,file:n,input:P}),await ev({paths:w.paths,name:r,state:y,input:P,projectRoot:t}),y.document_constraints_version===1&&await Hu({paths:w.paths,state:y})}catch(fr){let _e=sn("next",fr);return{..._e,data:{..._e.data&&typeof _e.data=="object"?_e.data:{},state:Pe(y,w.paths),continuation:Y(y)}}}let _=await Wu({paths:w.paths,name:r});if(_.action==="rerun-final-verification")return et("next",{state:Pe(_.state,w.paths),...await pr(w.paths,_.state)});let j=await Jm({paths:w.paths,name:r,preserveRunningExecution:!0}),ue=j.state;if(j.action==="await-user"||j.action==="done"||j.reason!=="available")return et("next",{state:Pe(ue,w.paths),recovery:DE(j),...await pr(w.paths,ue)});if(ue.phase==="build"){let fr=await Es({paths:w.paths,state:ue});if(fr.drifted){let wa=await xs({paths:w.paths,name:r,reason:fr.reason??"Native confirmed requirements changed",keepFailureBudget:!0});return et("next",{state:Pe(wa,w.paths),...await pr(w.paths,wa)})}let _e=await D(w.paths,r),Ae=await Le({paths:w.paths,state:ue});if(Ae&&!Ae.allDone&&!_e)throw new X("Native parent Build advances child changes and does not accept a Builder handoff")}let de;try{de=await fE({paths:w.paths,name:r,input:P,inputFile:n,maxVerifyFailures:w.config.native.max_verify_failures})}catch(fr){let _e=await H(w.paths,r),Ae=sn("next",fr);return{...Ae,data:{...Ae.data&&typeof Ae.data=="object"?Ae.data:{},state:Pe(_e,w.paths),...await pr(w.paths,_e)}}}let Or="continuationCheckPlans"in de?de.continuationCheckPlans:void 0,tt="continuationRetryCheckIds"in de?de.continuationRetryCheckIds:void 0;return et("next",{...HB(de),state:Pe(de.state,w.paths),...await pr(w.paths,de.state,de.verifierDispatch?.verifierExecutionRef,Or,tt),coordination:Se})}if(!i)throw new X("--summary is required");let b=await Wu({paths:w.paths,name:r});if(b.action==="rerun-final-verification")return et("next",{state:Pe(b.state,w.paths),...await pr(w.paths,b.state)});let x=await Jm({paths:w.paths,name:r}),k=x.state;if(x.reason==="workspace-mismatch")return BE(w.paths,k,r,x.message);if(h!==void 0&&k.phase!=="shape")throw new X("--coordination-mode is only valid when confirming Shape");let S,C=null;if(o)if(k.phase==="shape"&&k.status==="await-user"&&k.loop.next_action==="confirm-shape"){if(!g)throw new X("--expected-state-version and --expected-action are required for Shape confirmation");S=await jm({paths:w.paths,name:r,expectedContinuation:g,...h===void 0?{}:{coordinationMode:h}})}else{if(k.phase==="shape")throw new X("--confirmed is only valid from the persisted Shape user confirmation boundary");if(k.phase==="verify"&&k.status==="await-user"&&k.loop.next_action==="confirm-verifier-unavailable")S=await qm({paths:w.paths,name:r,summary:i,expectedContinuation:g});else throw new X("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(s){if(!g&&(k.phase!=="verify"||k.status!=="await-user"||k.loop.next_action!=="confirm-skill-coordinated-pass"))throw new X("--accept-result is only valid for a pending Verify pass decision");S=await Wm({paths:w.paths,name:r,expectedContinuation:g,finish:c})}else if(l){if(k.phase!=="verify")throw new X("--revise-implementation is only valid from Verify");S=await an({paths:w.paths,name:r,reason:i,expectedContinuation:g})}else if(u){if(!g&&k.phase!=="verify"&&k.phase!=="archive")throw new X("--revise-requirements is only valid from Verify or Archive");S=await xs({paths:w.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:g})}else if(p)S=await Vm({paths:w.paths,name:r,expectedContinuation:g});else if(d)S=await Mm({paths:w.paths,name:r,reason:i,expectedContinuation:g});else{if(x.reason!=="available"){let ue=((await Le({paths:w.paths,state:k}))?.confirmed?await D(w.paths,k.name,{diagnostics:!0}):null)?.children.flatMap(({task:de})=>de?[ri(de,k.name,w.paths.projectRoot)]:[])??[];return et("next",{state:Pe(k,w.paths),recovery:DE(x),...await pr(w.paths,k),...ue.length>0?{supervisorTasks:ue}:{}})}if(k.phase==="build"){let _=await Es({paths:w.paths,state:k});if(_.drifted)S=await xs({paths:w.paths,name:r,reason:_.reason??"Native confirmed requirements changed",keepFailureBudget:!0});else{let j=await Le({paths:w.paths,state:k});if(j){let ue=j,de=[],Or=[],tt=null,fr=await D(w.paths,r);if(fr&&!j.allDone){let _e=await Vh({paths:w.paths,parent:r,maxParallel:k.coordination_mode==="single-session"?1:v});de=_e.state.children.flatMap(({task:Ae})=>Ae?[ri(Ae,r,w.paths.projectRoot)]:[]),tt=_e.tasks.map(({child:Ae})=>Ae),Or=_e.state.children.flatMap(({name:Ae,blocker:wa})=>wa?[{child:Ae,message:wa}]:[]),(de.length>0||_e.state.stateVersion!==fr.stateVersion)&&(ue=await Le({paths:w.paths,state:k})??ue)}if(ue.allDone&&!(k.loop.stage==="repairing"&&k.verification_result==="fail"))C=await Ts({paths:w.paths,name:r,trigger:"recovery"}),S=C.state;else return et("next",{state:Pe(k,w.paths),childSummary:ue.children.reduce((_e,Ae)=>({..._e,[Ae.status]:(_e[Ae.status]??0)+1}),{total:ue.children.length}),readyChildren:tt??ue.readyChildren,...de.length>0?{supervisorTasks:de}:{},...Or.length>0?{supervisorBlockers:Or}:{},continuation:Y(k,ue)})}}}if(k.phase==="shape"&&(S=await xm({paths:w.paths,name:r,enforceDocumentConstraints:!0,...h===void 0?{}:{coordinationMode:h},expectedContinuation:g})),S)return et("next",{state:Pe(S,w.paths),...C?{parentAdvance:C.parentAdvance}:{},...await pr(w.paths,S)});let P=k.phase==="shape"?await Le({paths:w.paths,state:k}):null;return et("next",{state:Pe(k,w.paths),continuation:Y(k,P)})}return et("next",{state:Pe(S,w.paths),...h===void 0?{}:{coordinationMode:h},...await pr(w.paths,S)})}async function BE(e,t,r,i){let n=Y(t),a=t.language==="zh-CN"?`先恢复此需求绑定的工作区和分支,再运行 comet native status ${r} --json 获取下一步;当前操作未推进状态,不要重复请求验收确认。`:`Restore the workspace and branch bound to this change, then run comet native status ${r} --json for the next action. No transition occurred; do not request acceptance again.`;return et("next",{state:Pe(t,e),...await pr(e,t),recovery:{action:"await-user",reason:"workspace-mismatch",message:i},continuation:{...n,disposition:"blocked",requiresUserDecision:!1,action:"repair",commandArgs:null,commandAlternatives:[],requiredInputs:[],inputOptions:[],runnerAction:{...n.runnerAction,kind:"none"},userCommunication:{required:!0,message:`${i}. ${a}`,suggestedReply:null,agentInstruction:a}}})}async function FE(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Vt(n,"--json"),Vt(n,"--verbose"),c=dr(n,"--project-root");let p=[...n,...a],d=async()=>{let f=await TE(c);return{executionCwd:f,...await t(p,f)}};l=$E(e,p)?await Zw(d):await d()}catch(p){l=sn(e,p)}let u=HE(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
309
394
  `)?"":`
310
- `)),u.exitCode}process.exitCode=await Bk("next",Dk);
395
+ `)),u.exitCode}process.exitCode=await FE("next",LE);