@punks/cli 3.1.1-beta.0 → 3.1.1

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 (698) hide show
  1. package/README.md +2 -0
  2. package/dist/CHANGELOG.md +30 -1
  3. package/dist/index.js +8 -8
  4. package/dist/tsconfig.tsbuildinfo +1 -1
  5. package/package.json +49 -9
  6. package/dist/baseline/scaffold-baseline/baseline.json +0 -12
  7. package/dist/baseline/scaffold-baseline/data/catalog/hooks.json +0 -16
  8. package/dist/baseline/scaffold-baseline/data/catalog/lint-assets.json +0 -208
  9. package/dist/baseline/scaffold-baseline/data/catalog/packs.json +0 -617
  10. package/dist/baseline/scaffold-baseline/data/catalog/skills.json +0 -756
  11. package/dist/baseline/scaffold-baseline/data/catalog/tools.json +0 -91
  12. package/dist/baseline/scaffold-baseline/data/hooks/format-edited-file.mjs +0 -719
  13. package/dist/baseline/scaffold-baseline/data/hooks/scaffold-update-check.mjs +0 -234
  14. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/adapters/claude.d.mts +0 -3
  15. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/adapters/claude.mjs +0 -124
  16. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/adapters/claude.test.ts +0 -130
  17. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/adapters/codex.d.mts +0 -3
  18. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/adapters/codex.mjs +0 -137
  19. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/adapters/codex.test.ts +0 -135
  20. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/adapters/cursor.d.mts +0 -5
  21. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/adapters/cursor.mjs +0 -106
  22. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/adapters/cursor.test.ts +0 -138
  23. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/adapters/opencode.d.mts +0 -5
  24. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/adapters/opencode.mjs +0 -100
  25. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/adapters/opencode.test.ts +0 -123
  26. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/apply.d.mts +0 -12
  27. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/apply.mjs +0 -96
  28. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/contract.test.ts +0 -875
  29. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/contract.ts +0 -206
  30. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/core.d.mts +0 -8
  31. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/core.mjs +0 -239
  32. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/application-context-plan.json +0 -27
  33. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/claude/actions.json +0 -109
  34. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/claude/context-plan.json +0 -150
  35. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/claude/matrix.json +0 -23
  36. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/claude/traces.json +0 -15
  37. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/codex/actions.json +0 -124
  38. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/codex/context-plan.json +0 -150
  39. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/codex/matrix.json +0 -23
  40. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/codex/traces.json +0 -15
  41. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/cursor/compiler-input.json +0 -93
  42. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/cursor/context-plan.json +0 -108
  43. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/cursor/matrix.json +0 -19
  44. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/cursor/projection.json +0 -54
  45. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/mixed-context-plan.json +0 -35
  46. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/opencode/compiler-input.json +0 -93
  47. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/opencode/context-plan.json +0 -108
  48. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/opencode/matrix.json +0 -19
  49. package/dist/baseline/scaffold-baseline/data/scripts/harness-projection/test-fixtures/opencode/projection.json +0 -51
  50. package/dist/baseline/scaffold-baseline/data/scripts/sync-subagents.mjs +0 -1665
  51. package/dist/baseline/scaffold-baseline/data/scripts/sync-subagents.test.ts +0 -1893
  52. package/dist/baseline/scaffold-baseline/data/subagents/manifest.mjs +0 -487
  53. package/dist/baseline/scaffold-baseline/data/subagents/manifest.test.ts +0 -56
  54. package/dist/baseline/scaffold-baseline/skills/agnostic/backend/backend-domain-structure/SKILL.md +0 -62
  55. package/dist/baseline/scaffold-baseline/skills/agnostic/backend/backend-domain-structure/agents/openai.yaml +0 -4
  56. package/dist/baseline/scaffold-baseline/skills/agnostic/backend/backend-domain-structure/references/layout.md +0 -225
  57. package/dist/baseline/scaffold-baseline/skills/agnostic/backend/backend-recoverable-actions/SKILL.md +0 -49
  58. package/dist/baseline/scaffold-baseline/skills/agnostic/backend/backend-recoverable-actions/agents/openai.yaml +0 -4
  59. package/dist/baseline/scaffold-baseline/skills/agnostic/backend/backend-recoverable-actions/references/strategy-matrix.md +0 -34
  60. package/dist/baseline/scaffold-baseline/skills/agnostic/backend/backend-recoverable-actions/references/test-matrix.md +0 -34
  61. package/dist/baseline/scaffold-baseline/skills/agnostic/backend/logging-best-practices/SKILL.md +0 -127
  62. package/dist/baseline/scaffold-baseline/skills/agnostic/backend/logging-best-practices/rules/context.md +0 -157
  63. package/dist/baseline/scaffold-baseline/skills/agnostic/backend/logging-best-practices/rules/pitfalls.md +0 -118
  64. package/dist/baseline/scaffold-baseline/skills/agnostic/backend/logging-best-practices/rules/structure.md +0 -193
  65. package/dist/baseline/scaffold-baseline/skills/agnostic/backend/logging-best-practices/rules/wide-events.md +0 -113
  66. package/dist/baseline/scaffold-baseline/skills/agnostic/cli/hi-cli/SKILL.md +0 -37
  67. package/dist/baseline/scaffold-baseline/skills/agnostic/cli/hi-cli/references/commands.md +0 -77
  68. package/dist/baseline/scaffold-baseline/skills/agnostic/cli/hi-cli/references/post-command-flow.md +0 -127
  69. package/dist/baseline/scaffold-baseline/skills/agnostic/debug/debug-agent/SKILL.md +0 -184
  70. package/dist/baseline/scaffold-baseline/skills/agnostic/docs/docs-onboarding/SKILL.md +0 -46
  71. package/dist/baseline/scaffold-baseline/skills/agnostic/docs/docs-onboarding/agents/openai.yaml +0 -4
  72. package/dist/baseline/scaffold-baseline/skills/agnostic/docs/docs-onboarding/references/artifact-contract.md +0 -67
  73. package/dist/baseline/scaffold-baseline/skills/agnostic/docs/upstream/mattpocock-writing-skills.md +0 -41
  74. package/dist/baseline/scaffold-baseline/skills/agnostic/docs/writing-beats/SKILL.md +0 -69
  75. package/dist/baseline/scaffold-baseline/skills/agnostic/docs/writing-fragments/SKILL.md +0 -76
  76. package/dist/baseline/scaffold-baseline/skills/agnostic/docs/writing-great-skills/GLOSSARY.md +0 -69
  77. package/dist/baseline/scaffold-baseline/skills/agnostic/docs/writing-great-skills/SKILL.md +0 -61
  78. package/dist/baseline/scaffold-baseline/skills/agnostic/docs/writing-shape/SKILL.md +0 -75
  79. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/agent-browser/.clawdhub/origin.json +0 -7
  80. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/agent-browser/SKILL.md +0 -229
  81. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/agent-browser/references/authentication.md +0 -202
  82. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/agent-browser/references/commands.md +0 -259
  83. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/agent-browser/references/proxy-support.md +0 -188
  84. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/agent-browser/references/session-management.md +0 -193
  85. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/agent-browser/references/snapshot-refs.md +0 -194
  86. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/agent-browser/references/video-recording.md +0 -173
  87. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/agent-browser/templates/authenticated-session.sh +0 -97
  88. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/agent-browser/templates/capture-workflow.sh +0 -69
  89. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/agent-browser/templates/form-automation.sh +0 -62
  90. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/design-taste-frontend/SKILL.md +0 -1206
  91. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/frontend-domain-structure/SKILL.md +0 -55
  92. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/frontend-domain-structure/agents/openai.yaml +0 -4
  93. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/frontend-domain-structure/references/react/structure.md +0 -102
  94. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/frontend-domain-structure/references/structure.md +0 -257
  95. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/gpt-taste/SKILL.md +0 -74
  96. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/imagegen-frontend-mobile/SKILL.md +0 -1465
  97. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/imagegen-frontend-web/SKILL.md +0 -987
  98. package/dist/baseline/scaffold-baseline/skills/agnostic/frontend/redesign-existing-projects/SKILL.md +0 -178
  99. package/dist/baseline/scaffold-baseline/skills/agnostic/generic/handoff/SKILL.md +0 -15
  100. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/REFERENCE.md +0 -39
  101. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/SKILL.md +0 -92
  102. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/references/backlog-sync.md +0 -44
  103. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/references/grill-ambiguity.md +0 -66
  104. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/references/plan-schema.md +0 -112
  105. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/references/planner-task-graph.md +0 -42
  106. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/references/stop-conditions.md +0 -18
  107. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-plan/references/tdd-shaping.md +0 -49
  108. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-spec/SKILL.md +0 -109
  109. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-spec/assets/SPEC-TEMPLATE.md +0 -92
  110. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-spec/references/backlog-sync.md +0 -49
  111. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-spec/references/discovery.md +0 -54
  112. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-spec/references/folder-naming.md +0 -33
  113. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-spec/references/grill-phase.md +0 -42
  114. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-spec/references/questioning.md +0 -51
  115. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-spec/references/spec-quality-bar.md +0 -59
  116. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/create-spec/references/wiki-bookkeeping.md +0 -50
  117. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/SKILL.md +0 -105
  118. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/assets/IMPLEMENTATION-NOTES-TEMPLATE.md +0 -71
  119. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/lifecycle.md +0 -220
  120. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/parallel-orchestration.md +0 -107
  121. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/parallel-worker-brief.md +0 -86
  122. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/parallel.md +0 -56
  123. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/runtime-product-validation.md +0 -50
  124. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/sequential.md +0 -48
  125. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/implement-spec/references/ui-screenshot-evidence.md +0 -61
  126. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/stack/SKILL.md +0 -89
  127. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/swarm-planner/SKILL.md +0 -179
  128. package/dist/baseline/scaffold-baseline/skills/agnostic/planning/wayfinder/SKILL.md +0 -42
  129. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/autoreview/SKILL.md +0 -191
  130. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/autoreview/scripts/autoreview +0 -1176
  131. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/autoreview/scripts/test-review-harness +0 -176
  132. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/codebase-design/DEEPENING.md +0 -34
  133. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/codebase-design/DESIGN-IT-TWICE.md +0 -43
  134. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/codebase-design/SKILL.md +0 -60
  135. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/review/SKILL.md +0 -89
  136. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/simplify/SKILL.md +0 -14
  137. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/tdd/SKILL.md +0 -139
  138. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/tdd/deep-modules.md +0 -33
  139. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/tdd/high-signal-tests.md +0 -39
  140. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/tdd/interface-design.md +0 -31
  141. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/tdd/mocking.md +0 -59
  142. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/tdd/refactoring.md +0 -10
  143. package/dist/baseline/scaffold-baseline/skills/agnostic/quality/tdd/tests.md +0 -61
  144. package/dist/baseline/scaffold-baseline/skills/agnostic/repo-asset-management/SKILL.md +0 -28
  145. package/dist/baseline/scaffold-baseline/skills/agnostic/repo-asset-management/references/acceptance.md +0 -6
  146. package/dist/baseline/scaffold-baseline/skills/agnostic/repo-asset-management/references/azure.md +0 -11
  147. package/dist/baseline/scaffold-baseline/skills/agnostic/repo-asset-management/references/bitbucket.md +0 -8
  148. package/dist/baseline/scaffold-baseline/skills/agnostic/repo-asset-management/references/github.md +0 -11
  149. package/dist/baseline/scaffold-baseline/skills/agnostic/repo-asset-management/references/gitlab.md +0 -11
  150. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/grilling/LICENSE +0 -21
  151. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/grilling/SKILL.md +0 -14
  152. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/grilling/UPSTREAM.md +0 -16
  153. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/requirements-grill/SKILL.md +0 -44
  154. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/requirements-grill/references/artifact-output.md +0 -181
  155. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/requirements-grill/references/grilling-flow.md +0 -58
  156. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/requirements-grill/references/wiki-output.md +0 -101
  157. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/write-backlog/EXAMPLES.md +0 -89
  158. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/write-backlog/REFERENCE.md +0 -357
  159. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/write-backlog/SKILL.md +0 -103
  160. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/write-backlog/assets/concepts/backlog-model.md +0 -155
  161. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/write-backlog/assets/concepts/story-shape.md +0 -172
  162. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/write-backlog/assets/providers/azure-devops-create-payload.md +0 -129
  163. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/write-backlog/assets/providers/github-projects-create-payload.md +0 -280
  164. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/write-backlog/assets/providers/linear-create-payload.md +0 -114
  165. package/dist/baseline/scaffold-baseline/skills/agnostic/requirements/write-backlog/assets/providers/monday-create-payload.md +0 -220
  166. package/dist/baseline/scaffold-baseline/skills/agnostic/research/improve-codebase-architecture/REFERENCE.md +0 -78
  167. package/dist/baseline/scaffold-baseline/skills/agnostic/research/improve-codebase-architecture/SKILL.md +0 -80
  168. package/dist/baseline/scaffold-baseline/skills/agnostic/research/parallel-research/SKILL.md +0 -71
  169. package/dist/baseline/scaffold-baseline/skills/agnostic/research/parallel-research/agents/openai.yaml +0 -4
  170. package/dist/baseline/scaffold-baseline/skills/agnostic/research/prototype/LOGIC.md +0 -31
  171. package/dist/baseline/scaffold-baseline/skills/agnostic/research/prototype/SKILL.md +0 -31
  172. package/dist/baseline/scaffold-baseline/skills/agnostic/research/prototype/UI.md +0 -29
  173. package/dist/baseline/scaffold-baseline/skills/agnostic/security/audit-cicd-security/SKILL.md +0 -58
  174. package/dist/baseline/scaffold-baseline/skills/agnostic/security/audit-cicd-security/agents/openai.yaml +0 -4
  175. package/dist/baseline/scaffold-baseline/skills/agnostic/security/audit-cicd-security/references/argo-workflows.md +0 -25
  176. package/dist/baseline/scaffold-baseline/skills/agnostic/security/audit-cicd-security/references/azure-pipelines.md +0 -27
  177. package/dist/baseline/scaffold-baseline/skills/agnostic/security/audit-cicd-security/references/bitbucket-pipelines.md +0 -26
  178. package/dist/baseline/scaffold-baseline/skills/agnostic/security/audit-cicd-security/references/buildkite.md +0 -26
  179. package/dist/baseline/scaffold-baseline/skills/agnostic/security/audit-cicd-security/references/circleci.md +0 -25
  180. package/dist/baseline/scaffold-baseline/skills/agnostic/security/audit-cicd-security/references/github-actions.md +0 -24
  181. package/dist/baseline/scaffold-baseline/skills/agnostic/security/audit-cicd-security/references/gitlab-cicd.md +0 -27
  182. package/dist/baseline/scaffold-baseline/skills/agnostic/security/audit-cicd-security/references/jenkins.md +0 -26
  183. package/dist/baseline/scaffold-baseline/skills/agnostic/security/audit-cicd-security/references/tekton.md +0 -24
  184. package/dist/baseline/scaffold-baseline/skills/agnostic/security/security-best-practices/LICENSE.txt +0 -201
  185. package/dist/baseline/scaffold-baseline/skills/agnostic/security/security-best-practices/SKILL.md +0 -86
  186. package/dist/baseline/scaffold-baseline/skills/agnostic/security/security-best-practices/agents/openai.yaml +0 -4
  187. package/dist/baseline/scaffold-baseline/skills/agnostic/security/security-best-practices/references/golang-general-backend-security.md +0 -826
  188. package/dist/baseline/scaffold-baseline/skills/agnostic/security/security-best-practices/references/javascript-express-web-server-security.md +0 -1158
  189. package/dist/baseline/scaffold-baseline/skills/agnostic/security/security-best-practices/references/javascript-general-web-frontend-security.md +0 -747
  190. package/dist/baseline/scaffold-baseline/skills/agnostic/security/security-best-practices/references/javascript-jquery-web-frontend-security.md +0 -678
  191. package/dist/baseline/scaffold-baseline/skills/agnostic/security/security-best-practices/references/javascript-typescript-nextjs-web-server-security.md +0 -1144
  192. package/dist/baseline/scaffold-baseline/skills/agnostic/security/security-best-practices/references/javascript-typescript-react-web-frontend-security.md +0 -990
  193. package/dist/baseline/scaffold-baseline/skills/agnostic/security/security-best-practices/references/javascript-typescript-vue-web-frontend-security.md +0 -791
  194. package/dist/baseline/scaffold-baseline/skills/agnostic/security/security-best-practices/references/python-django-web-server-security.md +0 -882
  195. package/dist/baseline/scaffold-baseline/skills/agnostic/security/security-best-practices/references/python-fastapi-web-server-security.md +0 -1036
  196. package/dist/baseline/scaffold-baseline/skills/agnostic/security/security-best-practices/references/python-flask-web-server-security.md +0 -705
  197. package/dist/baseline/scaffold-baseline/skills/agnostic/subagents/swarm-planner/SKILL.md +0 -179
  198. package/dist/baseline/scaffold-baseline/skills/frameworks/better-auth/better-auth-best-practices/SKILL.md +0 -166
  199. package/dist/baseline/scaffold-baseline/skills/frameworks/better-auth/better-auth-security-best-practices/SKILL.MD +0 -432
  200. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect/LICENSE +0 -21
  201. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect/SKILL.md +0 -100
  202. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect/UPSTREAM.md +0 -11
  203. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect/references/CACHING.md +0 -76
  204. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect/references/CONFIG.md +0 -67
  205. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect/references/EFFECT_ATOM.md +0 -257
  206. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect/references/HTTP_CLIENTS.md +0 -101
  207. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect/references/OBSERVABILITY.md +0 -88
  208. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect/references/SCHEDULING.md +0 -135
  209. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect/references/SCHEMA.md +0 -130
  210. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect/references/SERVICES_LAYERS.md +0 -168
  211. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect/references/STREAMS.md +0 -135
  212. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect/references/TESTING.md +0 -118
  213. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect-backend-structure/SKILL.md +0 -95
  214. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect-backend-structure/agents/openai.yaml +0 -4
  215. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect-backend-structure/references/layout.md +0 -68
  216. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect-recoverable-actions/SKILL.md +0 -65
  217. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect-recoverable-actions/agents/openai.yaml +0 -4
  218. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect-recoverable-actions/references/flow-examples.md +0 -154
  219. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect-recoverable-actions/references/source-backed-primitives.md +0 -104
  220. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect-recoverable-actions/references/strategy-matrix.md +0 -34
  221. package/dist/baseline/scaffold-baseline/skills/frameworks/effect/effect-recoverable-actions/references/test-matrix.md +0 -36
  222. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/SKILL.md +0 -475
  223. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/examples/basic.ts +0 -9
  224. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/examples/body-parser.ts +0 -33
  225. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/examples/complex.ts +0 -112
  226. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/examples/cookie.ts +0 -45
  227. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/examples/error.ts +0 -38
  228. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/examples/file.ts +0 -10
  229. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/examples/guard.ts +0 -34
  230. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/examples/map-response.ts +0 -15
  231. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/examples/redirect.ts +0 -6
  232. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/examples/rename.ts +0 -32
  233. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/examples/schema.ts +0 -61
  234. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/examples/state.ts +0 -6
  235. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/examples/upload-file.ts +0 -20
  236. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/examples/websocket.ts +0 -25
  237. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/integrations/ai-sdk.md +0 -92
  238. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/integrations/astro.md +0 -59
  239. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/integrations/better-auth.md +0 -117
  240. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/integrations/cloudflare-worker.md +0 -95
  241. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/integrations/deno.md +0 -34
  242. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/integrations/drizzle.md +0 -258
  243. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/integrations/expo.md +0 -95
  244. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/integrations/nextjs.md +0 -103
  245. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/integrations/nodejs.md +0 -64
  246. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/integrations/nuxt.md +0 -67
  247. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/integrations/prisma.md +0 -93
  248. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/integrations/react-email.md +0 -134
  249. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/integrations/sveltekit.md +0 -53
  250. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/integrations/tanstack-start.md +0 -87
  251. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/integrations/vercel.md +0 -55
  252. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/patterns/mvc.md +0 -380
  253. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/plugins/bearer.md +0 -30
  254. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/plugins/cors.md +0 -141
  255. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/plugins/cron.md +0 -265
  256. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/plugins/graphql-apollo.md +0 -90
  257. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/plugins/graphql-yoga.md +0 -87
  258. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/plugins/html.md +0 -188
  259. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/plugins/jwt.md +0 -197
  260. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/plugins/openapi.md +0 -246
  261. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/plugins/opentelemetry.md +0 -167
  262. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/plugins/server-timing.md +0 -71
  263. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/plugins/static.md +0 -84
  264. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/references/bun-fullstack-dev-server.md +0 -129
  265. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/references/cookie.md +0 -187
  266. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/references/deployment.md +0 -413
  267. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/references/eden.md +0 -158
  268. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/references/lifecycle.md +0 -198
  269. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/references/macro.md +0 -83
  270. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/references/plugin.md +0 -207
  271. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/references/route.md +0 -331
  272. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/references/testing.md +0 -385
  273. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/references/validation.md +0 -491
  274. package/dist/baseline/scaffold-baseline/skills/frameworks/elysia/elysiajs/references/websocket.md +0 -250
  275. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/add-app-clip/SKILL.md +0 -280
  276. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/add-app-clip/agents/openai.yaml +0 -4
  277. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/add-app-clip/references/native-module.md +0 -96
  278. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/SKILL.md +0 -377
  279. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/agents/openai.yaml +0 -4
  280. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/references/animations.md +0 -220
  281. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/references/controls.md +0 -270
  282. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/references/form-sheet.md +0 -253
  283. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/references/gradients.md +0 -106
  284. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/references/icons.md +0 -213
  285. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/references/media.md +0 -198
  286. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/references/route-structure.md +0 -229
  287. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/references/search.md +0 -248
  288. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/references/storage.md +0 -121
  289. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/references/tabs.md +0 -433
  290. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/references/toolbar-and-headers.md +0 -284
  291. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/references/visual-effects.md +0 -197
  292. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/references/webgpu-three.md +0 -605
  293. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/building-native-ui/references/zoom-transitions.md +0 -158
  294. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/eas-simulator/SKILL.md +0 -154
  295. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/eas-simulator/references/controllers.md +0 -67
  296. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/eas-simulator/references/run-your-app.md +0 -185
  297. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/eas-simulator/references/troubleshooting.md +0 -38
  298. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/eas-update-insights/SKILL.md +0 -228
  299. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/eas-update-insights/agents/openai.yaml +0 -4
  300. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/eas-update-insights/references/channel-insights-schema.md +0 -47
  301. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/eas-update-insights/references/update-insights-schema.md +0 -69
  302. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-api-routes/SKILL.md +0 -368
  303. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-api-routes/agents/openai.yaml +0 -4
  304. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-brownfield/SKILL.md +0 -54
  305. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-brownfield/agents/openai.yaml +0 -4
  306. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-brownfield/references/brownfield-integrated.md +0 -526
  307. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-brownfield/references/brownfield-isolated.md +0 -402
  308. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-brownfield/references/comparison.md +0 -63
  309. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-brownfield/references/troubleshooting.md +0 -88
  310. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-cicd-workflows/SKILL.md +0 -92
  311. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-cicd-workflows/agents/openai.yaml +0 -4
  312. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-cicd-workflows/scripts/fetch.js +0 -109
  313. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-cicd-workflows/scripts/package.json +0 -11
  314. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-cicd-workflows/scripts/validate.js +0 -84
  315. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-deployment/SKILL.md +0 -167
  316. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-deployment/agents/openai.yaml +0 -4
  317. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-deployment/references/app-store-metadata.md +0 -497
  318. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-deployment/references/ios-app-store.md +0 -371
  319. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-deployment/references/play-store.md +0 -246
  320. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-deployment/references/testflight.md +0 -58
  321. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-deployment/references/workflows.md +0 -160
  322. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-dev-client/SKILL.md +0 -172
  323. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-dev-client/agents/openai.yaml +0 -4
  324. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-examples/SKILL.md +0 -97
  325. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-examples/references/catalog.md +0 -105
  326. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-module/SKILL.md +0 -141
  327. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-module/agents/openai.yaml +0 -4
  328. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-module/references/config-plugin.md +0 -90
  329. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-module/references/create-expo-module.md +0 -206
  330. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-module/references/lifecycle.md +0 -127
  331. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-module/references/module-config.md +0 -48
  332. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-module/references/native-module.md +0 -286
  333. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-module/references/native-view.md +0 -171
  334. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-observe/SKILL.md +0 -29
  335. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-observe/references/metrics.md +0 -47
  336. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-observe/references/queries.md +0 -342
  337. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-observe/references/setup.md +0 -255
  338. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-skill-eval/SKILL.md +0 -314
  339. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-skill-eval/agents/visual-grader.md +0 -52
  340. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-skill-eval/references/design-rubric.md +0 -45
  341. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-skill-eval/references/runtime-matrix.md +0 -33
  342. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-skill-eval/scripts/check-static.sh +0 -64
  343. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-skill-eval/scripts/clean-fixture.sh +0 -56
  344. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-skill-eval/scripts/generate_viewer.py +0 -450
  345. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-skill-eval/scripts/latest-sdk.sh +0 -46
  346. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-skill-eval/scripts/make-fixture.sh +0 -95
  347. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-skill-eval/scripts/make-workspace.sh +0 -31
  348. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-skill-eval/scripts/snapshot-android.sh +0 -284
  349. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-skill-eval/scripts/snapshot-ios.sh +0 -132
  350. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-skill-eval/scripts/snapshot-web.sh +0 -61
  351. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-tailwind-setup/SKILL.md +0 -480
  352. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-tailwind-setup/agents/openai.yaml +0 -4
  353. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-ui/SKILL.md +0 -47
  354. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-ui/agents/openai.yaml +0 -4
  355. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-ui/references/drop-in-replacements.md +0 -27
  356. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-ui/references/jetpack-compose.md +0 -73
  357. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-ui/references/swift-ui.md +0 -73
  358. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-ui/references/universal.md +0 -73
  359. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/expo-ui/scripts/list-components.js +0 -193
  360. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/native-data-fetching/SKILL.md +0 -505
  361. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/native-data-fetching/agents/openai.yaml +0 -4
  362. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/native-data-fetching/references/expo-router-loaders.md +0 -341
  363. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/upgrading-expo/SKILL.md +0 -134
  364. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/upgrading-expo/agents/openai.yaml +0 -4
  365. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/upgrading-expo/references/expo-av-to-audio.md +0 -132
  366. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/upgrading-expo/references/expo-av-to-video.md +0 -160
  367. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/upgrading-expo/references/native-tabs.md +0 -124
  368. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/upgrading-expo/references/new-architecture.md +0 -79
  369. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/upgrading-expo/references/react-19.md +0 -79
  370. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/upgrading-expo/references/react-compiler.md +0 -59
  371. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/upgrading-expo/references/react-navigation-to-expo-router.md +0 -61
  372. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/use-dom/SKILL.md +0 -417
  373. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/use-dom/agents/openai.yaml +0 -4
  374. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/web-to-native/SKILL.md +0 -83
  375. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/web-to-native/references/false-friends.md +0 -119
  376. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/web-to-native/references/native-patterns.md +0 -39
  377. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/web-to-native/references/run-as-goal.md +0 -48
  378. package/dist/baseline/scaffold-baseline/skills/frameworks/expo/web-to-native/references/verify-on-device.md +0 -45
  379. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/.github/workflows/branch-protection.yml +0 -24
  380. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/.github/workflows/deploy.yml +0 -61
  381. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/AGENTS.md +0 -5958
  382. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/SKILL.md +0 -130
  383. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/api-use-dto-serialization.md +0 -182
  384. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/api-use-interceptors.md +0 -202
  385. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/api-use-pipes.md +0 -205
  386. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/api-versioning.md +0 -191
  387. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/arch-avoid-circular-deps.md +0 -80
  388. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/arch-feature-modules.md +0 -82
  389. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/arch-module-sharing.md +0 -141
  390. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/arch-single-responsibility.md +0 -106
  391. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/arch-use-events.md +0 -108
  392. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/arch-use-repository-pattern.md +0 -97
  393. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/db-avoid-n-plus-one.md +0 -139
  394. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/db-use-migrations.md +0 -129
  395. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/db-use-transactions.md +0 -140
  396. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/devops-graceful-shutdown.md +0 -222
  397. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/devops-use-config-module.md +0 -167
  398. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/devops-use-logging.md +0 -232
  399. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/di-avoid-service-locator.md +0 -104
  400. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/di-interface-segregation.md +0 -165
  401. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/di-liskov-substitution.md +0 -221
  402. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/di-prefer-constructor-injection.md +0 -86
  403. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/di-scope-awareness.md +0 -94
  404. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/di-use-interfaces-tokens.md +0 -101
  405. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/error-handle-async-errors.md +0 -125
  406. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/error-throw-http-exceptions.md +0 -114
  407. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/error-use-exception-filters.md +0 -140
  408. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/micro-use-health-checks.md +0 -226
  409. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/micro-use-patterns.md +0 -167
  410. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/micro-use-queues.md +0 -252
  411. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/perf-async-hooks.md +0 -109
  412. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/perf-lazy-loading.md +0 -121
  413. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/perf-optimize-database.md +0 -131
  414. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/perf-use-caching.md +0 -128
  415. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/security-auth-jwt.md +0 -146
  416. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/security-rate-limiting.md +0 -125
  417. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/security-sanitize-output.md +0 -139
  418. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/security-use-guards.md +0 -135
  419. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/security-validate-all-input.md +0 -150
  420. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/test-e2e-supertest.md +0 -178
  421. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/test-mock-external-services.md +0 -179
  422. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/rules/test-use-testing-module.md +0 -153
  423. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/scripts/build-agents.ts +0 -299
  424. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/scripts/build.sh +0 -16
  425. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/scripts/package-lock.json +0 -237
  426. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-best-practices/scripts/package.json +0 -15
  427. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-expert/SKILL.md +0 -208
  428. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-expert/references/authentication.md +0 -166
  429. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-expert/references/controllers-routing.md +0 -111
  430. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-expert/references/dtos-validation.md +0 -153
  431. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-expert/references/migration-from-express.md +0 -1237
  432. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-expert/references/services-di.md +0 -140
  433. package/dist/baseline/scaffold-baseline/skills/frameworks/nestjs/nestjs-expert/references/testing-patterns.md +0 -186
  434. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/SKILL.md +0 -153
  435. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/async-patterns.md +0 -87
  436. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/bundling.md +0 -180
  437. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/data-patterns.md +0 -297
  438. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/debug-tricks.md +0 -105
  439. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/directives.md +0 -73
  440. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/error-handling.md +0 -227
  441. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/file-conventions.md +0 -140
  442. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/font.md +0 -245
  443. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/functions.md +0 -108
  444. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/hydration-error.md +0 -91
  445. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/image.md +0 -173
  446. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/metadata.md +0 -301
  447. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/parallel-routes.md +0 -287
  448. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/route-handlers.md +0 -146
  449. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/rsc-boundaries.md +0 -159
  450. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/runtime-selection.md +0 -39
  451. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/scripts.md +0 -141
  452. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/self-hosting.md +0 -371
  453. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-best-practices/suspense-boundaries.md +0 -67
  454. package/dist/baseline/scaffold-baseline/skills/frameworks/nextjs/next-cache-components/SKILL.md +0 -360
  455. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/package-usage/SKILL.md +0 -49
  456. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/package-usage/agents/openai.yaml +0 -4
  457. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/package-usage/use_cases.yaml +0 -15
  458. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/provider-upgrade/SKILL.md +0 -332
  459. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/provider-upgrade/agents/openai.yaml +0 -4
  460. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/provider-upgrade/references/diagnostic-toolbox.md +0 -131
  461. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/provider-upgrade/use_cases.yaml +0 -28
  462. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/pulumi-automation-api/SKILL.md +0 -320
  463. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/pulumi-automation-api/agents/openai.yaml +0 -4
  464. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/pulumi-automation-api/use_cases.yaml +0 -7
  465. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/pulumi-best-practices/SKILL.md +0 -501
  466. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/pulumi-best-practices/agents/openai.yaml +0 -4
  467. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/pulumi-best-practices/use_cases.yaml +0 -7
  468. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/pulumi-component/SKILL.md +0 -830
  469. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/pulumi-component/agents/openai.yaml +0 -4
  470. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/pulumi-component/use_cases.yaml +0 -19
  471. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/pulumi-esc/SKILL.md +0 -281
  472. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/pulumi-esc/agents/openai.yaml +0 -4
  473. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/pulumi-esc/use_cases.yaml +0 -30
  474. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/pulumi-overview/SKILL.md +0 -289
  475. package/dist/baseline/scaffold-baseline/skills/frameworks/pulumi/pulumi-overview/use_cases.yaml +0 -50
  476. package/dist/baseline/scaffold-baseline/skills/frameworks/react/async-react-patterns/SKILL.md +0 -78
  477. package/dist/baseline/scaffold-baseline/skills/frameworks/react/react-doctor/SKILL.md +0 -64
  478. package/dist/baseline/scaffold-baseline/skills/frameworks/react/react-doctor/references/explain.md +0 -71
  479. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-composition-patterns/AGENTS.md +0 -946
  480. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-composition-patterns/SKILL.md +0 -89
  481. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-composition-patterns/rules/architecture-avoid-boolean-props.md +0 -100
  482. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-composition-patterns/rules/architecture-compound-components.md +0 -112
  483. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-composition-patterns/rules/patterns-children-over-render-props.md +0 -87
  484. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-composition-patterns/rules/patterns-explicit-variants.md +0 -100
  485. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-composition-patterns/rules/react19-no-forwardref.md +0 -42
  486. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-composition-patterns/rules/state-context-interface.md +0 -191
  487. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-composition-patterns/rules/state-decouple-implementation.md +0 -113
  488. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-composition-patterns/rules/state-lift-state.md +0 -125
  489. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/AGENTS.md +0 -3750
  490. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/SKILL.md +0 -148
  491. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/advanced-effect-event-deps.md +0 -56
  492. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/advanced-event-handler-refs.md +0 -55
  493. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/advanced-init-once.md +0 -42
  494. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/advanced-use-latest.md +0 -39
  495. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/async-api-routes.md +0 -38
  496. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/async-cheap-condition-before-await.md +0 -37
  497. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/async-defer-await.md +0 -82
  498. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/async-dependencies.md +0 -51
  499. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/async-parallel.md +0 -28
  500. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/async-suspense-boundaries.md +0 -99
  501. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/bundle-barrel-imports.md +0 -60
  502. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/bundle-conditional.md +0 -31
  503. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/bundle-defer-third-party.md +0 -49
  504. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/bundle-dynamic-imports.md +0 -35
  505. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/bundle-preload.md +0 -50
  506. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/client-event-listeners.md +0 -74
  507. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/client-localstorage-schema.md +0 -71
  508. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/client-passive-event-listeners.md +0 -48
  509. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/client-swr-dedup.md +0 -56
  510. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/js-batch-dom-css.md +0 -107
  511. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/js-cache-function-results.md +0 -80
  512. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/js-cache-property-access.md +0 -28
  513. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/js-cache-storage.md +0 -70
  514. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/js-combine-iterations.md +0 -32
  515. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/js-early-exit.md +0 -50
  516. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/js-flatmap-filter.md +0 -60
  517. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/js-hoist-regexp.md +0 -45
  518. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/js-index-maps.md +0 -37
  519. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/js-length-check-first.md +0 -49
  520. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/js-min-max-loop.md +0 -82
  521. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/js-request-idle-callback.md +0 -105
  522. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/js-set-map-lookups.md +0 -24
  523. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/js-tosorted-immutable.md +0 -57
  524. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rendering-activity.md +0 -26
  525. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md +0 -47
  526. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rendering-conditional-render.md +0 -40
  527. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rendering-content-visibility.md +0 -38
  528. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rendering-hoist-jsx.md +0 -46
  529. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md +0 -82
  530. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md +0 -30
  531. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rendering-resource-hints.md +0 -85
  532. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rendering-script-defer-async.md +0 -68
  533. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rendering-svg-precision.md +0 -28
  534. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rendering-usetransition-loading.md +0 -75
  535. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rerender-defer-reads.md +0 -39
  536. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rerender-dependencies.md +0 -45
  537. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md +0 -40
  538. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rerender-derived-state.md +0 -29
  539. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rerender-functional-setstate.md +0 -74
  540. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rerender-lazy-state-init.md +0 -58
  541. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rerender-memo-with-default-value.md +0 -38
  542. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rerender-memo.md +0 -44
  543. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rerender-move-effect-to-event.md +0 -45
  544. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rerender-no-inline-components.md +0 -82
  545. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md +0 -35
  546. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rerender-split-combined-hooks.md +0 -64
  547. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rerender-transitions.md +0 -40
  548. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rerender-use-deferred-value.md +0 -59
  549. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md +0 -73
  550. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/server-after-nonblocking.md +0 -73
  551. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/server-auth-actions.md +0 -96
  552. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/server-cache-lru.md +0 -41
  553. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/server-cache-react.md +0 -76
  554. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/server-dedup-props.md +0 -65
  555. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/server-hoist-static-io.md +0 -149
  556. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/server-no-shared-module-state.md +0 -50
  557. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/server-parallel-fetching.md +0 -83
  558. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/server-parallel-nested-fetching.md +0 -34
  559. package/dist/baseline/scaffold-baseline/skills/frameworks/react/vercel-react-best-practices/rules/server-serialization.md +0 -38
  560. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/.claude-plugin/plugin.json +0 -12
  561. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/SKILL.md +0 -849
  562. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/assets/example-template.txt +0 -14
  563. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/references/best-practices.md +0 -304
  564. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/references/common-patterns.md +0 -271
  565. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/references/example-reference.md +0 -26
  566. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/references/testing.md +0 -282
  567. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/references/top-errors.md +0 -332
  568. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/references/typescript-patterns.md +0 -291
  569. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/references/v4-to-v5-migration.md +0 -231
  570. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/rules/tanstack-query.md +0 -126
  571. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/scripts/example-script.sh +0 -15
  572. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/templates/custom-hooks-pattern.tsx +0 -281
  573. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/templates/devtools-setup.tsx +0 -248
  574. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/templates/error-boundary.tsx +0 -243
  575. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/templates/package.json +0 -31
  576. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/templates/provider-setup.tsx +0 -50
  577. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/templates/query-client-config.ts +0 -72
  578. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/templates/use-infinite-query.tsx +0 -214
  579. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/templates/use-mutation-basic.tsx +0 -201
  580. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/templates/use-mutation-optimistic.tsx +0 -234
  581. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-query/tanstack-query/templates/use-query-basic.tsx +0 -119
  582. package/dist/baseline/scaffold-baseline/skills/frameworks/tanstack-start/tanstack-start/SKILL.md +0 -250
  583. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/.claude-plugin/plugin.json +0 -12
  584. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/SKILL.md +0 -1058
  585. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/assets/example-template.txt +0 -14
  586. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/references/best-practices.md +0 -304
  587. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/references/common-patterns.md +0 -271
  588. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/references/example-reference.md +0 -26
  589. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/references/testing.md +0 -282
  590. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/references/top-errors.md +0 -332
  591. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/references/typescript-patterns.md +0 -291
  592. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/references/v4-to-v5-migration.md +0 -231
  593. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/rules/tanstack-query.md +0 -126
  594. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/scripts/example-script.sh +0 -15
  595. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/templates/custom-hooks-pattern.tsx +0 -281
  596. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/templates/devtools-setup.tsx +0 -248
  597. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/templates/error-boundary.tsx +0 -243
  598. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/templates/package.json +0 -31
  599. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/templates/provider-setup.tsx +0 -50
  600. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/templates/query-client-config.ts +0 -72
  601. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/templates/use-infinite-query.tsx +0 -214
  602. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/templates/use-mutation-basic.tsx +0 -201
  603. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/templates/use-mutation-optimistic.tsx +0 -234
  604. package/dist/baseline/scaffold-baseline/skills/frameworks/trpc/tanstack-query/templates/use-query-basic.tsx +0 -119
  605. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/SKILL.md +0 -914
  606. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/command/turborepo.md +0 -70
  607. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/best-practices/RULE.md +0 -241
  608. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/best-practices/dependencies.md +0 -246
  609. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/best-practices/packages.md +0 -335
  610. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/best-practices/structure.md +0 -270
  611. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/boundaries/RULE.md +0 -126
  612. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/caching/RULE.md +0 -107
  613. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/caching/gotchas.md +0 -169
  614. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/caching/remote-cache.md +0 -127
  615. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/ci/RULE.md +0 -79
  616. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/ci/github-actions.md +0 -162
  617. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/ci/patterns.md +0 -145
  618. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/ci/vercel.md +0 -103
  619. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/cli/RULE.md +0 -100
  620. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/cli/commands.md +0 -297
  621. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/configuration/RULE.md +0 -211
  622. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/configuration/global-options.md +0 -187
  623. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/configuration/gotchas.md +0 -348
  624. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/configuration/tasks.md +0 -285
  625. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/environment/RULE.md +0 -96
  626. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/environment/gotchas.md +0 -141
  627. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/environment/modes.md +0 -101
  628. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/filtering/RULE.md +0 -148
  629. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/filtering/patterns.md +0 -152
  630. package/dist/baseline/scaffold-baseline/skills/frameworks/turborepo/turborepo/references/watch/RULE.md +0 -99
  631. package/dist/baseline/scaffold-baseline/skills/languages/python/async-python-patterns/SKILL.md +0 -735
  632. package/dist/baseline/scaffold-baseline/skills/languages/python/python-code-style/SKILL.md +0 -360
  633. package/dist/baseline/scaffold-baseline/skills/languages/python/python-design-patterns/SKILL.md +0 -433
  634. package/dist/baseline/scaffold-baseline/skills/languages/python/python-project-structure/SKILL.md +0 -252
  635. package/dist/baseline/scaffold-baseline/skills/languages/python/python-testing-patterns/SKILL.md +0 -622
  636. package/dist/baseline/scaffold-baseline/skills/languages/python/python-testing-patterns/references/advanced-patterns.md +0 -411
  637. package/dist/baseline/scaffold-baseline/skills/languages/typescript/quality-types/SKILL.md +0 -93
  638. package/dist/baseline/scaffold-baseline/skills/misc/secrets-cli/SKILL.md +0 -54
  639. package/dist/baseline/scaffold-baseline/skills/misc/secrets-cli/references/command-reference.md +0 -107
  640. package/dist/baseline/scaffold-baseline/skills/misc/secrets-cli/references/safety-and-errors.md +0 -54
  641. package/dist/baseline/scaffold-baseline/skills/misc/secrets-cli/references/workflows.md +0 -106
  642. package/dist/baseline/scaffold-baseline/skills/misc/timesheet/SKILL.md +0 -87
  643. package/dist/baseline/scaffold-baseline/skills/misc/timesheet/scripts/git-timesheet-evidence.mjs +0 -214
  644. package/dist/baseline/scaffold-baseline/skills/phases/bug-discovery-phase/REFERENCE.md +0 -193
  645. package/dist/baseline/scaffold-baseline/skills/phases/bug-discovery-phase/SKILL.md +0 -46
  646. package/dist/baseline/scaffold-baseline/skills/phases/bug-discovery-phase/agents/openai.yaml +0 -2
  647. package/dist/baseline/scaffold-baseline/skills/phases/bug-resolution-phase/REFERENCE.md +0 -183
  648. package/dist/baseline/scaffold-baseline/skills/phases/bug-resolution-phase/SKILL.md +0 -50
  649. package/dist/baseline/scaffold-baseline/skills/phases/bug-resolution-phase/agents/openai.yaml +0 -2
  650. package/dist/baseline/scaffold-baseline/skills/phases/debugging-phase/SKILL.md +0 -88
  651. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/SKILL.md +0 -52
  652. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/agents/openai.yaml +0 -2
  653. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/closeout.md +0 -35
  654. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/debug.md +0 -30
  655. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/docs-ingest.md +0 -27
  656. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/implement.md +0 -32
  657. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/plan.md +0 -27
  658. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/review.md +0 -29
  659. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/router.md +0 -46
  660. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/phases/spec.md +0 -26
  661. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/references/artifact-state.md +0 -42
  662. package/dist/baseline/scaffold-baseline/skills/phases/delivery-phase/references/phase-handoff.md +0 -27
  663. package/dist/baseline/scaffold-baseline/skills/phases/design-phase/SKILL.md +0 -48
  664. package/dist/baseline/scaffold-baseline/skills/phases/design-phase/agents/openai.yaml +0 -2
  665. package/dist/baseline/scaffold-baseline/skills/phases/design-phase/phases/approval.md +0 -37
  666. package/dist/baseline/scaffold-baseline/skills/phases/design-phase/phases/backlog.md +0 -28
  667. package/dist/baseline/scaffold-baseline/skills/phases/design-phase/phases/delivery-handoff.md +0 -29
  668. package/dist/baseline/scaffold-baseline/skills/phases/design-phase/phases/grill.md +0 -37
  669. package/dist/baseline/scaffold-baseline/skills/phases/design-phase/phases/intake.md +0 -25
  670. package/dist/baseline/scaffold-baseline/skills/phases/design-phase/phases/prototype.md +0 -30
  671. package/dist/baseline/scaffold-baseline/skills/phases/design-phase/phases/router.md +0 -66
  672. package/dist/baseline/scaffold-baseline/skills/phases/docs-ingest-phase/SKILL.md +0 -46
  673. package/dist/baseline/scaffold-baseline/skills/phases/docs-ingest-phase/agents/openai.yaml +0 -4
  674. package/dist/baseline/scaffold-baseline/skills/phases/docs-ingest-phase/phases/private-internal.md +0 -57
  675. package/dist/baseline/scaffold-baseline/skills/phases/docs-ingest-phase/phases/public-docs.md +0 -52
  676. package/dist/baseline/scaffold-baseline/skills/phases/docs-ingest-phase/phases/router.md +0 -42
  677. package/dist/baseline/scaffold-baseline/skills/phases/docs-ingest-phase/references/concept-pages.md +0 -70
  678. package/dist/baseline/scaffold-baseline/skills/phases/docs-ingest-phase/references/flow-pages.md +0 -56
  679. package/dist/baseline/scaffold-baseline/skills/phases/docs-ingest-phase/references/fumadocs-routing.md +0 -74
  680. package/dist/baseline/scaffold-baseline/skills/phases/docs-ingest-phase/references/learning-artifacts.md +0 -96
  681. package/dist/baseline/scaffold-baseline/skills/phases/docs-ingest-phase/references/public-docs.md +0 -90
  682. package/dist/baseline/scaffold-baseline/skills/phases/docs-ingest-phase/references/repo-docs.md +0 -38
  683. package/dist/baseline/scaffold-baseline/skills/phases/docs-ingest-phase/references/wiki-ingest.md +0 -134
  684. package/dist/baseline/scaffold-baseline/skills/phases/finder-phase/SKILL.md +0 -53
  685. package/dist/baseline/scaffold-baseline/skills/phases/finder-phase/agents/openai.yaml +0 -2
  686. package/dist/baseline/scaffold-baseline/skills/phases/finder-phase/references/frontier-lifecycle.md +0 -70
  687. package/dist/baseline/scaffold-baseline/skills/phases/finder-phase/references/root-routing.md +0 -29
  688. package/dist/baseline/scaffold-baseline/skills/phases/goalify/EXAMPLES.md +0 -11
  689. package/dist/baseline/scaffold-baseline/skills/phases/goalify/SKILL.md +0 -32
  690. package/dist/baseline/scaffold-baseline/skills/phases/requirements-phase/SKILL.md +0 -69
  691. package/dist/baseline/scaffold-baseline/skills/phases/requirements-phase/agents/openai.yaml +0 -2
  692. package/dist/baseline/scaffold-baseline/skills/phases/resolve-debt-phase/SKILL.md +0 -89
  693. package/dist/baseline/scaffold-baseline/skills/phases/resolve-debt-phase/agents/openai.yaml +0 -2
  694. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/REFERENCE.md +0 -147
  695. package/dist/baseline/scaffold-baseline/skills/phases/review-phase/SKILL.md +0 -54
  696. package/dist/baseline/scaffold-baseline.json +0 -12
  697. package/dist/baseline/scaffold-baseline.tgz +0 -0
  698. package/dist/skills/frameworks/nestjs/nestjs-best-practices/.gitignore +0 -29
package/dist/index.js CHANGED
@@ -186,7 +186,7 @@ ${prefix}}`}return stack};var FiberTypeId=`~effect/Fiber/${version}`;var fiberVa
186
186
  `)){filepath=filepath.replace(newlineRegExp,"%0A")}if(filepath.includes("\r")){filepath=filepath.replace(carriageReturnRegExp,"%0D")}if(filepath.includes("\t")){filepath=filepath.replace(tabRegExp,"%09")}return filepath}var posixImpl=Path.of({[TypeId29]:TypeId29,resolve:resolve2,normalize(path){if(path.length===0)return".";const isAbsolute=path.charCodeAt(0)===47;const trailingSeparator=path.charCodeAt(path.length-1)===47;path=normalizeStringPosix(path,!isAbsolute);if(path.length===0&&!isAbsolute)path=".";if(path.length>0&&trailingSeparator)path+="/";if(isAbsolute)return"/"+path;return path},isAbsolute(path){return path.length>0&&path.charCodeAt(0)===47},join(){if(arguments.length===0){return"."}let joined;for(let i=0;i<arguments.length;++i){const arg=arguments[i];if(arg.length>0){if(joined===undefined){joined=arg}else{joined+="/"+arg}}}if(joined===undefined){return"."}return posixImpl.normalize(joined)},relative(from,to){if(from===to)return"";from=posixImpl.resolve(from);to=posixImpl.resolve(to);if(from===to)return"";let fromStart=1;for(;fromStart<from.length;++fromStart){if(from.charCodeAt(fromStart)!==47){break}}const fromEnd=from.length;const fromLen=fromEnd-fromStart;let toStart=1;for(;toStart<to.length;++toStart){if(to.charCodeAt(toStart)!==47){break}}const toEnd=to.length;const toLen=toEnd-toStart;const length=fromLen<toLen?fromLen:toLen;let lastCommonSep=-1;let i=0;for(;i<=length;++i){if(i===length){if(toLen>length){if(to.charCodeAt(toStart+i)===47){return to.slice(toStart+i+1)}else if(i===0){return to.slice(toStart+i)}}else if(fromLen>length){if(from.charCodeAt(fromStart+i)===47){lastCommonSep=i}else if(i===0){lastCommonSep=0}}break}const fromCode=from.charCodeAt(fromStart+i);const toCode=to.charCodeAt(toStart+i);if(fromCode!==toCode){break}else if(fromCode===47){lastCommonSep=i}}let out="";for(i=fromStart+lastCommonSep+1;i<=fromEnd;++i){if(i===fromEnd||from.charCodeAt(i)===47){if(out.length===0){out+=".."}else{out+="/.."}}}if(out.length>0){return out+to.slice(toStart+lastCommonSep)}else{toStart+=lastCommonSep;if(to.charCodeAt(toStart)===47){++toStart}return to.slice(toStart)}},dirname(path){if(path.length===0)return".";let code=path.charCodeAt(0);const hasRoot=code===47;let end=-1;let matchedSlash=true;for(let i=path.length-1;i>=1;--i){code=path.charCodeAt(i);if(code===47){if(!matchedSlash){end=i;break}}else{matchedSlash=false}}if(end===-1)return hasRoot?"/":".";if(hasRoot&&end===1)return"//";return path.slice(0,end)},basename(path,ext){let start=0;let end=-1;let matchedSlash=true;let i;if(ext!==undefined&&ext.length>0&&ext.length<=path.length){if(ext.length===path.length&&ext===path)return"";let extIdx=ext.length-1;let firstNonSlashEnd=-1;for(i=path.length-1;i>=0;--i){const code=path.charCodeAt(i);if(code===47){if(!matchedSlash){start=i+1;break}}else{if(firstNonSlashEnd===-1){matchedSlash=false;firstNonSlashEnd=i+1}if(extIdx>=0){if(code===ext.charCodeAt(extIdx)){if(--extIdx===-1){end=i}}else{extIdx=-1;end=firstNonSlashEnd}}}}if(start===end)end=firstNonSlashEnd;else if(end===-1)end=path.length;return path.slice(start,end)}else{for(i=path.length-1;i>=0;--i){if(path.charCodeAt(i)===47){if(!matchedSlash){start=i+1;break}}else if(end===-1){matchedSlash=false;end=i+1}}if(end===-1)return"";return path.slice(start,end)}},extname(path){let startDot=-1;let startPart=0;let end=-1;let matchedSlash=true;let preDotState=0;for(let i=path.length-1;i>=0;--i){const code=path.charCodeAt(i);if(code===47){if(!matchedSlash){startPart=i+1;break}continue}if(end===-1){matchedSlash=false;end=i+1}if(code===46){if(startDot===-1){startDot=i}else if(preDotState!==1){preDotState=1}}else if(startDot!==-1){preDotState=-1}}if(startDot===-1||end===-1||preDotState===0||preDotState===1&&startDot===end-1&&startDot===startPart+1){return""}return path.slice(startDot,end)},format:function format4(pathObject){if(pathObject===null||typeof pathObject!=="object"){throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof pathObject)}return _format("/",pathObject)},parse(path){const ret={root:"",dir:"",base:"",ext:"",name:""};if(path.length===0)return ret;let code=path.charCodeAt(0);const isAbsolute=code===47;let start;if(isAbsolute){ret.root="/";start=1}else{start=0}let startDot=-1;let startPart=0;let end=-1;let matchedSlash=true;let i=path.length-1;let preDotState=0;for(;i>=start;--i){code=path.charCodeAt(i);if(code===47){if(!matchedSlash){startPart=i+1;break}continue}if(end===-1){matchedSlash=false;end=i+1}if(code===46){if(startDot===-1)startDot=i;else if(preDotState!==1)preDotState=1}else if(startDot!==-1){preDotState=-1}}if(startDot===-1||end===-1||preDotState===0||preDotState===1&&startDot===end-1&&startDot===startPart+1){if(end!==-1){if(startPart===0&&isAbsolute)ret.base=ret.name=path.slice(1,end);else ret.base=ret.name=path.slice(startPart,end)}}else{if(startPart===0&&isAbsolute){ret.name=path.slice(1,startDot);ret.base=path.slice(1,end)}else{ret.name=path.slice(startPart,startDot);ret.base=path.slice(startPart,end)}ret.ext=path.slice(startDot,end)}if(startPart>0)ret.dir=path.slice(0,startPart-1);else if(isAbsolute)ret.dir="/";return ret},sep:"/",fromFileUrl,toFileUrl,toNamespacedPath:identity});function makeValue(value3){return{_tag:"Value",value:value3}}function makeRecord(keys2,value3){return{_tag:"Record",keys:keys2,value:value3}}function makeArray(length,value3){return{_tag:"Array",length,value:value3}}class SourceError extends TaggedError2("SourceError"){}var ConfigProvider=Reference("effect/ConfigProvider",{defaultValue:()=>fromEnv()});var Proto5={...PipeInspectableProto,toJSON(){return{_id:"ConfigProvider"}}};var identityPath=(path)=>path;function makeProvider(state,load){const self=Object.create(Proto5);self.state=state;self.load=load;return self}function makeSource(get4,transform3){const state={_tag:"Source",get:get4,transform:transform3};return makeProvider(state,(path)=>state.get(state.transform(path)))}function makeOrElse(first,second){const state={_tag:"OrElse",first,second};return makeProvider(state,(path)=>flatMap4(state.first.load(path),(node)=>node?succeed6(node):state.second.load(path)))}function make20(get4){return makeSource(get4,identityPath)}var orElse=dual(2,(self,that)=>makeOrElse(self,that));var mapInput2=dual(2,(self,f)=>{const state=self.state;switch(state._tag){case"Source":return makeSource(state.get,flow(state.transform,f));case"OrElse":return makeOrElse(mapInput2(state.first,f),mapInput2(state.second,f))}});var constantCase=mapInput2((path)=>path.map((seg)=>typeof seg==="number"?seg:configCase(seg)));var nested=dual(2,(self,prefix)=>{const path=typeof prefix==="string"?[prefix]:prefix;const state=self.state;switch(state._tag){case"Source":return makeSource(state.get,flow(state.transform,(input)=>[...path,...input]));case"OrElse":return makeOrElse(nested(state.first,path),nested(state.second,path))}});var layer=(self)=>isEffect2(self)?effect(ConfigProvider)(self):succeed5(ConfigProvider)(self);var layerAdd=(self,options)=>effect(ConfigProvider)(gen2(function*(){const current=yield*ConfigProvider;const configProvider=isEffect2(self)?yield*self:self;return options?.asPrimary?orElse(configProvider,current):orElse(current,configProvider)}));function fromUnknown(root,options){const preserveEmptyStrings=options?.preserveEmptyStrings===true;return make20((path)=>succeed6(nodeAtJson(root,path,preserveEmptyStrings)))}function nodeAtJson(root,path,preserveEmptyStrings){let cur=root;for(const seg of path){if(cur===null||cur===undefined)return;if(Array.isArray(cur)){if(typeof seg!=="number"||!Number.isInteger(seg)||seg<0||seg>=cur.length)return;cur=cur[seg];continue}if(isObject(cur)){if(typeof seg!=="string")return;if(!Object.hasOwn(cur,seg))return;cur=cur[seg];continue}return}return describeUnknown(cur,preserveEmptyStrings)}function describeUnknown(u,preserveEmptyStrings){if(u===undefined||u===null)return;if(typeof u==="string")return stringNode(u,preserveEmptyStrings);if(typeof u==="number"||typeof u==="boolean"||typeof u==="bigint"){return makeValue(String(u))}if(Array.isArray(u))return makeArray(u.length);if(isObject(u)){return makeRecord(new Set(Object.keys(u)))}return makeValue(format(u))}function stringNode(value3,preserveEmptyStrings){const normalized=emptyStringAsMissing(value3,preserveEmptyStrings);return normalized===undefined?undefined:makeValue(normalized)}function emptyStringAsMissing(value3,preserveEmptyStrings){return value3===""&&!preserveEmptyStrings?undefined:value3}function fromEnv(options){const env=options?.env??{...globalThis?.process?.env,...import.meta?.env};const preserveEmptyStrings=options?.preserveEmptyStrings===true;const trie=buildEnvTrie(env);return make20((path)=>succeed6(nodeAtEnv(trie,env,path,preserveEmptyStrings)))}function buildEnvTrie(env){const trie={};for(const[name,value3]of Object.entries(env)){if(value3===undefined)continue;const segments=name.split("_");let node=trie;for(const seg of segments){node.children??={};node=node.children[seg]??={}}}return trie}var NUMERIC_INDEX=/^(0|[1-9][0-9]*)$/;function nodeAtEnv(trie,env,path,preserveEmptyStrings){const key=path.map(String).join("_");const leafValue=emptyStringAsMissing(env[key],preserveEmptyStrings);const trieNode=trieNodeAt(trie,path);const children=trieNode?.children?Object.keys(trieNode.children):[];if(children.length===0){return leafValue===undefined?undefined:makeValue(leafValue)}const allNumeric=children.every((k)=>NUMERIC_INDEX.test(k));if(allNumeric){const length=Math.max(...children.map((k)=>parseInt(k,10)))+1;return makeArray(length,leafValue)}return makeRecord(new Set(children),leafValue)}function trieNodeAt(root,path){if(path.length===0)return root;let node=root;for(const seg of path){node=node?.children?.[String(seg)];if(!node)return}return node}function fromDotEnvContents(lines,options){let env=parseDotEnvContents(lines);if(options?.expandVariables){env=dotEnvExpand(env)}return fromEnv({env,preserveEmptyStrings:options?.preserveEmptyStrings})}var DOT_ENV_LINE=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function parseDotEnvContents(lines){const obj={};lines=lines.replace(/\r\n?/gm,`
187
187
  `);let match8;while((match8=DOT_ENV_LINE.exec(lines))!=null){const key=match8[1];let value3=match8[2]||"";value3=value3.trim();const maybeQuote=value3[0];value3=value3.replace(/^(['"`])([\s\S]*)\1$/gm,"$2");if(maybeQuote==='"'){value3=value3.replace(/\\n/g,`
188
188
  `);value3=value3.replace(/\\r/g,"\r")}obj[key]=value3}return obj}function dotEnvExpand(parsed){const newParsed={};for(const configKey in parsed){newParsed[configKey]=interpolate(parsed[configKey],parsed).replace(/\\\$/g,"$")}return newParsed}function interpolate(envValue,parsed){const lastUnescapedDollarSignIndex=searchLast(envValue,/(?!(?<=\\))\$/g);if(lastUnescapedDollarSignIndex===-1)return envValue;const rightMostGroup=envValue.slice(lastUnescapedDollarSignIndex);const matchGroup=/((?!(?<=\\))\${?([\w]+)(?::-([^}\\]*))?}?)/;const match8=rightMostGroup.match(matchGroup);if(match8!==null){const[_,group,variableName,defaultValue]=match8;return interpolate(envValue.replace(group,defaultValue||parsed[variableName]||""),parsed)}return envValue}function searchLast(str,rgx){const matches=Array.from(str.matchAll(rgx));return matches.length>0?matches.slice(-1)[0].index:-1}var fromDotEnv=fnUntraced2(function*(options){const fs=yield*FileSystem;const content=yield*fs.readFileString(options?.path??".env");return fromDotEnvContents(content,options)});var fromDir=fnUntraced2(function*(options){const platformPath=yield*Path;const fs=yield*FileSystem;const rootPath=options?.rootPath??"/";const preserveEmptyStrings=options?.preserveEmptyStrings===true;return make20((path)=>{const fullPath=platformPath.join(rootPath,...path.map(String));const asFile=fs.readFileString(fullPath).pipe(map7((content)=>stringNode(content.trim(),preserveEmptyStrings)));const asDirectory=fs.readDirectory(fullPath).pipe(map7((entries)=>makeRecord(new Set(entries.map((entry)=>platformPath.basename(entry))))));return asFile.pipe(catch_2((fileCause)=>asDirectory.pipe(catch_2((dirCause)=>isNotFound(fileCause)&&isNotFound(dirCause)?succeed6(undefined):fail6(isNotFound(fileCause)?dirCause:fileCause)))),mapError3((cause)=>new SourceError({message:`Failed to read file at ${platformPath.join(rootPath,...path.map(String))}`,cause})))})});var isNotFound=(cause)=>cause.reason._tag==="NotFound";var values=["All","Fatal","Error","Warn","Info","Debug","Trace","None"];var exports_Schema={};__export(exports_Schema,{withDecodingDefaultTypeKey:()=>withDecodingDefaultTypeKey,withDecodingDefaultType:()=>withDecodingDefaultType,withDecodingDefaultKey:()=>withDecodingDefaultKey,withDecodingDefault:()=>withDecodingDefault,withConstructorDefault:()=>withConstructorDefault2,toType:()=>toType2,toTaggedUnion:()=>toTaggedUnion,toStandardSchemaV1:()=>toStandardSchemaV1,toStandardJSONSchemaV1:()=>toStandardJSONSchemaV1,toRepresentation:()=>toRepresentation,toJsonSchemaDocument:()=>toJsonSchemaDocument2,toIsoSource:()=>toIsoSource,toIsoFocus:()=>toIsoFocus,toIso:()=>toIso,toFormatter:()=>toFormatter,toEquivalence:()=>toEquivalence2,toEncoderXml:()=>toEncoderXml,toEncoded:()=>toEncoded2,toDifferJsonPatch:()=>toDifferJsonPatch,toCodecStringTree:()=>toCodecStringTree,toCodecJson:()=>toCodecJson,toCodecIso:()=>toCodecIso,toCodecArrayFromSingle:()=>toCodecArrayFromSingle,toArbitraryLazy:()=>toArbitraryLazy,toArbitrary:()=>toArbitrary,tagDefaultOmit:()=>tagDefaultOmit,tag:()=>tag,suspend:()=>suspend5,revealCodec:()=>revealCodec,revealBottom:()=>revealBottom,resolveAnnotationsKey:()=>resolveAnnotationsKey,resolveAnnotations:()=>resolveAnnotations,requiredKey:()=>requiredKey,required:()=>required,refine:()=>refine,redact:()=>redact3,readonlyKey:()=>readonlyKey,overrideToFormatter:()=>overrideToFormatter,overrideToEquivalence:()=>overrideToEquivalence,overrideToCodecIso:()=>overrideToCodecIso,optionalKey:()=>optionalKey2,optional:()=>optional,mutableKey:()=>mutableKey2,mutable:()=>mutable,middlewareEncoding:()=>middlewareEncoding2,middlewareDecoding:()=>middlewareDecoding2,makeIsMultipleOf:()=>makeIsMultipleOf,makeIsLessThanOrEqualTo:()=>makeIsLessThanOrEqualTo,makeIsLessThan:()=>makeIsLessThan,makeIsGreaterThanOrEqualTo:()=>makeIsGreaterThanOrEqualTo,makeIsGreaterThan:()=>makeIsGreaterThan,makeIsBetween:()=>makeIsBetween,makeFilterGroup:()=>makeFilterGroup,makeFilter:()=>makeFilter2,make:()=>make26,link:()=>link,isUppercased:()=>isUppercased,isUnique:()=>isUnique,isUncapitalized:()=>isUncapitalized,isUint32:()=>isUint32,isUUID:()=>isUUID,isULID:()=>isULID,isTrimmed:()=>isTrimmed,isStringSymbol:()=>isStringSymbol2,isStringFinite:()=>isStringFinite2,isStringBigInt:()=>isStringBigInt2,isStartsWith:()=>isStartsWith,isSizeBetween:()=>isSizeBetween,isSchemaError:()=>isSchemaError,isSchema:()=>isSchema,isPropertyNames:()=>isPropertyNames,isPropertiesLengthBetween:()=>isPropertiesLengthBetween,isPattern:()=>isPattern2,isNonEmpty:()=>isNonEmpty,isMultipleOf:()=>isMultipleOf,isMinSize:()=>isMinSize,isMinProperties:()=>isMinProperties,isMinLength:()=>isMinLength,isMaxSize:()=>isMaxSize,isMaxProperties:()=>isMaxProperties,isMaxLength:()=>isMaxLength,isLowercased:()=>isLowercased,isLessThanOrEqualToDate:()=>isLessThanOrEqualToDate,isLessThanOrEqualToBigInt:()=>isLessThanOrEqualToBigInt,isLessThanOrEqualToBigDecimal:()=>isLessThanOrEqualToBigDecimal,isLessThanOrEqualTo:()=>isLessThanOrEqualTo4,isLessThanDate:()=>isLessThanDate,isLessThanBigInt:()=>isLessThanBigInt,isLessThanBigDecimal:()=>isLessThanBigDecimal,isLessThan:()=>isLessThan4,isLengthBetween:()=>isLengthBetween,isInt32:()=>isInt32,isInt:()=>isInt,isIncludes:()=>isIncludes,isGreaterThanOrEqualToDate:()=>isGreaterThanOrEqualToDate,isGreaterThanOrEqualToBigInt:()=>isGreaterThanOrEqualToBigInt,isGreaterThanOrEqualToBigDecimal:()=>isGreaterThanOrEqualToBigDecimal,isGreaterThanOrEqualTo:()=>isGreaterThanOrEqualTo3,isGreaterThanDate:()=>isGreaterThanDate,isGreaterThanBigInt:()=>isGreaterThanBigInt,isGreaterThanBigDecimal:()=>isGreaterThanBigDecimal,isGreaterThan:()=>isGreaterThan4,isGUID:()=>isGUID,isFinite:()=>isFinite3,isEndsWith:()=>isEndsWith,isDateValid:()=>isDateValid,isCapitalized:()=>isCapitalized,isBetweenDate:()=>isBetweenDate,isBetweenBigInt:()=>isBetweenBigInt,isBetweenBigDecimal:()=>isBetweenBigDecimal,isBetween:()=>isBetween2,isBase64Url:()=>isBase64Url,isBase64:()=>isBase64,is:()=>is2,instanceOf:()=>instanceOf,fromURLSearchParams:()=>fromURLSearchParams2,fromJsonString:()=>fromJsonString2,fromFormData:()=>fromFormData2,fromBrand:()=>fromBrand,flip:()=>flip4,fieldsAssign:()=>fieldsAssign,extendTo:()=>extendTo,encodeUnknownSync:()=>encodeUnknownSync2,encodeUnknownResult:()=>encodeUnknownResult2,encodeUnknownPromise:()=>encodeUnknownPromise,encodeUnknownOption:()=>encodeUnknownOption2,encodeUnknownExit:()=>encodeUnknownExit2,encodeUnknownEffect:()=>encodeUnknownEffect2,encodeTo:()=>encodeTo,encodeSync:()=>encodeSync2,encodeResult:()=>encodeResult,encodePromise:()=>encodePromise,encodeOption:()=>encodeOption2,encodeKeys:()=>encodeKeys,encodeExit:()=>encodeExit,encodeEffect:()=>encodeEffect,encode:()=>encode,decodeUnknownSync:()=>decodeUnknownSync2,decodeUnknownResult:()=>decodeUnknownResult2,decodeUnknownPromise:()=>decodeUnknownPromise,decodeUnknownOption:()=>decodeUnknownOption2,decodeUnknownExit:()=>decodeUnknownExit2,decodeUnknownEffect:()=>decodeUnknownEffect2,decodeTo:()=>decodeTo2,decodeSync:()=>decodeSync2,decodeResult:()=>decodeResult,decodePromise:()=>decodePromise,decodeOption:()=>decodeOption2,decodeExit:()=>decodeExit,decodeEffect:()=>decodeEffect2,decode:()=>decode,declareConstructor:()=>declareConstructor,declare:()=>declare,check:()=>check2,catchEncodingWithContext:()=>catchEncodingWithContext,catchEncoding:()=>catchEncoding,catchDecodingWithContext:()=>catchDecodingWithContext,catchDecoding:()=>catchDecoding,brand:()=>brand2,asserts:()=>asserts2,asClass:()=>asClass,annotateKey:()=>annotateKey2,annotateEncoded:()=>annotateEncoded,annotate:()=>annotate2,Void:()=>Void2,UnknownFromJsonString:()=>UnknownFromJsonString,Unknown:()=>Unknown2,UniqueSymbol:()=>UniqueSymbol2,UniqueArray:()=>UniqueArray,Union:()=>Union2,UndefinedOr:()=>UndefinedOr,Undefined:()=>Undefined2,Uint8ArrayFromHex:()=>Uint8ArrayFromHex,Uint8ArrayFromBase64Url:()=>Uint8ArrayFromBase64Url,Uint8ArrayFromBase64:()=>Uint8ArrayFromBase64,Uint8Array:()=>Uint8Array2,URLSearchParams:()=>URLSearchParams2,URLFromString:()=>URLFromString,URL:()=>URL2,TupleWithRest:()=>TupleWithRest,Tuple:()=>Tuple2,Trimmed:()=>Trimmed,Trim:()=>Trim,Tree:()=>Tree,TimeZoneOffset:()=>TimeZoneOffset,TimeZoneNamedFromString:()=>TimeZoneNamedFromString,TimeZoneNamed:()=>TimeZoneNamed,TimeZoneFromString:()=>TimeZoneFromString,TimeZone:()=>TimeZone,TemplateLiteralParser:()=>TemplateLiteralParser,TemplateLiteral:()=>TemplateLiteral2,TaggedUnion:()=>TaggedUnion,TaggedStruct:()=>TaggedStruct,TaggedErrorClass:()=>TaggedErrorClass,TaggedClass:()=>TaggedClass2,Symbol:()=>Symbol3,StructWithRest:()=>StructWithRest,Struct:()=>Struct,StringFromUriComponent:()=>StringFromUriComponent,StringFromHex:()=>StringFromHex,StringFromBase64Url:()=>StringFromBase64Url,StringFromBase64:()=>StringFromBase64,String:()=>String5,StandardSchemaV1FailureResult:()=>StandardSchemaV1FailureResult,SchemaError:()=>SchemaError,Result:()=>Result,RegExp:()=>RegExp3,RedactedFromValue:()=>RedactedFromValue,Redacted:()=>Redacted,Record:()=>Record,ReadonlySet:()=>ReadonlySet,ReadonlyMap:()=>ReadonlyMap,PropertyKey:()=>PropertyKey,OptionFromUndefinedOr:()=>OptionFromUndefinedOr,OptionFromOptionalNullOr:()=>OptionFromOptionalNullOr,OptionFromOptionalKey:()=>OptionFromOptionalKey,OptionFromOptional:()=>OptionFromOptional,OptionFromNullishOr:()=>OptionFromNullishOr,OptionFromNullOr:()=>OptionFromNullOr,Option:()=>Option,Opaque:()=>Opaque,ObjectKeyword:()=>ObjectKeyword2,NumberFromString:()=>NumberFromString,Number:()=>Number6,NullishOr:()=>NullishOr,NullOr:()=>NullOr,Null:()=>Null2,NonEmptyString:()=>NonEmptyString,NonEmptyArray:()=>NonEmptyArray,Never:()=>Never2,MutableJson:()=>MutableJson2,Literals:()=>Literals,Literal:()=>Literal2,Json:()=>Json2,Int:()=>Int,HashSet:()=>HashSet,HashMap:()=>HashMap,FormData:()=>FormData2,FiniteFromString:()=>FiniteFromString,Finite:()=>Finite,File:()=>File,Exit:()=>Exit,ErrorClass:()=>ErrorClass,Error:()=>Error4,Enum:()=>Enum2,DurationFromString:()=>DurationFromString,DurationFromNanos:()=>DurationFromNanos,DurationFromMillis:()=>DurationFromMillis,Duration:()=>Duration,Defect:()=>Defect,DateValid:()=>DateValid,DateTimeZonedFromString:()=>DateTimeZonedFromString,DateTimeZoned:()=>DateTimeZoned,DateTimeUtcFromString:()=>DateTimeUtcFromString,DateTimeUtcFromMillis:()=>DateTimeUtcFromMillis,DateTimeUtcFromDate:()=>DateTimeUtcFromDate,DateTimeUtc:()=>DateTimeUtc,DateFromString:()=>DateFromString,DateFromMillis:()=>DateFromMillis,Date:()=>Date4,Class:()=>Class4,Chunk:()=>Chunk,Char:()=>Char,CauseReason:()=>CauseReason,Cause:()=>Cause,BooleanFromBit:()=>BooleanFromBit,Boolean:()=>Boolean4,BigIntFromString:()=>BigIntFromString,BigInt:()=>BigInt5,BigDecimalFromString:()=>BigDecimalFromString,BigDecimal:()=>BigDecimal,ArrayEnsure:()=>ArrayEnsure,Array:()=>ArraySchema,Any:()=>Any2});var HashMapTypeId="~effect/collections/HashMap";var SHIFT=5;var BUCKET_SIZE=1<<SHIFT;var MIN_ARRAY_NODE=BUCKET_SIZE/4;var MAX_INDEX_NODE=BUCKET_SIZE/2;var BITMAP_INDEX_MASK=BUCKET_SIZE-1;var popcount=(n)=>{n=n-(n>>>1&1431655765);n=(n&858993459)+(n>>>2&858993459);return(n+(n>>>4)&252645135)*16843009>>>24};var mask=(hash2,shift)=>hash2>>>shift&BITMAP_INDEX_MASK;var bitpos=(hash2,shift)=>1<<mask(hash2,shift);var index=(bitmap,bit)=>popcount(bitmap&bit-1);function mergeLeaves(edit,shift,hash1,node1,hash2,node2){if(shift>32){throw new Error("HashMap: max depth exceeded")}const bit1=bitpos(hash1,shift);const bit2=bitpos(hash2,shift);if(bit1===bit2){const child=mergeLeaves(edit,shift+SHIFT,hash1,node1,hash2,node2);return new IndexedNode(edit,bit1,[child])}const bitmap=bit1|bit2;const children=bit1>>>0<bit2>>>0?[node1,node2]:[node2,node1];return new IndexedNode(edit,bitmap,children)}class Node{canEdit(edit){return this.edit===edit}}class EmptyNode extends Node{_tag="EmptyNode";edit=0;get size(){return 0}get(_shift,_hash,_key){return none2()}has(_shift,_hash,_key){return false}set(edit,_shift,hash2,key,value3,added){added.value=true;return new LeafNode(edit,hash2,key,value3)}remove(_edit,_shift,_hash,_key,_removed){return this}iterator(){return[][Symbol.iterator]()}[Symbol.iterator](){return this.iterator()}canEdit(_edit){return false}}class LeafNode extends Node{_tag="LeafNode";edit;hash;key;value;constructor(edit,hash2,key,value3){super();this.edit=edit;this.hash=hash2;this.key=key;this.value=value3}get size(){return 1}get(_shift,hash2,key){if(this.hash===hash2&&equals(this.key,key)){return some2(this.value)}return none2()}has(_shift,hash2,key){return this.hash===hash2&&equals(this.key,key)}set(edit,shift,hash2,key,value3,added){if(this.hash===hash2&&equals(this.key,key)){if(equals(this.value,value3)){return this}if(this.canEdit(edit)){this.value=value3;return this}return new LeafNode(edit,hash2,key,value3)}added.value=true;if(this.hash===hash2){return new CollisionNode(edit,hash2,[[this.key,this.value],[key,value3]])}const newBit=bitpos(hash2,shift);const existingBit=bitpos(this.hash,shift);if(newBit===existingBit){return new IndexedNode(edit,newBit,[this.set(edit,shift+SHIFT,hash2,key,value3,added)])}const bitmap=newBit|existingBit;const nodes=newBit>>>0<existingBit>>>0?[new LeafNode(edit,hash2,key,value3),this]:[this,new LeafNode(edit,hash2,key,value3)];return new IndexedNode(edit,bitmap,nodes)}remove(_edit,_shift,hash2,key,removed){if(this.hash===hash2&&equals(this.key,key)){removed.value=true;return}return this}iterator(){return[[this.key,this.value]][Symbol.iterator]()}[Symbol.iterator](){return this.iterator()}}class CollisionNode extends Node{_tag="CollisionNode";edit;hash;entries;constructor(edit,hash2,entries){super();this.edit=edit;this.hash=hash2;this.entries=entries}get size(){return this.entries.length}get(_shift,hash2,key){if(this.hash!==hash2){return none2()}for(const[k,v]of this.entries){if(equals(k,key)){return some2(v)}}return none2()}has(_shift,hash2,key){if(this.hash!==hash2){return false}for(const[k]of this.entries){if(equals(k,key)){return true}}return false}set(edit,shift,hash2,key,value3,added){if(this.hash!==hash2){added.value=true;return mergeLeaves(edit,shift,this.hash,this,hash2,new LeafNode(edit,hash2,key,value3))}for(let i=0;i<this.entries.length;i++){if(equals(this.entries[i][0],key)){if(equals(this.entries[i][1],value3)){return this}if(this.canEdit(edit)){this.entries[i]=[key,value3];return this}const newEntries=[...this.entries];newEntries[i]=[key,value3];return new CollisionNode(edit,this.hash,newEntries)}}added.value=true;if(this.canEdit(edit)){this.entries.push([key,value3]);return this}return new CollisionNode(edit,this.hash,[...this.entries,[key,value3]])}remove(edit,_shift,hash2,key,removed){if(this.hash!==hash2){return this}const idx=this.entries.findIndex(([k])=>equals(k,key));if(idx===-1){return this}removed.value=true;if(this.entries.length===1){return}if(this.entries.length===2){const remaining=this.entries[idx===0?1:0];return new LeafNode(edit,this.hash,remaining[0],remaining[1])}if(this.canEdit(edit)){this.entries.splice(idx,1);return this}const newEntries=[...this.entries];newEntries.splice(idx,1);return new CollisionNode(edit,this.hash,newEntries)}iterator(){return this.entries[Symbol.iterator]()}[Symbol.iterator](){return this.iterator()}}class IndexedNode extends Node{_tag="IndexedNode";edit;_size;bitmap;children;constructor(edit,bitmap,children){super();this.edit=edit;this.bitmap=bitmap;this.children=children}get size(){if(this._size===undefined){this._size=this.children.reduce((acc,child)=>acc+child.size,0)}return this._size}get(shift,hash2,key){const bit=bitpos(hash2,shift);if((this.bitmap&bit)===0){return none2()}const idx=index(this.bitmap,bit);return this.children[idx].get(shift+SHIFT,hash2,key)}has(shift,hash2,key){const bit=bitpos(hash2,shift);if((this.bitmap&bit)===0){return false}const idx=index(this.bitmap,bit);return this.children[idx].has(shift+SHIFT,hash2,key)}set(edit,shift,hash2,key,value3,added){const bit=bitpos(hash2,shift);const idx=index(this.bitmap,bit);if((this.bitmap&bit)!==0){const child=this.children[idx];const newChild=child.set(edit,shift+SHIFT,hash2,key,value3,added);if(child===newChild){return this}if(this.canEdit(edit)){this.children[idx]=newChild;return this}const newChildren=[...this.children];newChildren[idx]=newChild;return new IndexedNode(edit,this.bitmap,newChildren)}else{added.value=true;const newChild=new LeafNode(edit,hash2,key,value3);const newBitmap=this.bitmap|bit;if(this.canEdit(edit)){this.children.splice(idx,0,newChild);this.bitmap=newBitmap;this._size=undefined;if(this.children.length>MAX_INDEX_NODE){return this.expand(edit,newBitmap,this.children)}return this}const newChildren=[...this.children];newChildren.splice(idx,0,newChild);if(newChildren.length>MAX_INDEX_NODE){return this.expand(edit,newBitmap,newChildren)}return new IndexedNode(edit,newBitmap,newChildren)}}remove(edit,shift,hash2,key,removed){const bit=bitpos(hash2,shift);if((this.bitmap&bit)===0){return this}const idx=index(this.bitmap,bit);const child=this.children[idx];const newChild=child.remove(edit,shift+SHIFT,hash2,key,removed);if(!removed.value){return this}if(newChild===undefined){const newBitmap=this.bitmap^bit;if(newBitmap===0){return}if(this.children.length===2){const remaining=this.children[idx===0?1:0];if(remaining._tag==="LeafNode"){return remaining}}if(this.canEdit(edit)){this.children.splice(idx,1);this.bitmap=newBitmap;this._size=undefined;return this}const newChildren2=[...this.children];newChildren2.splice(idx,1);return new IndexedNode(edit,newBitmap,newChildren2)}if(child===newChild){return this}if(this.canEdit(edit)){this.children[idx]=newChild;return this}const newChildren=[...this.children];newChildren[idx]=newChild;return new IndexedNode(edit,this.bitmap,newChildren)}expand(edit,bitmap,children){const nodes=new globalThis.Array(BUCKET_SIZE);let j=0;for(let i=0;i<BUCKET_SIZE;i++){if((bitmap&1<<i)!==0){nodes[i]=children[j++]}}return new ArrayNode(edit,children.length,nodes)}iterator(){let childIndex=0;let currentIterator;return{next:()=>{while(childIndex<this.children.length){if(!currentIterator){currentIterator=this.children[childIndex].iterator()}const result3=currentIterator.next();if(!result3.done){return result3}currentIterator=undefined;childIndex++}return{done:true,value:undefined}}}}[Symbol.iterator](){return this.iterator()}}class ArrayNode extends Node{_tag="ArrayNode";edit;_size;count;children;constructor(edit,count,children){super();this.edit=edit;this.count=count;this.children=children}get size(){if(this._size===undefined){this._size=this.children.reduce((acc,child)=>acc+(child?.size??0),0)}return this._size}get(shift,hash2,key){const idx=mask(hash2,shift);const child=this.children[idx];return child?child.get(shift+SHIFT,hash2,key):none2()}has(shift,hash2,key){const idx=mask(hash2,shift);const child=this.children[idx];return child?child.has(shift+SHIFT,hash2,key):false}set(edit,shift,hash2,key,value3,added){const idx=mask(hash2,shift);const child=this.children[idx];if(child){const newChild=child.set(edit,shift+SHIFT,hash2,key,value3,added);if(child===newChild){return this}if(this.canEdit(edit)){this.children[idx]=newChild;return this}const newChildren=[...this.children];newChildren[idx]=newChild;return new ArrayNode(edit,this.count,newChildren)}else{added.value=true;const newChild=new LeafNode(edit,hash2,key,value3);if(this.canEdit(edit)){this.children[idx]=newChild;this.count++;this._size=undefined;return this}const newChildren=[...this.children];newChildren[idx]=newChild;return new ArrayNode(edit,this.count+1,newChildren)}}remove(edit,shift,hash2,key,removed){const idx=mask(hash2,shift);const child=this.children[idx];if(!child){return this}const newChild=child.remove(edit,shift+SHIFT,hash2,key,removed);if(!removed.value){return this}const newCount=this.count-(newChild?0:1);if(newCount<MIN_ARRAY_NODE){return this.pack(edit,idx,newChild)}if(child===newChild){return this}if(this.canEdit(edit)){this.children[idx]=newChild;if(!newChild){this.count=newCount}this._size=undefined;return this}const newChildren=[...this.children];newChildren[idx]=newChild;return new ArrayNode(edit,newCount,newChildren)}pack(edit,excludeIdx,newChild){const children=[];let bitmap=0;let bit=1;for(let i=0;i<this.children.length;i++){const child=i===excludeIdx?newChild:this.children[i];if(child){children.push(child);bitmap|=bit}bit<<=1}return new IndexedNode(edit,bitmap,children)}iterator(){let childIndex=0;let currentIterator;return{next:()=>{while(childIndex<this.children.length){const child=this.children[childIndex];if(!child){childIndex++;continue}if(!currentIterator){currentIterator=child.iterator()}const result3=currentIterator.next();if(!result3.done){return result3}currentIterator=undefined;childIndex++}return{done:true,value:undefined}}}}[Symbol.iterator](){return this.iterator()}}class HashMapImpl{[HashMapTypeId]=HashMapTypeId;_editable;_edit;_root;_size;constructor(editable,edit,root,size2){this._editable=editable;this._edit=edit;this._root=root;this._size=size2}get size(){return this._size}[Symbol.iterator](){return this._root.iterator()}[symbol2](that){if(isHashMap(that)){const thatImpl=that;if(this.size!==thatImpl.size){return false}for(const[key,value3]of this){const otherValue=pipe(that,get4(key));if(isNone2(otherValue)||!equals(value3,otherValue.value)){return false}}return true}return false}[symbol](){let hash2=string("HashMap");for(const[key,value3]of this){hash2=hash2^hash(key)+hash(value3)}return hash2}[NodeInspectSymbol](){return toJson(this)}toString(){return`HashMap(${format(Array.from(this))})`}toJSON(){return{_id:"HashMap",values:Array.from(this).map(([k,v])=>[toJson(k),toJson(v)])}}pipe(){return pipeArguments(this,arguments)}}var emptyNode=new EmptyNode;var isHashMap=(u)=>hasProperty(u,HashMapTypeId);var empty8=()=>new HashMapImpl(false,0,emptyNode,0);var fromIterable3=(entries)=>{let root=emptyNode;let size2=0;const added={value:false};for(const[key,value3]of entries){const hash2=hash(key);added.value=false;root=root.set(NaN,0,hash2,key,value3,added);if(added.value){size2++}}return new HashMapImpl(false,0,root,size2)};var get4=dual(2,(self,key)=>{const impl=self;return impl._root.get(0,hash(key),key)});var has2=dual(2,(self,key)=>{const impl=self;return impl._root.has(0,hash(key),key)});var set2=dual(3,(self,key,value3)=>{const impl=self;const hash2=hash(key);const added={value:false};const edit=impl._editable?impl._edit:NaN;const newRoot=impl._root.set(edit,0,hash2,key,value3,added);if(impl._editable){impl._root=newRoot;if(added.value){impl._size++}return self}if(impl._root===newRoot){return self}return new HashMapImpl(false,impl._edit,newRoot,impl._size+(added.value?1:0))});var keys2=(self)=>{const iterator=self[Symbol.iterator]();return{[Symbol.iterator](){return this},next(){const result3=iterator.next();if(result3.done){return{done:true,value:undefined}}return{done:false,value:result3.value[0]}}}};var entries=(self)=>{const iterator=self[Symbol.iterator]();return{[Symbol.iterator](){return this},next(){return iterator.next()}}};var size2=(self)=>self.size;var isHashMap2=isHashMap;var fromIterable4=fromIterable3;var entries2=entries;var toEntries=(self)=>Array.from(entries2(self));var size3=size2;var HashSetTypeId="~effect/collections/HashSet";var HashSetProto={[symbol](){return hash(HashSetTypeId)},[symbol2](that){return isHashSet(that)&&size4(this)===size4(that)&&every2(this,(value3)=>has3(that,value3))},[Symbol.iterator](){return keys2(keyMap(this))},toString(){return`HashSet(${format(Array.from(this))})`},toJSON(){return{_id:"HashSet",values:toJson(Array.from(this))}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};var makeImpl=(keyMap)=>{const set3=Object.create(HashSetProto);set3[HashSetTypeId]=HashSetTypeId;set3.keyMap=keyMap;return set3};var isHashSet=(u)=>hasProperty(u,HashSetTypeId);var keyMap=(self)=>self.keyMap;var fromIterable5=(values3)=>{let map11=empty8();for(const value3 of values3){map11=set2(map11,value3,true)}return makeImpl(map11)};var has3=(self,value3)=>has2(keyMap(self),value3);var size4=(self)=>size2(keyMap(self));var every2=(self,predicate)=>{for(const value3 of self){if(!predicate(value3)){return false}}return true};var fromIterable6=fromIterable5;var isHashSet2=isHashSet;var size5=size4;var Boolean3=globalThis.Boolean;var ReducerOr=make2((a,b)=>a||b,false);var pick=dual(2,(self,keys3)=>{return buildStruct(self,(k,v)=>keys3.includes(k)?[k,v]:undefined)});var omit2=dual(2,(self,keys3)=>{return buildStruct(self,(k,v)=>!keys3.includes(k)?[k,v]:undefined)});var assign=dual(2,(self,that)=>{return{...self,...that}});var renameKeys=dual(2,(self,mapping)=>{return buildStruct(self,(k,v)=>[Object.hasOwn(mapping,k)?mapping[k]:k,v])});var lambda=(f)=>f;function buildStruct(source,f){const out={};for(const k of Reflect.ownKeys(source)){if(!Object.prototype.propertyIsEnumerable.call(source,k))continue;const res=f(k,source[k]);if(res){const[nk,nv]=res;out[nk]=nv}}return out}function makeCombiner(combiners,options){const omitKeyWhen=options?.omitKeyWhen??(()=>false);return make((self,that)=>{const keys3=Reflect.ownKeys(combiners);const out={};for(const key of keys3){const merge5=combiners[key].combine(self[key],that[key]);if(omitKeyWhen(merge5))continue;out[key]=merge5}return out})}var map12=dual(2,(self,f)=>self===undefined?undefined:f(self));function makeReducer(combiner){return make2((self,that)=>{if(self===undefined)return that;if(that===undefined)return self;return combiner.combine(self,that)},undefined)}function errorWithPath(message,path){if(path.length>0){message+=`
189
- at ${formatPath(path)}`}return new Error(message)}var arbitraryMemoMap=new WeakMap;var suspendDepthIdentifierMap=new WeakMap;var emptyRecursionStack=[];function makeReport(){return{warnings:[]}}function toReport(report){return{warnings:report.warnings.slice()}}function arbitraryError(what){return new Error(`Unable to derive an arbitrary for ${what}`)}var entryComparator=([a],[b])=>equals(a,b);function applyChecks(ast,filters,arbitrary){return filters.reduce((acc,filter10)=>acc.filter((a)=>filter10.run(a,ast,defaultParseOptions)===undefined),arbitrary)}function validateArrayConstraints(constraint,label){if(constraint?.minLength!==undefined&&constraint.maxLength!==undefined&&constraint.minLength>constraint.maxLength){throw arbitraryError(`${label} constraints`)}}function lengthToFastCheckConstraints(constraint){return constraint===undefined||constraint.minLength===undefined&&constraint.maxLength===undefined?undefined:{...constraint.minLength!==undefined?{minLength:constraint.minLength}:{},...constraint.maxLength!==undefined?{maxLength:constraint.maxLength}:{}}}function arrayWithConstraints(fc,item,constraint,comparator){return comparator?fc.uniqueArray(item,{...constraint,comparator}):fc.array(item,constraint)}function array2(fc,ctx,item,terminal=false){const constraint=ctx.constraint;const arrayConstraints=lengthToFastCheckConstraints(constraint);validateArrayConstraints(arrayConstraints,"array");return arrayWithConstraints(fc,item,terminal?{...arrayConstraints,maxLength:arrayConstraints?.minLength??0}:arrayConstraints,constraint?.unique?equals:undefined)}function appendArray(fc,out,len,rest){return out.chain((as3)=>as3.length<len?fc.constant(as3):rest.map((rest2)=>[...as3,...rest2]))}function appendObjectEntries(out,entries3){return out.chain((o)=>entries3.map((entries4)=>({...Object.fromEntries(entries4),...o})))}var max4=makeReducer(ReducerMax);var min4=makeReducer(ReducerMin);var or2=makeReducer(ReducerOr);var concat=makeReducer(makeReducerConcat());var combiner=makeCombiner({integer:or2,maxLength:min4,minLength:max4,noInfinity:or2,noNaN:or2,patterns:concat,unique:or2,valid:or2},{omitKeyWhen:isUndefined});function mergeOrderedBound(order,self,selfExclusive,that,thatExclusive,takeComparison){if(that===undefined||self===undefined){return that===undefined?[self,selfExclusive]:[that,thatExclusive]}const comparison=order(self,that);return comparison===takeComparison?[that,thatExclusive]:comparison===0?[self,selfExclusive||thatExclusive]:[self,selfExclusive]}function mergeOrderedConstraints(self,that){if(self===undefined){return that}if(self.order!==that.order){throw new Error("Cannot merge ordered arbitrary constraints with different Order instances")}const[minimum,exclusiveMinimum]=mergeOrderedBound(self.order,self.minimum,self.exclusiveMinimum,that.minimum,that.exclusiveMinimum,-1);const[maximum,exclusiveMaximum]=mergeOrderedBound(self.order,self.maximum,self.exclusiveMaximum,that.maximum,that.exclusiveMaximum,1);return{order:self.order,...minimum!==undefined?{minimum}:{},...exclusiveMinimum!==undefined?{exclusiveMinimum}:{},...maximum!==undefined?{maximum}:{},...exclusiveMaximum!==undefined?{exclusiveMaximum}:{}}}function mergeConstraint(self,that){const{ordered:selfOrdered,...selfRest}=self??{};const{ordered:thatOrdered,...thatRest}=that;const ordered=thatOrdered===undefined?selfOrdered:mergeOrderedConstraints(selfOrdered,thatOrdered);const out=combiner.combine(selfRest,thatRest);return{...out,...ordered===undefined?{}:{ordered}}}function collectChecks(checks){const filters=[];const arbitraries=[];function visit(check){if(check.annotations?.arbitrary){arbitraries.push(check.annotations.arbitrary)}if(check._tag!=="Filter"){for(const child of check.checks){visit(child)}}else{filters.push(check)}}checks?.forEach(visit);return{filters,arbitraries}}function constraintContext(arbitraries){const constraintAnnotations=arbitraries.map(({constraint})=>constraint).filter(isNotUndefined);return(ctx)=>{const constraint=constraintAnnotations.reduce((acc,c)=>mergeConstraint(acc,c),ctx.constraint);return{...ctx,constraint}}}function resetContext(ctx){return{...ctx,constraint:undefined}}function objectEntriesConstraints(ast,constraint,requiredKeys){if(constraint===undefined||constraint.minLength===undefined&&constraint.maxLength===undefined){return}if(constraint.minLength!==undefined&&ast.indexSignatures.length===0&&constraint.minLength>ast.propertySignatures.length){throw arbitraryError("object property constraints")}const out={};if(constraint.minLength!==undefined){out.minLength=Math.max(0,constraint.minLength-requiredKeys)}if(constraint.maxLength!==undefined){out.maxLength=constraint.maxLength-requiredKeys;if(out.maxLength<0){throw arbitraryError("object property constraints")}}validateArrayConstraints(out,"object property");return out}function objectWithOptionalCount(fc,pss,orderedNames,requiredKeys,optionalNames,constraint){const requiredCount=requiredKeys.length;if(constraint.maxLength!==undefined&&constraint.maxLength<requiredCount){throw arbitraryError("object property constraints")}const minOptional=constraint.minLength===undefined?0:Math.max(0,constraint.minLength-requiredCount);const maxOptional=constraint.maxLength===undefined?optionalNames.length:Math.min(optionalNames.length,constraint.maxLength-requiredCount);if(minOptional>maxOptional){throw arbitraryError("object property constraints")}const full=fc.record(pss,{requiredKeys:[...requiredKeys,...optionalNames]});const chosen=fc.shuffledSubarray([...optionalNames],{minLength:minOptional,maxLength:maxOptional});return fc.tuple(full,chosen).map(([base,names])=>{const keep=new Set([...requiredKeys,...names]);const out={};for(const name of orderedNames){if(keep.has(name)){out[name]=base[name]}}return out})}function toRangeConstraints(ordered,min5,max5,error){const out={};if(ordered?.minimum!==undefined){out.min=min5(ordered.minimum,ordered.exclusiveMinimum===true)}if(ordered?.maximum!==undefined){out.max=max5(ordered.maximum,ordered.exclusiveMaximum===true)}if(out.min!==undefined&&out.max!==undefined&&out.min>out.max){throw arbitraryError(error)}return out}function toIntegerConstraints(ordered){return toRangeConstraints(ordered,(minimum,excluded)=>excluded?Math.floor(minimum)+1:Math.ceil(minimum),(maximum,excluded)=>excluded?Math.ceil(maximum)-1:Math.floor(maximum),"integer constraints")}function toFloatConstraints(constraint,ordered){const out={...constraint?.noInfinity?{noDefaultInfinity:true}:{},...constraint?.noNaN?{noNaN:true}:{},...ordered?.minimum!==undefined?{min:ordered.minimum}:{},...ordered?.exclusiveMinimum!==undefined?{minExcluded:ordered.exclusiveMinimum}:{},...ordered?.maximum!==undefined?{max:ordered.maximum}:{},...ordered?.exclusiveMaximum!==undefined?{maxExcluded:ordered.exclusiveMaximum}:{}};if(out.min!==undefined&&out.max!==undefined&&(out.min>out.max||out.min===out.max&&(out.minExcluded||out.maxExcluded))){throw arbitraryError("number constraints")}return out}function toBigIntConstraints(ordered){return toRangeConstraints(ordered,(minimum,excluded)=>excluded?minimum+BigInt(1):minimum,(maximum,excluded)=>excluded?maximum-BigInt(1):maximum,"the ordered bigint constraints")}function makeLazy(normal,terminal){const out=(fc,ctx,recursionStack=emptyRecursionStack)=>normal(fc,ctx,recursionStack);out.terminal=(fc,ctx,recursionStack=emptyRecursionStack)=>terminal(fc,ctx,recursionStack);return out}function same(f){return makeLazy(f,f)}function getSuspendRecursion(fc,ast){const depthIdentifier=suspendDepthIdentifierMap.get(ast)??fc.createDepthIdentifier();suspendDepthIdentifierMap.set(ast,depthIdentifier);return{maxDepth:2,depthIdentifier}}function oneOf(fc,arbitraries){return arbitraries.length===0?undefined:arbitraries.length===1?arbitraries[0]:fc.oneof(...arbitraries)}var finiteNumberConstraint={noInfinity:true,noNaN:true};function finiteNumberContext(ctx){return{...ctx,constraint:finiteNumberConstraint}}function reportChecks(report,checks,path){function visit(check,covered){const arbitrary=check.annotations?.arbitrary;const nextCovered=covered||arbitrary?.constraint!==undefined||arbitrary?.candidate!==undefined;if(check._tag!=="Filter"){for(const child of check.checks){visit(child,nextCovered)}}else if(!nextCovered){const meta=check.annotations?.meta;const description=typeof meta==="object"&&meta!==null&&"_tag"in meta&&typeof meta._tag==="string"?meta._tag:check.annotations?.identifier??check.annotations?.expected;report.warnings.push({_tag:"OpaqueFilter",path,...description===undefined?{}:{description}})}}checks?.forEach((check)=>visit(check,false))}function collectReport(ast,report){const stack=new WeakSet;function visit(ast2,path){if(stack.has(ast2)){return}stack.add(ast2);reportChecks(report,ast2.checks,path);switch(ast2._tag){case"Declaration":ast2.typeParameters.forEach((tp)=>visit(tp,path));break;case"Arrays":{for(const[i,type]of[...ast2.elements,...ast2.rest].entries()){visit(type,[...path,i])}break}case"Objects":ast2.propertySignatures.forEach((ps)=>visit(ps.type,[...path,ps.name]));ast2.indexSignatures.forEach((is)=>{visit(is.parameter,path);visit(is.type,path)});break;case"Union":ast2.types.forEach((type)=>visit(type,path));break;case"TemplateLiteral":ast2.parts.forEach((part,i)=>visit(toEncoded(part),[...path,i]));break;case"Suspend":visit(ast2.thunk(),path);break}stack.delete(ast2)}visit(ast,[])}function applyCandidates(fc,ctx,arbitraries,base){const weighted=base===undefined?[]:[{arbitrary:base,weight:1}];for(const{candidate}of arbitraries){if(!candidate){continue}const arbitrary=candidate.make(fc,ctx);if(arbitrary===undefined){continue}const weight=candidate.weight??1;if(!globalThis.Number.isInteger(weight)||weight<=0){throw arbitraryError("a candidate with an invalid weight")}weighted.push({arbitrary,weight})}return weighted.length===0?undefined:weighted.length===1?weighted[0].arbitrary:fc.oneof(...weighted)}function applyFilterLayer(ast,checks,fc,ctx,base){const out=applyCandidates(fc,ctx,checks.arbitraries,base);return out===undefined?undefined:applyChecks(ast,checks.filters,out)}function normalizeDerivation(output,hasTypeParameters){if(!(typeof output==="object"&&output!==null&&("arbitrary"in output))){return{arbitrary:output,terminal:hasTypeParameters?undefined:output}}const terminal="terminal"in output?output.terminal:hasTypeParameters?undefined:output.arbitrary;return{arbitrary:output.arbitrary,terminal}}function makeTypeParameters(typeParameters,fc,ctx,recursionStack,lazyNormal){return typeParameters.map((tp)=>({arbitrary:lazyNormal?fc.constant(null).chain(()=>tp(fc,ctx,recursionStack)):tp(fc,ctx,recursionStack),terminal:tp.terminal(fc,ctx,recursionStack)}))}function filterLayer(ast,checks,normalBase,terminalBase){const f=constraintContext(checks.arbitraries);return makeLazy((fc,ctx,recursionStack)=>{const nextCtx=f(ctx);return applyFilterLayer(ast,checks,fc,nextCtx,normalBase(fc,ctx,nextCtx,recursionStack))},(fc,ctx,recursionStack)=>{const nextCtx=f(ctx);return applyFilterLayer(ast,checks,fc,nextCtx,terminalBase(fc,ctx,nextCtx,recursionStack))})}var memoized=memoize((ast)=>recur(ast,[]));function recur(ast,path){const annotation=resolve(ast)?.toArbitrary;if(annotation){const typeParameters=isDeclaration(ast)?ast.typeParameters.map((tp)=>recur(tp,path)):[];const checks=collectChecks(ast.checks);const derive=(lazyNormal)=>(fc,ctx,nextCtx,recursionStack)=>normalizeDerivation(annotation(makeTypeParameters(typeParameters,fc,resetContext(ctx),recursionStack,lazyNormal))(fc,nextCtx),typeParameters.length>0)[lazyNormal?"terminal":"arbitrary"];return filterLayer(ast,checks,derive(false),derive(true))}if(ast.checks){const checks=collectChecks(ast.checks);const lawc=recur(replaceChecks(ast,undefined),path);return filterLayer(ast,checks,(fc,_ctx,nextCtx,recursionStack)=>lawc(fc,nextCtx,recursionStack),(fc,_ctx,nextCtx,recursionStack)=>lawc.terminal(fc,nextCtx,recursionStack))}return base(ast,path)}function base(ast,path){switch(ast._tag){case"Never":case"Declaration":throw errorWithPath(`Unsupported AST ${ast._tag}`,path);case"Null":return same((fc)=>fc.constant(null));case"Void":case"Undefined":return same((fc)=>fc.constant(undefined));case"Unknown":case"Any":return same((fc)=>fc.anything());case"String":return same((fc,ctx)=>{const constraint=ctx.constraint;const patterns=constraint?.patterns;return patterns?fc.oneof(...patterns.map((pattern)=>fc.stringMatching(new RegExp(pattern)))):fc.string(lengthToFastCheckConstraints(constraint))});case"Number":return same((fc,ctx)=>{const constraint=ctx.constraint;const ordered=constraint?.ordered?.order===Number2?constraint.ordered:undefined;return constraint?.integer?fc.integer(toIntegerConstraints(ordered)):fc.float(toFloatConstraints(constraint,ordered))});case"Boolean":return same((fc)=>fc.boolean());case"BigInt":return same((fc,ctx)=>{const ordered=ctx.constraint?.ordered?.order===BigInt2?ctx.constraint.ordered:undefined;return fc.bigInt(toBigIntConstraints(ordered))});case"Symbol":return same((fc)=>fc.string().map(Symbol.for));case"Literal":return same((fc)=>fc.constant(ast.literal));case"UniqueSymbol":return same((fc)=>fc.constant(ast.symbol));case"ObjectKeyword":return same((fc)=>fc.oneof(fc.object(),fc.array(fc.anything())));case"Enum":return recur(enumsToLiterals(ast),path);case"TemplateLiteral":{const parts=ast.parts.map((part,i)=>recur(toEncoded(part),[...path,i]));return same((fc,ctx,recursionStack)=>fc.tuple(...parts.map((part)=>part(fc,finiteNumberContext(ctx),recursionStack))).map((segments)=>segments.map((segment)=>globalThis.String(segment)).join("")))}case"Arrays":{const elements=ast.elements.map((ast2,i)=>({ast:ast2,arbitrary:recur(ast2,[...path,i])}));const len=ast.elements.length;const rest=ast.rest.map((ast2,i)=>({ast:ast2,arbitrary:recur(ast2,[...path,len+i])}));const terminal=(fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const elementArbitraries=[];const optionals=[];let length=0;for(const element of elements){const out2=element.arbitrary.terminal(fc,reset,recursionStack);if(isOptional(element.ast)){optionals.push(out2);continue}if(out2===undefined){return}length++;elementArbitraries.push(out2.map(some2))}const minLength=ctx.constraint?.minLength??0;const needsRest=isReadonlyArrayNonEmpty(rest)&&minLength>length+optionals.length;const optionalTarget=needsRest?optionals.length:Math.max(0,minLength-length);let includedOptionals=0;for(const out2 of optionals){if(includedOptionals>=optionalTarget||out2===undefined){elementArbitraries.push(fc.constant(none2()));continue}includedOptionals++;length++;elementArbitraries.push(out2.map(some2))}if(includedOptionals<optionalTarget){return}let out=fc.tuple(...elementArbitraries).map(getSomes);if(isReadonlyArrayNonEmpty(rest)){const[head,...tail]=rest;const restCtx=ast.elements.length===0?ctx:reset;const minRestLength=Math.max(0,minLength-length-tail.length);const headArbitrary=minRestLength===0?undefined:head.arbitrary.terminal(fc,reset,recursionStack);if(minRestLength>0&&headArbitrary===undefined){return}const restArbitrary=minRestLength===0?fc.constant([]):array2(fc,{...restCtx,constraint:{...restCtx.constraint,minLength:minRestLength}},headArbitrary,true);out=appendArray(fc,out,len,restArbitrary);if(tail.length>0){const tailArbitraries=[];for(const element of tail){const out2=element.arbitrary.terminal(fc,reset,recursionStack);if(out2===undefined){return}tailArbitraries.push(out2)}const t=fc.tuple(...tailArbitraries);out=appendArray(fc,out,len,t)}}return out};return makeLazy((fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const elementArbitraries=elements.map(({ast:ast2,arbitrary})=>{const out2=arbitrary(fc,reset,recursionStack);return isOptional(ast2)?out2.chain((a)=>fc.boolean().map((b)=>b?some2(a):none2())):out2.map(some2)});let out=fc.tuple(...elementArbitraries).map(getSomes);if(isReadonlyArrayNonEmpty(rest)){const[head,...tail]=rest.map(({arbitrary})=>arbitrary(fc,reset,recursionStack));const restArbitrary=array2(fc,ast.elements.length===0?ctx:reset,head);out=appendArray(fc,out,len,restArbitrary);if(tail.length>0){const t=fc.tuple(...tail);out=appendArray(fc,out,len,t)}}if(ctx.recursion){const terminalOut=terminal(fc,ctx,recursionStack);if(terminalOut!==undefined){return fc.oneof(ctx.recursion,terminalOut,out)}}return out},terminal)}case"Objects":{const propertySignatures=ast.propertySignatures.map((ps)=>({ps,arbitrary:recur(ps.type,[...path,ps.name])}));const indexSignatures=ast.indexSignatures.map((is)=>({is,parameter:recur(is.parameter,path),type:recur(is.type,path)}));const terminal=(fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const pss={};const requiredKeys=[];const optionals=[];for(const{ps,arbitrary}of propertySignatures){const name=ps.name;const out2=arbitrary.terminal(fc,reset,recursionStack);if(isOptional(ps.type)){if(out2!==undefined){optionals.push([name,out2])}continue}if(out2===undefined){return}requiredKeys.push(name);pss[name]=out2}let optionalCount=Math.max(0,(ctx.constraint?.minLength??0)-requiredKeys.length);for(const[name,out2]of optionals){if(optionalCount===0){break}optionalCount--;requiredKeys.push(name);pss[name]=out2}if(optionalCount>0&&ast.indexSignatures.length===0){return}let out=fc.record(pss,{requiredKeys});const entriesConstraints=objectEntriesConstraints(ast,ctx.constraint,requiredKeys.length);const minEntries=entriesConstraints?.minLength??0;for(const{parameter,type}of indexSignatures){let entries3;if(minEntries===0){entries3=fc.constant([])}else{const key=parameter.terminal(fc,reset,recursionStack);const value3=type.terminal(fc,reset,recursionStack);if(key===undefined||value3===undefined){return}entries3=arrayWithConstraints(fc,fc.tuple(key,value3),{...entriesConstraints,maxLength:minEntries},entryComparator)}out=appendObjectEntries(out,entries3)}return out};return makeLazy((fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const pss={};const orderedNames=[];const requiredKeys=[];const optionalNames=[];for(const{ps,arbitrary}of propertySignatures){const name=ps.name;orderedNames.push(name);if(isOptional(ps.type)){optionalNames.push(name)}else{requiredKeys.push(name)}pss[name]=arbitrary(fc,reset,recursionStack)}const constraint=ctx.constraint;if(optionalNames.length>0&&indexSignatures.length===0&&constraint!==undefined&&(constraint.minLength!==undefined||constraint.maxLength!==undefined)){return objectWithOptionalCount(fc,pss,orderedNames,requiredKeys,optionalNames,constraint)}let out=fc.record(pss,{requiredKeys});const entriesConstraints=objectEntriesConstraints(ast,ctx.constraint,requiredKeys.length);for(const{parameter,type}of indexSignatures){const entry=fc.tuple(parameter(fc,reset,recursionStack),type(fc,reset,recursionStack));const entries3=arrayWithConstraints(fc,entry,entriesConstraints,entryComparator);out=appendObjectEntries(out,entries3)}return out},terminal)}case"Union":{const types=ast.types.map((ast2)=>recur(ast2,path));const terminal=(fc,ctx,recursionStack)=>oneOf(fc,types.map((type)=>type.terminal(fc,ctx,recursionStack)).filter(isNotUndefined));return makeLazy((fc,ctx,recursionStack)=>{const arbitraries=types.map((type)=>type(fc,ctx,recursionStack));if(ctx.recursion){const terminalOut=terminal(fc,ctx,recursionStack);if(terminalOut!==undefined){return fc.oneof(ctx.recursion,terminalOut,...arbitraries)}}const out=oneOf(fc,arbitraries);if(out===undefined){throw arbitraryError("a union with no members")}return out},terminal)}case"Suspend":{const memo=arbitraryMemoMap.get(ast);if(memo)return memo;const get5=memoizeThunk(()=>recur(ast.thunk(),path));const out=makeLazy((fc,ctx,recursionStack)=>{const recursion=getSuspendRecursion(fc,ast);const nextCtx={...ctx,recursion};const nextStack=recursionStack.includes(ast)?recursionStack:[...recursionStack,ast];const terminal=get5().terminal(fc,nextCtx,nextStack);if(terminal===undefined){throw errorWithPath("Unable to derive an arbitrary for a recursive schema without a finite generation path",path)}return fc.oneof(recursion,terminal,fc.constant(null).chain(()=>get5()(fc,nextCtx,nextStack)))},(fc,ctx,recursionStack)=>{if(recursionStack.includes(ast)){return}const recursion=getSuspendRecursion(fc,ast);return get5().terminal(fc,{...ctx,recursion},[...recursionStack,ast])});arbitraryMemoMap.set(ast,out);return out}}}var toConstructorAST=memoize((ast)=>{switch(ast._tag){case"Declaration":{const getLink=ast.annotations?.[ClassTypeId];if(isFunction(getLink)){const link=getLink(ast.typeParameters);const to=toConstructorAST(link.to);return replaceEncoding(ast,to===link.to?[link]:[new Link(to,link.transformation)])}return ast}case"Objects":case"Arrays":return ast.recur((ast2)=>{const defaultValue=ast2.context?.defaultValue;if(defaultValue){const out=toConstructorAST(ast2);return replaceEncoding(out,out.encoding?[...out.encoding,...defaultValue]:defaultValue)}return toConstructorAST(ast2)});case"Suspend":return ast.recur(toConstructorAST);default:return ast}});function makeEffect(schema){const ast=toConstructorAST(toType(schema.ast));const parser=run2(ast);return(input,options)=>{return parser(input,options?.disableChecks?options?.parseOptions?{...options.parseOptions,disableChecks:true}:{disableChecks:true}:options?.parseOptions)}}function makeOption(schema){const parser=makeEffect(schema);return(input,options)=>{const exit3=runSyncExit2(parser(input,options));if(isSuccess4(exit3)){return some2(exit3.value)}getSchemaIssueOrThrow(exit3.cause,"Option adapter can only return none for schema issues");return none2()}}function make23(schema){const parser=makeEffect(schema);return(input,options)=>{const exit3=runSyncExit2(parser(input,options));if(isSuccess4(exit3)){return exit3.value}const issue=getSchemaIssueOrThrow(exit3.cause,"Constructor adapter can only throw schema issues");throw new Error(issue.toString(),{cause:issue})}}function is(schema){return _is(schema.ast)}function _is(ast){const parser=asExit(run2(toType(ast)));return(input)=>{const exit3=parser(input,defaultParseOptions);if(isSuccess4(exit3)){return true}getSchemaIssueOrThrow(exit3.cause,"Type guard adapter can only return false for schema issues");return false}}function _issue(ast){const parser=run2(ast);return(input,options)=>{const exit3=runSyncExit2(parser(input,options));if(isSuccess4(exit3)){return}return getSchemaIssueOrThrow(exit3.cause,"Issue adapter can only return schema issues")}}function asserts(schema,input){const parser=asExit(run2(toType(schema.ast)));const exit3=parser(input,defaultParseOptions);if(isFailure4(exit3)){const issue=getSchemaIssueOrThrow(exit3.cause,"Assertion adapter can only throw schema issues");throw new Error(issue.toString(),{cause:issue})}}function decodeUnknownEffect(schema,options){const parser=run2(schema.ast);return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}var decodeEffect=decodeUnknownEffect;function decodeUnknownExit(schema,options){return asExit(decodeUnknownEffect(schema,options))}function decodeUnknownOption(schema,options){return asOption(decodeUnknownEffect(schema,options))}var decodeOption=decodeUnknownOption;function decodeUnknownResult(schema,options){return asResult(decodeUnknownEffect(schema,options))}function decodeUnknownSync(schema,options){return asSync(decodeUnknownEffect(schema,options))}var decodeSync=decodeUnknownSync;function encodeUnknownEffect(schema,options){const parser=run2(flip3(schema.ast));return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}function encodeUnknownExit(schema,options){return asExit(encodeUnknownEffect(schema,options))}function encodeUnknownOption(schema,options){return asOption(encodeUnknownEffect(schema,options))}var encodeOption=encodeUnknownOption;function encodeUnknownResult(schema,options){return asResult(encodeUnknownEffect(schema,options))}function encodeUnknownSync(schema,options){return asSync(encodeUnknownEffect(schema,options))}var encodeSync=encodeUnknownSync;var mergeParseOptions=(options,overrideOptions)=>overrideOptions===undefined?options:{...options,...overrideOptions};function run2(ast){const parser=recur2(ast);return(input,options)=>flatMapEager2(parser(some2(input),options??defaultParseOptions),(oa)=>{if(oa._tag==="None"){return fail6(new InvalidValue(oa))}return succeed6(oa.value)})}function asExit(parser){return(input,options)=>runSyncExit2(parser(input,options))}function asOption(parser){const parserExit=asExit(parser);return(input,options)=>{const exit3=parserExit(input,options);if(isSuccess4(exit3)){return some2(exit3.value)}getSchemaIssueOrThrow(exit3.cause,"Option adapter can only return none for schema issues");return none2()}}function asResult(parser){const parserExit=asExit(parser);return(input,options)=>{const exit3=parserExit(input,options);if(isSuccess4(exit3)){return succeed2(exit3.value)}return fail2(getSchemaIssueOrThrow(exit3.cause,"Result adapter can only return schema issues"))}}function asSync(parser){const parserExit=asExit(parser);return(input,options)=>{const exit3=parserExit(input,options);if(isSuccess4(exit3)){return exit3.value}const issue=getSchemaIssueOrThrow(exit3.cause,"Sync adapter can only throw schema issues");throw new Error(issue.toString(),{cause:issue})}}function mapSchemaIssueEffect(self,f){return catchCause2(self,(cause)=>failCauseSync2(()=>map6(cause,f)))}var recur2=memoize((ast)=>{let parser;const checks=ast.checks;const encoding=ast.encoding;const links=encoding;const len=links?.length??0;const encodingChecks=ast.encodingChecks;const astOptions=(checks?checks[checks.length-1].annotations:ast.annotations)?.["parseOptions"];if(!ast.context&&!encoding&&!checks&&!encodingChecks){return(ou,options)=>{parser??=ast.getParser(recur2);if(astOptions){options={...options,...astOptions}}return parser(ou,options)}}const isStructural=isArrays(ast)||isObjects(ast)||isDeclaration(ast)&&ast.typeParameters.length>0;const structuralChecks=checks&&isStructural?checks.filter((check)=>check.annotations?.[STRUCTURAL_ANNOTATION_KEY]):undefined;return(ou,options)=>{if(astOptions){options={...options,...astOptions}}let srou;if(links){for(let i=len-1;i>=0;i--){const link=links[i];const to=link.to;const parser2=recur2(to);srou=srou?flatMapEager2(srou,(ou2)=>parser2(ou2,options)):parser2(ou,options);if(link.transformation._tag==="Transformation"){const getter=link.transformation.decode;srou=flatMapEager2(srou,(ou2)=>getter.run(ou2,options))}else{srou=link.transformation.decode(srou,options)}}srou=mapSchemaIssueEffect(srou,(issue)=>new Encoding(ast,ou,issue))}parser??=ast.getParser(recur2);const parseLocal=(localOu)=>{let sroa2=parser(localOu,options);if(encodingChecks&&!options?.disableChecks){sroa2=flatMapEager2(sroa2,(oa)=>{if(isSome2(localOu)&&isSome2(oa)){const issues=[];collectIssues(encodingChecks,localOu.value,issues,ast,options);if(isArrayNonEmpty2(issues)){return fail6(new Composite(ast,localOu,issues))}}return succeed6(oa)})}if(checks&&!options?.disableChecks){if(options?.errors==="all"&&structuralChecks&&structuralChecks.length>0&&isSome2(localOu)){sroa2=mapSchemaIssueEffect(sroa2,(issue)=>{const issues=[];collectIssues(structuralChecks,localOu.value,issues,ast,options);const out=isArrayNonEmpty2(issues)?issue._tag==="Composite"&&issue.ast===ast?new Composite(ast,issue.actual,[...issue.issues,...issues]):new Composite(ast,localOu,[issue,...issues]):issue;return out})}sroa2=flatMapEager2(sroa2,(oa)=>{if(isSome2(oa)){const value3=oa.value;const issues=[];collectIssues(checks,value3,issues,ast,options);if(isArrayNonEmpty2(issues)){return fail6(new Composite(ast,oa,issues))}}return succeed6(oa)})}return sroa2};const sroa=srou?flatMapEager2(srou,parseLocal):parseLocal(ou);return sroa}});var toEquivalence=memoize((ast)=>{return recur3(ast,[])});function recur3(ast,path){const annotation=resolve(ast)?.["toEquivalence"];if(annotation){return annotation(isDeclaration(ast)?ast.typeParameters.map((tp)=>recur3(tp,path)):[])}switch(ast._tag){case"Never":throw errorWithPath(`Unsupported AST ${ast._tag}`,path);case"Declaration":case"Null":case"Undefined":case"Void":case"Unknown":case"Any":case"String":case"Number":case"Boolean":case"BigInt":case"Symbol":case"Literal":case"UniqueSymbol":case"ObjectKeyword":case"Enum":case"TemplateLiteral":return equals;case"Arrays":{const elements=ast.elements.map((e,i)=>recur3(e,[...path,i]));const len=ast.elements.length;const rest=ast.rest.map((r,i)=>recur3(r,[...path,len+i]));return make3((a,b)=>{if(!Array.isArray(a)||!Array.isArray(b)){return false}const len2=a.length;if(len2!==b.length){return false}let i=0;for(;i<Math.min(len2,ast.elements.length);i++){if(!elements[i](a[i],b[i])){return false}}if(rest.length>0){const[head,...tail]=rest;for(;i<len2-tail.length;i++){if(!head(a[i],b[i])){return false}}for(let j=0;j<tail.length;j++){if(!tail[j](a[i+j],b[i+j])){return false}}}return true})}case"Objects":{if(ast.propertySignatures.length===0&&ast.indexSignatures.length===0){return equals}const propertySignatures=ast.propertySignatures.map((ps)=>recur3(ps.type,[...path,ps.name]));const indexSignatures=ast.indexSignatures.map((is2)=>recur3(is2.type,path));return make3((a,b)=>{if(!isObject(a)||!isObject(b)){return false}for(let i=0;i<propertySignatures.length;i++){const ps=ast.propertySignatures[i];const name=ps.name;const aHas=Object.hasOwn(a,name);const bHas=Object.hasOwn(b,name);if(isOptional(ps.type)){if(aHas!==bHas){return false}}if(aHas&&bHas&&!propertySignatures[i](a[name],b[name])){return false}}for(let i=0;i<indexSignatures.length;i++){const is2=ast.indexSignatures[i];const aKeys=getIndexSignatureKeys(a,is2.parameter);const bKeys=getIndexSignatureKeys(b,is2.parameter);if(aKeys.length!==bKeys.length)return false;for(let j=0;j<aKeys.length;j++){const key=aKeys[j];if(!Object.hasOwn(b,key)||!indexSignatures[i](a[key],b[key])){return false}}}return true})}case"Union":return make3((a,b)=>{const candidates=getCandidates(a,ast.types);const types=candidates.map(_is);for(let i=0;i<candidates.length;i++){const is2=types[i];if(is2(a)&&is2(b)){return recur3(candidates[i],path)(a,b)}}return false});case"Suspend":{const get5=memoizeThunk(()=>recur3(ast.thunk(),path));return make3((a,b)=>get5()(a,b))}}}function escapeToken(token){return token.replace(/~/g,"~0").replace(/\//g,"~1")}function unescapeToken(token){return token.replace(/~1/g,"/").replace(/~0/g,"~")}var RegExp2=globalThis.RegExp;var escape=(string3)=>string3.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var TypeId30="~effect/SchemaError/SchemaError";class SchemaError extends TaggedError2("SchemaError"){[TypeId30]=TypeId30;constructor(issue){super({issue})}get message(){return this.issue.toString()}toString(){return`SchemaError(${this.message})`}}function isSchemaError(u){return hasProperty(u,TypeId30)}var TypeId31="~effect/Schema/Schema";var SchemaProto={[TypeId31]:TypeId31,pipe(){return pipeArguments(this,arguments)},annotate(annotations){return this.rebuild(annotate(this.ast,annotations))},annotateKey(annotations){return this.rebuild(annotateKey(this.ast,annotations))},check(...checks){return this.rebuild(appendChecks(this.ast,checks))}};function make24(ast,options){const self=Object.create(SchemaProto);if(options){Object.assign(self,options)}self.ast=ast;self.rebuild=(ast2)=>make24(ast2,options);const makeEffect2=makeEffect(self);self.makeEffect=(input,options2)=>fromIssueEffect(makeEffect2(input,options2));self.make=make23(self);self.makeOption=makeOption(self);return self}function fromIssueEffect(self){return catchCause2(self,(cause)=>failCauseSync2(()=>map6(cause,(issue)=>new SchemaError(issue))))}var jsonReorder=makeReorder(getJsonPriority);function getJsonPriority(ast){switch(ast._tag){case"BigInt":case"Symbol":case"UniqueSymbol":return 0;default:return 1}}function makeReorder(getPriority){return(types)=>{const indexMap=new Map;for(let i=0;i<types.length;i++){indexMap.set(toEncoded(types[i]),i)}const sortedTypes=[...types].sort((a,b)=>{a=toEncoded(a);b=toEncoded(b);const pa=getPriority(a);const pb=getPriority(b);if(pa!==pb)return pa-pb;return indexMap.get(a)-indexMap.get(b)});const orderChanged=sortedTypes.some((ast,index2)=>ast!==types[index2]);if(!orderChanged)return types;return sortedTypes}}function fromAST(ast){const{references,representations:schemas}=fromASTs([ast]);return{representation:schemas[0],references}}function fromASTs(asts){const references={};const referenceMap=new Map;const uniqueReferences=new Set;const visiting=new Set;const schemas=map4(asts,(ast)=>recur4(ast));return{representations:schemas,references};function gen3(prefix){let candidate=prefix;let suffix=0;while(uniqueReferences.has(candidate)){candidate=`${prefix}${++suffix}`}uniqueReferences.add(candidate);return candidate}function recur4(ast,prefix){const found=referenceMap.get(ast);if(found!==undefined){return{_tag:"Reference",$ref:found}}const last=getLastEncoding(ast);const identifier2=resolveIdentifier(ast)??prefix;if(ast!==last){return recur4(last,identifier2)}if(identifier2!==undefined){const reference=gen3(identifier2);referenceMap.set(ast,reference);const out2=on(ast);const found2=references[identifier2];if(found2!==undefined&&equals(out2,found2)){referenceMap.set(ast,identifier2);return{_tag:"Reference",$ref:identifier2}}references[reference]=out2;return{_tag:"Reference",$ref:reference}}if(visiting.has(ast)){const reference=gen3(`${ast._tag}_`);referenceMap.set(ast,reference);return{_tag:"Reference",$ref:reference}}visiting.add(ast);const out=on(ast);visiting.delete(ast);const ref=referenceMap.get(ast);if(ref!==undefined){references[ref]=out;return{_tag:"Reference",$ref:ref}}return out}function getEncodedSchema(last){const getLink=last.annotations?.toCodecJson??last.annotations?.toCodec;if(isFunction(getLink)){return replaceEncoding(last,[getLink(last.typeParameters.map((tp)=>make24(toEncoded(tp))))])}return null_}function on(last){const annotations=fromASTAnnotations(last.annotations);switch(last._tag){case"Declaration":{const encodedSchema=recur4(getEncodedSchema(last));return{_tag:"Declaration",typeParameters:last.typeParameters.map((ast)=>recur4(ast)),encodedSchema,checks:fromASTChecks(last.checks),...annotations}}case"Null":case"Undefined":case"Void":case"Never":case"Unknown":case"Any":case"Boolean":case"Symbol":case"ObjectKeyword":return{_tag:last._tag,...annotations};case"String":{const contentMediaType=last.annotations?.contentMediaType;const contentSchema=last.annotations?.contentSchema;return{_tag:last._tag,checks:fromASTChecks(last.checks),...annotations,...typeof contentMediaType==="string"&&isAST(contentSchema)?{contentSchema:recur4(contentSchema)}:undefined}}case"Number":case"BigInt":return{_tag:last._tag,checks:fromASTChecks(last.checks),...annotations};case"Literal":return{_tag:last._tag,literal:last.literal,...annotations};case"UniqueSymbol":return{_tag:last._tag,symbol:last.symbol,...annotations};case"Enum":return{_tag:last._tag,enums:last.enums,...annotations};case"TemplateLiteral":return{_tag:last._tag,parts:last.parts.map((ast)=>recur4(ast)),...annotations};case"Arrays":return{_tag:last._tag,elements:last.elements.map((e)=>{const last2=getLastEncoding(e);return{isOptional:isOptional(last2),type:recur4(e),...fromASTAnnotations(last2.context?.annotations)}}),rest:last.rest.map((ast)=>recur4(ast)),checks:fromASTChecks(last.checks),...annotations};case"Objects":return{_tag:last._tag,propertySignatures:last.propertySignatures.map((ps)=>{const last2=getLastEncoding(ps.type);return{name:ps.name,type:recur4(ps.type),isOptional:isOptional(last2),isMutable:isMutable(last2),...fromASTAnnotations(last2.context?.annotations)}}),indexSignatures:last.indexSignatures.map((is2)=>({parameter:recur4(is2.parameter),type:recur4(is2.type)})),checks:fromASTChecks(last.checks),...annotations};case"Union":{const types=jsonReorder(last.types);return{_tag:last._tag,types:types.map((ast)=>recur4(ast)),mode:last.mode,...annotations}}case"Suspend":{return{_tag:"Suspend",checks:[],thunk:recur4(last.thunk()),...annotations}}}}function fromASTChecks(checks){if(!checks)return[];return checks.map(getCheck).filter((c)=>c!==undefined);function getCheck(c){switch(c._tag){case"Filter":{const meta=c.annotations?.meta;if(meta){return{_tag:"Filter",meta:meta._tag==="isPropertyNames"?{_tag:"isPropertyNames",propertyNames:recur4(meta.propertyNames)}:meta,...fromASTAnnotations(c.annotations)}}return}case"FilterGroup":{const checks2=fromASTChecks(c.checks);if(isArrayNonEmpty2(checks2)){return{_tag:"FilterGroup",checks:checks2,...fromASTAnnotations(c.annotations)}}}}}}}var fromASTBlacklist=new Set(["~structural","~sentinels","meta","arbitrary","toArbitrary","toEquivalence","toFormatter","toCodec","toCodecJson","toCodecIso",ClassTypeId]);var standardJsonSchemaAnnotationKeys=new Set(["title","description","default","examples","readOnly","writeOnly","format","contentEncoding","contentMediaType","contentSchema"]);function fromASTAnnotations(annotations){if(annotations!==undefined){const filtered=filter3(annotations,(_,k)=>!fromASTBlacklist.has(k));if(!isEmptyRecord(filtered)){return{annotations:filtered}}}return}function toJsonSchemaDocument(document,options){const{definitions,dialect:source,schemas}=toJsonSchemaMultiDocument({representations:[document.representation],references:document.references},options);const schema=schemas[0];return{dialect:source,schema,definitions}}function toJsonSchemaMultiDocument(multiDocument,options){const generateDescriptions=options?.generateDescriptions??false;const additionalProperties=options?.additionalProperties??false;const includeAnnotationKey=options?.includeAnnotationKey;const definitions=map3(multiDocument.references,(d)=>recur4(d));return{dialect:"draft-2020-12",schemas:map4(multiDocument.representations,(s)=>recur4(s)),definitions};function recur4(s){let js=on(s);if("annotations"in s){const a=collectJsonSchemaAnnotations(s.annotations);if(a){js={...js,...a}}}if("checks"in s){const checks=collectJsonSchemaChecks(s.checks,js.type);for(const check of checks){js=appendJsonSchema(js,check)}}return js}function on(schema){switch(schema._tag){case"Any":case"Unknown":return{};case"ObjectKeyword":return{anyOf:[{type:"object"},{type:"array"}]};case"Void":case"Undefined":return{type:"null"};case"BigInt":return{type:"string",allOf:[{pattern:"^-?\\d+$"}]};case"Symbol":case"UniqueSymbol":return{type:"string",allOf:[{pattern:"^Symbol\\((.*)\\)$"}]};case"Declaration":return recur4(schema.encodedSchema);case"Suspend":return recur4(schema.thunk);case"Reference":return{$ref:`#/$defs/${escapeToken(schema.$ref)}`};case"Null":return{type:"null"};case"Never":return{not:{}};case"String":{const out={type:"string"};if(schema.contentMediaType!==undefined){out.contentMediaType=schema.contentMediaType}if(schema.contentSchema!==undefined){out.contentSchema=recur4(schema.contentSchema)}return out}case"Number":return hasCheck2(schema.checks,"isInt")?{type:"integer"}:hasCheck2(schema.checks,"isFinite")?{type:"number"}:{anyOf:[{type:"number"},{type:"string",enum:["NaN"]},{type:"string",enum:["Infinity"]},{type:"string",enum:["-Infinity"]}]};case"Boolean":return{type:"boolean"};case"Literal":{const literal=schema.literal;if(typeof literal==="string"){return{type:"string",enum:[literal]}}if(typeof literal==="number"){return{type:"number",enum:[literal]}}if(typeof literal==="boolean"){return{type:"boolean",enum:[literal]}}return{type:"string",enum:[String(literal)]}}case"Enum":{return recur4({_tag:"Union",types:schema.enums.map(([title,value3])=>({_tag:"Literal",literal:value3,annotations:{title}})),mode:"anyOf",annotations:schema.annotations})}case"TemplateLiteral":{const pattern=schema.parts.map(getPartPattern).join("");return{type:"string",pattern:`^${pattern}$`}}case"Arrays":{if(schema.rest.length>1){throw new globalThis.Error("Generating a JSON Schema for post-rest elements is not supported")}const out={type:"array"};let minItems=schema.elements.length;const prefixItems=schema.elements.map((e)=>{if(e.isOptional){minItems--}const v=recur4(e.type);const a=collectJsonSchemaAnnotations(e.annotations);return a?appendJsonSchema(v,a):v});if(prefixItems.length>0){out.prefixItems=prefixItems;out.maxItems=schema.elements.length;if(minItems>0){out.minItems=minItems}}else{out.items=false}if(schema.rest.length>0){delete out.maxItems;const rest=recur4(schema.rest[0]);if(Object.keys(rest).length>0){out.items=rest}else{delete out.items}}return out}case"Objects":{if(schema.propertySignatures.length===0&&schema.indexSignatures.length===0){return{anyOf:[{type:"object"},{type:"array"}]}}const out={type:"object"};const properties={};const required=[];for(const ps of schema.propertySignatures){const name=ps.name;if(typeof name!=="string"){throw new globalThis.Error(`Unsupported property signature name: ${format(name)}`)}const v=recur4(ps.type);const a=collectJsonSchemaAnnotations(ps.annotations);properties[name]=a?appendJsonSchema(v,a):v;if(!ps.isOptional){required.push(name)}}if(Object.keys(properties).length>0){out.properties=properties}if(required.length>0){out.required=required}out.additionalProperties=additionalProperties;const patternProperties={};for(const is2 of schema.indexSignatures){let type=recur4(is2.type);if(Object.keys(type).length===1&&"not"in type){type=false}const patterns=getParameterPatterns(is2.parameter);if(patterns.length>0){for(const pattern of patterns){patternProperties[pattern]=type}}else{out.additionalProperties=type}}if(Object.keys(patternProperties).length>0){out.patternProperties=patternProperties;delete out.additionalProperties}if(isObject(out.additionalProperties)&&isEmptyRecord(out.additionalProperties)){delete out.additionalProperties}return out}case"Union":{const types=schema.types.map(recur4);if(types.length===0){return{not:{}}}if(types.length>1){const compacted=compactEnums(types);if(compacted)return compacted}return schema.mode==="anyOf"?{anyOf:types}:{oneOf:types}}}}function compactEnums(types){let sharedType;const values3=[];for(const t of types){const keys3=Object.keys(t);if(keys3.length!==2||t.type===undefined||!Array.isArray(t.enum)||t.enum.length===0){return}if(sharedType===undefined){sharedType=t.type}else if(t.type!==sharedType){return}for(const v of t.enum){values3.push(v)}}return{type:sharedType,enum:values3}}function collectJsonSchemaAnnotations(annotations){if(annotations===undefined)return;const out={};if(typeof annotations.title==="string")out.title=annotations.title;if(typeof annotations.description==="string")out.description=annotations.description;else if(generateDescriptions&&typeof annotations.expected==="string")out.description=annotations.expected;if(annotations.default!==undefined)out.default=annotations.default;if(Array.isArray(annotations.examples))out.examples=annotations.examples;if(typeof annotations.readOnly==="boolean")out.readOnly=annotations.readOnly;if(typeof annotations.writeOnly==="boolean")out.writeOnly=annotations.writeOnly;if(typeof annotations.format==="string")out.format=annotations.format;if(typeof annotations.contentEncoding==="string")out.contentEncoding=annotations.contentEncoding;if(typeof annotations.contentMediaType==="string")out.contentMediaType=annotations.contentMediaType;if(includeAnnotationKey){for(const[key,value3]of Object.entries(annotations)){if(value3===undefined)continue;if(standardJsonSchemaAnnotationKeys.has(key))continue;if(!includeAnnotationKey(key))continue;out[key]=value3}}if(Object.keys(out).length>0)return out}function collectJsonSchemaChecks(checks,type){return checks.map(collectJsonSchemaCheck).filter((c)=>c!==undefined);function collectJsonSchemaCheck(check){switch(check._tag){case"Filter":return filterToJsonSchema(check,type);case"FilterGroup":{const checks2=check.checks.map(collectJsonSchemaCheck).filter((c)=>c!==undefined);if(checks2.length===0)return;let out={allOf:checks2};const a=collectJsonSchemaAnnotations(check.annotations);if(a){out={...out,...a}}return out}}}}function filterToJsonSchema(filter10,type){const meta=filter10.meta;if(!meta)return;let out=on2(meta);const a=collectJsonSchemaAnnotations(filter10.annotations);if(a){out={...out,...a}}return out;function on2(meta2){switch(meta2._tag){case"isMinLength":return type==="array"?{minItems:meta2.minLength}:{minLength:meta2.minLength};case"isMaxLength":return type==="array"?{maxItems:meta2.maxLength}:{maxLength:meta2.maxLength};case"isLengthBetween":return type==="array"?{allOf:[{minItems:meta2.minimum},{maxItems:meta2.maximum}]}:{allOf:[{minLength:meta2.minimum},{maxLength:meta2.maximum}]};case"isPattern":case"isGUID":case"isULID":case"isBase64":case"isBase64Url":case"isStartsWith":case"isEndsWith":case"isIncludes":case"isUppercased":case"isLowercased":case"isCapitalized":case"isUncapitalized":case"isTrimmed":case"isStringFinite":case"isStringBigInt":case"isStringSymbol":return{pattern:meta2.regExp.source};case"isUUID":return{pattern:meta2.regExp.source,format:"uuid"};case"isFinite":case"isInt":return;case"isMultipleOf":return{multipleOf:meta2.divisor};case"isGreaterThanOrEqualTo":return{minimum:meta2.minimum};case"isLessThanOrEqualTo":return{maximum:meta2.maximum};case"isGreaterThan":return{exclusiveMinimum:meta2.exclusiveMinimum};case"isLessThan":return{exclusiveMaximum:meta2.exclusiveMaximum};case"isBetween":{return{[meta2.exclusiveMinimum?"exclusiveMinimum":"minimum"]:meta2.minimum,[meta2.exclusiveMaximum?"exclusiveMaximum":"maximum"]:meta2.maximum}}case"isUnique":return{uniqueItems:true};case"isMinProperties":return{minProperties:meta2.minProperties};case"isMaxProperties":return{maxProperties:meta2.maxProperties};case"isPropertiesLengthBetween":return{minProperties:meta2.minimum,maxProperties:meta2.maximum};case"isPropertyNames":return{propertyNames:recur4(meta2.propertyNames)};case"isDateValid":return{format:"date-time"}}}}function getParameterPatterns(parameter){switch(parameter._tag){default:throw new globalThis.Error(`Unsupported index signature parameter: ${parameter._tag}`);case"Reference":return getParameterPatterns(multiDocument.references[parameter.$ref]);case"String":return getPatterns(parameter);case"TemplateLiteral":return[`^${parameter.parts.map(getPartPattern).join("")}$`];case"Union":return parameter.types.flatMap(getParameterPatterns)}}}function getPatterns(s){return recur4(s.checks);function recur4(checks){return checks.flatMap((c)=>{switch(c._tag){case"Filter":{if("regExp"in c.meta){return[c.meta.regExp.source]}return[]}case"FilterGroup":return recur4(c.checks)}})}}function hasCheck2(checks,tag){return checks.some((c)=>{switch(c._tag){case"Filter":return c.meta._tag===tag;case"FilterGroup":return hasCheck2(c.checks,tag)}})}function appendJsonSchema(a,b){if(Object.keys(a).length===0)return b;const len=Object.keys(b).length;if(len===0)return a;const members=Array.isArray(b.allOf)&&len===1?b.allOf:[b];if(Array.isArray(a.allOf)){return{...a,allOf:[...a.allOf,...members]}}if(typeof a.$ref==="string"){return{allOf:[a,...members]}}return{...a,allOf:members}}function getPartPattern(part){switch(part._tag){case"Literal":return escape(globalThis.String(part.literal));case"String":return STRING_PATTERN;case"Number":return FINITE_PATTERN;case"TemplateLiteral":return part.parts.map(getPartPattern).join("");case"Union":return part.types.map(getPartPattern).join("|");default:throw new globalThis.Error("Unsupported part",{cause:part})}}function get5(oldValue,newValue){if(Object.is(oldValue,newValue))return[];const patches=[];if(Array.isArray(oldValue)&&Array.isArray(newValue)){const len1=oldValue.length;const len2=newValue.length;const shared=Math.min(len1,len2);for(let i=0;i<shared;i++){const path=`/${i}`;const patch=get5(oldValue[i],newValue[i]);for(const op of patch){prefixPathInPlace(op,path);patches.push(op)}}for(let i=len1-1;i>=len2;i--){patches.push({op:"remove",path:`/${i}`})}for(let i=len1;i<len2;i++){patches.push({op:"add",path:`/${i}`,value:newValue[i]})}return patches}if(isJsonObject(oldValue)&&isJsonObject(newValue)){const keys1=Object.keys(oldValue);const keys22=Object.keys(newValue);const allKeys=Array.from(new Set([...keys1,...keys22])).sort();for(const key of allKeys){const esc=escapeToken(key);const path=`/${esc}`;const hasKey1=Object.hasOwn(oldValue,key);const hasKey2=Object.hasOwn(newValue,key);if(hasKey1&&hasKey2){const patch=get5(oldValue[key],newValue[key]);for(const op of patch){prefixPathInPlace(op,path);patches.push(op)}}else if(!hasKey1&&hasKey2){patches.push({op:"add",path,value:newValue[key]})}else if(hasKey1&&!hasKey2){patches.push({op:"remove",path})}}return patches}patches.push({op:"replace",path:"",value:newValue});return patches}function apply(patch,oldValue){let doc=oldValue;for(const op of patch){switch(op.op){case"replace":{doc=op.path===""?op.value:setAt(doc,op.path,op.value,"replace");break}case"add":{doc=addAt(doc,op.path,op.value);break}case"remove":{doc=setAt(doc,op.path,undefined,"remove");break}}}return doc}function prefixPathInPlace(op,parent){op.path=op.path===""?parent:parent+op.path}function isJsonObject(value3){return isObject(value3)}function tokenize(pointer){if(pointer==="")return[];if(pointer.charCodeAt(0)!==47){throw new Error(`Invalid JSON Pointer, it must start with "/": ${format(pointer)}`)}return pointer.split("/").slice(1).map(unescapeToken)}function toIndex(token){if(!/^(0|[1-9]\d*)$/.test(token)){throw new Error(`Invalid array index: "${token}"`)}return Number(token)}function addAt(doc,pointer,val){if(pointer==="")return val;const resolved=resolveParent(doc,pointer);if(resolved===null){throw new Error(`Cannot add at "${pointer}" (parent not found or not a container).`)}const{lastToken,parent,stack}=resolved;if(Array.isArray(parent)){const idx=lastToken==="-"?parent.length:toIndex(lastToken);if(idx<0||idx>parent.length)throw new Error(`Array index out of bounds at "${pointer}".`);const updated=parent.slice();updated.splice(idx,0,val);return rebuildFromStack(stack,updated)}if(isJsonObject(parent)){const updated={...parent};updated[lastToken]=val;return rebuildFromStack(stack,updated)}throw new Error(`Cannot add at "${pointer}" (parent not found or not a container).`)}function setAt(doc,pointer,val,mode){if(pointer===""){if(mode==="remove"||val===undefined)throw new Error("Unsupported operation at the root");return val}const resolved=resolveParent(doc,pointer);if(resolved===null){throw new Error(`Cannot ${mode} at "${pointer}" (parent not found or not a container).`)}const{lastToken,parent,stack}=resolved;if(Array.isArray(parent)){if(lastToken==="-")throw new Error(`"-" is not valid for ${mode} at "${pointer}".`);const idx=toIndex(lastToken);if(idx<0||idx>=parent.length)throw new Error(`Array index out of bounds at "${pointer}".`);const updated=parent.slice();if(mode==="remove")updated.splice(idx,1);else updated[idx]=val;return rebuildFromStack(stack,updated)}if(isJsonObject(parent)){if(!Object.hasOwn(parent,lastToken)){throw new Error(`Property "${lastToken}" does not exist at "${pointer}".`)}const updated={...parent};if(mode==="remove")delete updated[lastToken];else updated[lastToken]=val;return rebuildFromStack(stack,updated)}throw new Error(`Cannot ${mode} at "${pointer}" (parent not found or not a container).`)}function resolveParent(doc,pointer){const tokens=tokenize(pointer);if(tokens.length===0)return null;const lastToken=tokens[tokens.length-1];const stack=[];let cur=doc;for(let i=0;i<tokens.length-1;i++){const token=tokens[i];if(cur==null)return null;if(Array.isArray(cur)){const idx=toIndex(token);if(idx<0||idx>=cur.length)return null;stack.push({container:cur,token:idx});cur=cur[idx];continue}if(cur&&typeof cur==="object"){if(!Object.hasOwn(cur,token))return null;stack.push({container:cur,token});cur=cur[token];continue}return null}return{stack,parent:cur,lastToken}}function rebuildFromStack(stack,newParent){let acc=newParent;for(let i=stack.length-1;i>=0;i--){const{container,token}=stack[i];if(Array.isArray(container)){const copy2=container.slice();copy2[token]=acc;acc=copy2}else{const copy2={...container};copy2[token]=acc;acc=copy2}}return acc}var RE_DEFS=/^#\/\$defs(?=\/|$)/;function toDocumentDraft07(document){return{dialect:"draft-07",schema:toSchemaDraft07(document.schema),definitions:map3(document.definitions,toSchemaDraft07)}}function toSchemaDraft07(schema){return rewrite(schema);function rewrite(node){return walk(rewrite_refs(node,(ref)=>ref.replace(RE_DEFS,"#/definitions")),true)}function walk(node,_isRoot){if(Array.isArray(node))return node.map((v)=>walk(v,false));if(!isObject(node))return node;const src=node;const out={};let prefixItems=undefined;let items=undefined;for(const k of Object.keys(src)){const v=src[k];switch(k){case"$ref":case"type":case"required":case"enum":case"const":case"title":case"description":case"default":case"examples":case"format":case"pattern":case"minimum":case"maximum":case"exclusiveMinimum":case"exclusiveMaximum":case"minLength":case"maxLength":case"minItems":case"maxItems":case"minProperties":case"maxProperties":case"multipleOf":case"uniqueItems":out[k]=v;break;case"properties":case"patternProperties":{const mapped=walk_object(v,walk);out[k]=mapped??v;break}case"additionalProperties":case"propertyNames":out[k]=walk(v,false);break;case"allOf":case"anyOf":case"oneOf":out[k]=Array.isArray(v)?v.map((x)=>walk(x,false)):v;break;case"prefixItems":prefixItems=v;break;case"items":items=v;break;default:break}}if(prefixItems!==undefined){if(Array.isArray(prefixItems)){out.items=prefixItems.map((x)=>walk(x,false));if(items!==undefined)out.additionalItems=walk(items,false)}else{out.items=walk(prefixItems,false)}}else if(items!==undefined){out.items=walk(items,false)}return out}}function toMultiDocumentOpenApi3_1(multiDocument){const keyMap2=new Map;for(const key of Object.keys(multiDocument.definitions)){const sanitized=sanitizeOpenApiComponentsSchemasKey(key);if(sanitized!==key){keyMap2.set(key,sanitized)}}function rewrite(schema){return rewrite_refs(schema,($ref)=>{const tokens=$ref.split("/");if(tokens.length>0){const identifier2=unescapeToken(tokens[tokens.length-1]);const sanitized=keyMap2.get(identifier2);if(sanitized!==undefined){$ref=tokens.slice(0,-1).join("/")+"/"+sanitized}}return $ref.replace(RE_DEFS,"#/components/schemas")})}return{dialect:"openapi-3.1",schemas:map4(multiDocument.schemas,rewrite),definitions:mapEntries(multiDocument.definitions,(definition,key)=>[keyMap2.get(key)??key,rewrite(definition)])}}var VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP=/^[a-zA-Z0-9.\-_]+$/;function sanitizeOpenApiComponentsSchemasKey(s){if(s.length===0)return"_";if(VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP.test(s))return s;const out=[];for(const ch of s){const code=ch.codePointAt(0);if(code!==undefined&&(code>=48&&code<=57||code>=65&&code<=90||code>=97&&code<=122||code===46||code===45||code===95)){out.push(ch)}else{out.push("_")}}return out.join("")}function rewrite_refs(node,f){if(Array.isArray(node))return node.map((v)=>rewrite_refs(v,f));if(!isObject(node))return node;const out={};for(const k of Object.keys(node)){const v=node[k];if(k==="$ref"){out[k]=typeof v==="string"?f(v):v}else if(Array.isArray(v)||isObject(v)){out[k]=rewrite_refs(v,f)}else{out[k]=v}}return out}function walk_object(value3,walk){if(!isObject(value3))return;const out={};for(const k of Object.keys(value3))out[k]=walk(value3[k],false);return out}function makeIso(get6,set3){return make25(new IsoNode(get6,set3))}function makeLens(get6,replace){return make25(new LensNode(get6,replace))}class IdentityNode{_tag="IdentityNode"}var identityNode=new IdentityNode;class CompositionNode{_tag="CompositionNode";nodes;constructor(nodes){this.nodes=nodes}}class IsoNode{_tag="IsoNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class LensNode{_tag="LensNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class PrismNode{_tag="PrismNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class OptionalNode{_tag="OptionalNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class PathNode{_tag="PathNode";path;constructor(path){this.path=path}}class CheckNode{_tag="CheckNode";checks;constructor(checks){this.checks=checks}}function pushNormalized(acc,node){const last=acc[acc.length-1];if(last){if(last._tag==="PathNode"&&node._tag==="PathNode"){acc[acc.length-1]=new PathNode([...last.path,...node.path]);return}if(last._tag==="CheckNode"&&node._tag==="CheckNode"){acc[acc.length-1]=new CheckNode([...last.checks,...node.checks]);return}}acc.push(node)}function collect(node,acc){if(node._tag==="IdentityNode")return;if(node._tag==="CompositionNode"){for(let i=0;i<node.nodes.length;i++)collect(node.nodes[i],acc);return}pushNormalized(acc,node)}function compose(a,b){const nodes=[];collect(a,nodes);collect(b,nodes);switch(nodes.length){case 0:return identityNode;case 1:return nodes[0];default:return new CompositionNode(nodes)}}function makeOptional(getResult,set3){return make25(new OptionalNode(getResult,set3))}class OptionalImpl{node;getResult;replaceResult;constructor(node,getResult,replaceResult){this.node=node;this.getResult=getResult;this.replaceResult=replaceResult}replace(a,s){return getOrElse3(this.replaceResult(a,s),()=>s)}modify(f){return(s)=>getOrElse3(flatMap2(this.getResult(s),(a)=>this.replaceResult(f(a),s)),()=>s)}compose(that){return make25(compose(this.node,that.node))}key(key){return make25(compose(this.node,new PathNode([key])))}optionalKey(key){return make25(compose(this.node,new LensNode((s)=>s[key],(a,s)=>{const copy2=cloneShallow(s);if(a===undefined){if(Array.isArray(copy2)&&typeof key==="number"){copy2.splice(key,1)}else{delete copy2[key]}}else{copy2[key]=a}return copy2})))}check(...checks){return make25(compose(this.node,new CheckNode(checks)))}refine(refinement,annotations){return make25(compose(this.node,new CheckNode([makeFilterByGuard(refinement,annotations)])))}tag(tag){return make25(compose(this.node,new PrismNode((s)=>s._tag===tag?succeed2(s):fail2(`Expected ${format(tag)} tag, got ${format(s._tag)}`),identity)))}at(key,..._rest){const err=fail2(`Key ${format(key)} not found`);return make25(compose(this.node,new OptionalNode((s)=>Object.hasOwn(s,key)?succeed2(s[key]):err,(a,s)=>{if(Object.hasOwn(s,key)){const copy2=cloneShallow(s);copy2[key]=a;return succeed2(copy2)}else{return err}})))}pick(keys3){return this.compose(makeLens(pick(keys3),(p,a)=>({...a,...p})))}omit(keys3){return this.compose(makeLens(omit2(keys3),(o,a)=>({...a,...o})))}notUndefined(){return this.refine(isNotUndefined,{expected:"a value other than `undefined`"})}forEach(f){const inner=f(id());return makeOptional((s)=>map2(this.getResult(s),(as3)=>{const bs=[];for(let i=0;i<as3.length;i++){const r=inner.getResult(as3[i]);if(isSuccess2(r))bs.push(r.success)}return bs}),(bs,s)=>flatMap2(this.getResult(s),(as3)=>{const idxs=[];for(let i=0;i<as3.length;i++){if(isSuccess2(inner.getResult(as3[i])))idxs.push(i)}if(bs.length!==idxs.length){return fail2(`each: replacement length mismatch: ${bs.length} !== ${idxs.length}`)}const out=as3.slice();for(let k=0;k<idxs.length;k++){const i=idxs[k];const r=inner.replaceResult(bs[k],as3[i]);if(isFailure2(r)){return fail2(`each: could not set element ${i}`)}out[i]=r.success}return this.replaceResult(out,s)}))}modifyAll(f){return(s)=>getOrElse3(flatMap2(this.getResult(s),(as3)=>this.replaceResult(as3.map(f),s)),()=>s)}}class IsoImpl extends OptionalImpl{get;set;constructor(node,get6,set3){super(node,(s)=>succeed2(get6(s)),(a)=>succeed2(set3(a)));this.get=get6;this.set=set3}replace(a,_){return this.set(a)}modify(f){return(s)=>this.set(f(this.get(s)))}}class LensImpl extends OptionalImpl{get;constructor(node,get6,replace){super(node,(s)=>succeed2(get6(s)),(a,s)=>succeed2(replace(a,s)));this.get=get6;this.replace=replace}modify(f){return(s)=>this.replace(f(this.get(s)),s)}}class PrismImpl extends OptionalImpl{set;constructor(node,getResult,set3){super(node,getResult,(a,_)=>succeed2(set3(a)));this.set=set3}replace(a,_){return this.set(a)}modify(f){return(s)=>getOrElse3(map2(this.getResult(s),(a)=>this.set(f(a))),()=>s)}}function make25(node){const op=recur4(node);switch(op._tag){case"IsoNode":return new IsoImpl(node,op.get,op.set);case"LensNode":return new LensImpl(node,op.get,op.set);case"PrismNode":return new PrismImpl(node,op.get,op.set);case"OptionalNode":return new OptionalImpl(node,op.get,op.set)}}function cloneShallow(pojo){if(Array.isArray(pojo))return pojo.slice();if(typeof pojo==="object"&&pojo!==null){const proto=Object.getPrototypeOf(pojo);if(proto!==Object.prototype&&proto!==null){throw new Error("Cannot clone object with non-Object constructor or null prototype")}return{...pojo}}return pojo}var recur4=memoize((node)=>{switch(node._tag){case"IdentityNode":return{_tag:"IsoNode",get:identity,set:identity};case"IsoNode":case"LensNode":case"PrismNode":case"OptionalNode":return{_tag:node._tag,get:node.get,set:node.set};case"PathNode":{return{_tag:"LensNode",get:(s)=>{const path=node.path;let out=s;for(let i=0,n=path.length;i<n;i++){out=out[path[i]]}return out},set:(a,s)=>{const path=node.path;const out=cloneShallow(s);let current=out;let i=0;for(;i<path.length-1;i++){const key=path[i];current[key]=cloneShallow(current[key]);current=current[key]}const finalKey=path[i];current[finalKey]=a;return out}}}case"CheckNode":return{_tag:"PrismNode",get:(s)=>mapError(runChecks(node.checks,s),String),set:identity};case"CompositionNode":{const ops=node.nodes.map(recur4);const _tag=ops.reduce((tag,op)=>getCompositionTag(tag,op._tag),"IsoNode");return{_tag,get:(s)=>{for(let i=0;i<ops.length;i++){const op=ops[i];const result3=op.get(s);if(hasFailingGet(op._tag)){if(isFailure2(result3)){return result3}s=result3.success}else{s=result3}}return hasFailingGet(_tag)?succeed2(s):s},set:(a,s)=>{const source=s;const len=ops.length;const ss=new Array(len+1);ss[0]=s;for(let i=0;i<len;i++){const op=ops[i];if(hasFailingGet(op._tag)){const result3=op.get(s);if(isFailure2(result3)){return _tag==="OptionalNode"?result3:source}s=result3.success}else{s=op.get(s)}ss[i+1]=s}for(let i=len-1;i>=0;i--){const op=ops[i];if(hasSet(op._tag)){a=op.set(a)}else if(op._tag==="LensNode"){a=op.set(a,ss[i])}else{const result3=op.set(a,ss[i]);if(isFailure2(result3)){return result3}a=result3.success}}return _tag==="OptionalNode"?succeed2(a):a}}}}});function hasFailingGet(tag){return tag==="PrismNode"||tag==="OptionalNode"}function hasSet(tag){return tag==="IsoNode"||tag==="PrismNode"}function getCompositionTag(a,b){switch(a){case"IsoNode":return b;case"LensNode":return hasFailingGet(b)?"OptionalNode":"LensNode";case"PrismNode":return hasSet(b)?"PrismNode":"OptionalNode";case"OptionalNode":return"OptionalNode"}}var identityIso=make25(identityNode);function id(){return identityIso}var exports_FastCheck={};__export(exports_FastCheck,{webUrl:()=>webUrl,webSegment:()=>webSegment,webQueryParameters:()=>webQueryParameters,webPath:()=>webPath,webFragments:()=>webFragments,webAuthority:()=>webAuthority,uuid:()=>uuid,uniqueArray:()=>uniqueArray,ulid:()=>ulid,uint8ClampedArray:()=>uint8ClampedArray,uint8Array:()=>uint8Array,uint32Array:()=>uint32Array,uint16Array:()=>uint16Array,tuple:()=>tuple2,toStringMethod:()=>toStringMethod,subarray:()=>subarray,stringify:()=>stringify,stringMatching:()=>stringMatching,string:()=>string3,stream:()=>stream,statistics:()=>statistics,sparseArray:()=>sparseArray,shuffledSubarray:()=>shuffledSubarray,set:()=>set3,schedulerFor:()=>schedulerFor,scheduler:()=>scheduler,scheduledModelRun:()=>scheduledModelRun,sample:()=>sample,resetConfigureGlobal:()=>resetConfigureGlobal,record:()=>record2,readConfigureGlobal:()=>readConfigureGlobal,property:()=>property,pre:()=>pre,option:()=>option3,oneof:()=>oneof,object:()=>object,noShrink:()=>noShrink,noBias:()=>noBias,nat:()=>nat,modelRun:()=>modelRun,mixedCase:()=>mixedCase,memo:()=>memo,maxSafeNat:()=>maxSafeNat,maxSafeInteger:()=>maxSafeInteger,mapToConstant:()=>mapToConstant,map:()=>map13,lorem:()=>lorem,limitShrink:()=>limitShrink,letrec:()=>letrec,jsonValue:()=>jsonValue,json:()=>json,ipV6:()=>ipV6,ipV4Extended:()=>ipV4Extended,ipV4:()=>ipV4,integer:()=>integer,int8Array:()=>int8Array,int32Array:()=>int32Array,int16Array:()=>int16Array,infiniteStream:()=>infiniteStream,hash:()=>hash2,hasToStringMethod:()=>hasToStringMethod,hasCloneMethod:()=>hasCloneMethod,hasAsyncToStringMethod:()=>hasAsyncToStringMethod,getDepthContextFor:()=>getDepthContextFor,gen:()=>gen3,func:()=>func,float64Array:()=>float64Array,float32Array:()=>float32Array,float:()=>float,falsy:()=>falsy,entityGraph:()=>entityGraph,emailAddress:()=>emailAddress,double:()=>double,domain:()=>domain,dictionary:()=>dictionary,defaultReportMessage:()=>defaultReportMessage,date:()=>date,createDepthIdentifier:()=>createDepthIdentifier,context:()=>context3,constantFrom:()=>constantFrom,constant:()=>constant2,configureGlobal:()=>configureGlobal,compareFunc:()=>compareFunc,compareBooleanFunc:()=>compareBooleanFunc,commands:()=>commands,cloneMethod:()=>cloneMethod,cloneIfNeeded:()=>cloneIfNeeded,clone:()=>clone,check:()=>check,chainUntil:()=>chainUntil,boolean:()=>boolean2,bigUint64Array:()=>bigUint64Array,bigInt64Array:()=>bigInt64Array,bigInt:()=>bigInt2,base64String:()=>base64String,asyncToStringMethod:()=>asyncToStringMethod,asyncStringify:()=>asyncStringify,asyncProperty:()=>asyncProperty,asyncModelRun:()=>asyncModelRun,asyncDefaultReportMessage:()=>asyncDefaultReportMessage,assert:()=>assert,array:()=>array3,anything:()=>anything,__version:()=>__version,__type:()=>__type,__commitHash:()=>__commitHash,VerbosityLevel:()=>VerbosityLevel,Value:()=>Value,Stream:()=>Stream,Random:()=>Random,PreconditionFailure:()=>PreconditionFailure,ExecutionStatus:()=>ExecutionStatus,Arbitrary:()=>Arbitrary});var MULTIPLIER=214013;var INCREMENT=2531011;var MASK=4294967295;var MASK_2=-2147483649;var MULTIPLIER_2=-1443076087;var INCREMENT_2=505908858;var MULTIPLIER_3=1170746341;var INCREMENT_3=-755606699;var JUMP_MULTIPLIER=1994129409;var JUMP_INCREMENT=916127744;var LinearCongruential32=class LinearCongruential322{constructor(seed){this.seed=seed}clone(){return new LinearCongruential322(this.seed)}next(){const s0=this.seed;const s1=Math.imul(s0,MULTIPLIER)+INCREMENT|0;const s2=Math.imul(s0,MULTIPLIER_2)+INCREMENT_2|0;const s3=Math.imul(s0,MULTIPLIER_3)+INCREMENT_3|0;this.seed=s3;const v1=(s1&MASK_2)>>16;const v2=(s2&MASK_2)>>16;return(s3&MASK_2)>>16|v2<<15|v1<<30}jump(){this.seed=Math.imul(this.seed,JUMP_MULTIPLIER)+JUMP_INCREMENT&MASK}getState(){return[this.seed]}};function congruential32(seed){return new LinearCongruential32(seed)}var N=624;var M=397;var A=2567483615;var F=1812433253;var U=11;var S=7;var B=2636928640;var T=15;var C=4022730752;var L=18;var MASK_LOWER=2147483647;var MASK_UPPER=2147483648;var JUMP_COEFS="SUSgbA\\W`E[]KN2RUSo8XVU?HKBFRl11E\\KoWOg5B]XEWG;BE;1:oVK[`B^Z9Qd23^XTnhL>]Unda4f[X;_j9H5QD=cN<5H`3bW>9bk1mjoI2fK0obmAAINOV:>Mek_V9dd<hZ\\gC3?Fm7FEk07QH_3PLm^@?^i\\QMkgP<]oLHmFnlecg5F@7U^@4jhZ?WZS0k@GHehmM36:5^9;>Hmm`co>k:KOSkSbIINb1VFf>LXgP>GUAQTD>Ci>XMGkUflLlb?_FaFUk@?5N7i70@;1o68ah@I<HFH7R2^J:G][Gf962ITWID9GWK8ElD2G5=DcHcL]cA]P2n7A=[<bInM;IHDQnJMReRXDWbVldnGEIPij`E08Xdci3@0c:IBbD4:Nk]?lEN9j^;T`0blZX7eiWE8c`<ak7j05FZi>AjUDh?M1B?^??FAXKThf<aBOXZf7jXYGK>R<;NHk3S9YhM7STJ6`:MIE`S@7298X8W>PNK=@;lLX<i\\TXLL<W@X[X54H]in8M;;n?kkQbajgAMY=Tf9b;ZKf0QUB2FHYWfnfkDoU9YkcLd95T>lK6GM1YL\\lid:J>KYS=iJ]Y>QlF>?R5_[5QeYC=66;A32Ac>OHk_ne^0g>bK:g;KFPgbGUcPR_Z=TX3H9d03bKZ2IhEPKBo>LSGWd0iFdV8C<Y:<>T[O6lC\\blaZ>GoAYP4clf^j1IfnZJ]QeDe2X<HE[LJNWnaCg[P]Co^:IRbWPY?97UePBlZNNHY6LOBM8P>=h?Ye:_f_Sb9Ki5GDYBF4dWeMfdg^ccPllNWM7G1\\UMdoYeOOD5^e@foA22G?ADYo5:FVG[bWo96;>3kc_c1Ab30>30;1@4F8g2hY?DJ4[LOL;ZLLKo2]jo>[KMDUcR279N_kF=3WL@Dd620bMTdA\\U9k``ef2iD9JgJ8CZBHS>F^Uk;<laeaeHS<15OSeS`PcSSKBRBFY]aQ=EgUXGNg=?d56`KA@2BejY0^[_DCX`L=CGMT=BW^6S1i@2ATBVk>3_ocRA>2U:4GPQ6o>5jX2HIcV3S@On6KB<[SKB?FC_AAji9agbBFkAi\\;4I\\UJ]c36Ub@[;gQACVGY<V]SDJBUU]La\\_a@JdOO8gm2T0DJMa:8Hf7>E]noQ[1Kambn??QQ]S?1i0oMGOijb\\aGY6lQ^CJ?9bFle8<eH4UUjBINX;n8@VOA5ah^URV49B[A?ONHhHAC1J5;;h0SXYlG^0W=eJdHh^K4SGe=1HZLLam;D<Q3AOdbPcdX``82\\jo0En8jRVGC73WMCF9`d:0heS?80?C188cSn7H9<daZ]MgS4Pb^1HkA:1PU^5>^h_g[RQV@PnYBRI_]`B]Bh@Uk03eXGY`I16L76H28X`R>IROMeNVUdU[:lghLhPCQZ:4a<30YBZCYnXe[?;jc8gKI2QH2MjnWBm4nGCZW`aVU2a;P<AMI25mlW_Nm][2?b6o851X@lAm]YZ`bWRF1g<Ga:T]1NXH5Veja5P9S9>:aNg:Th1Y=5o78K>LQ8hW@5S?I83Lk5Xk;j5@I3o[d:4RjE^oS30:WP9gC\\i8aSI>QRE@4lP:7lDg8g2`Ql[2I8aBU\\BQ?B4_clL9Q]S;^e1Ob5[>3JER2`c7B=o]fPOWO<DGi;Niba1PoWPPE_Q3aX0OB0mZej\\f_M[J4Y6]1`h2MkF[GiW8Q^d3^_=<I1N2Q7]2<2j[iP7V3V821FaI]A`93bC^Z\\G=WJ;^Ih?B97_iIF@\\Dl<eK1je8SNTWo_=XFMZH<<JYLZ^YQMPgYOV45K_:]kSI8^XlO0]GY=VUfe_C_F6TOcoAlVUH:o=WhhT@K`2KFhe<3\\KXQ>W:M?S_4S5d@J^`[AGA7@3]DnGSCO`\\?E8HT75^d9\\:m\\m1egIfk8cd6bD9\\eU8\\n[Pb0Cgd^S0n9kGJHb]i5XodlKHc34Fhi9K>0U5WK`>7Ff2^KL=WC6:kc?e5C^a1T1:4:^S5flXlGNIj08AfO?Dh7T7dWO>E]NI9?ob7B7P_h[4TEP[EU;GllFTnSmg9:\\[N]<SAoKP_kPlG56A:I3T6EG8Hj=XnUE`KT5U@OQ?]7[N^MFN1_NU4KO_3::Le`8IL9[1Z1H1;V3SC\\N3]S@4U[F2mhT5dYM7[4Pg_Na0_8WTH0`bgceQS8]EG;XgD4Ib4iLTP@kE79Mn>AYRJA1U5^Blhgno:aHVYc03c3J0Vc9FjEV^M75Zfd8kVC9>iJDk`AJ[6f7DK2D^DL\\AX:6b5h31XH;RQB\\N<ZSM=J;6L[`UW^eOIFc1Y]6_dfedIe4ARh72mTXC0WND_IDHVCZRDE0eODARCEETQI5TPUQE=jEH5bS?LP[ai`F5ABRYDo2o\\@=]GT?_9;hc4Lm:\\SF9k1T<0E@fX9BG[]g0nY7k[Qmi@la8`PF0j6@Q?Ii7bLkXQ<lLHf]`:DCh@9JY5>hEVLTdhL\\b1EB0lLh<=WaO@F<;8g<d:@e:LA:cFIEdmQh7hNHfSRToW?8N4:Z1K;XEDRO;OIDh<UdVln?bjgL>?VE98[B\\K<BVjkG8LiSX;fb>jf?DUK00Aih<WY6QD6cEnHBZ8iN_fd<G8Ci`11RUW2QlW]IXV:m?;J0GXXHfGNQ>:D`=fLPbO?VOTEYLj^cNj5PM>jKB5HVjJ4U7lXaTQNL9<@\\1`m\\Ug@VQHd7>jW=ca0`miF7;N0F=GjoQ`RFchKMGTmn8cF@Oh4GGCm7m2`U9j93Tb>=kSERjE_J939F01I1;`<ijk_=_Vn=7RVAI6fnQI5KlF:C44bN<<8K=Z<2TP<1]5?<dB>^LA=ebloE2Y2:9lkh0\\<YKbHD97iE`<C5oj^1>X:??`H6BXF2hG1Q[dF0Q=>W=J?7C\\k1T?<;R44oW?1hY^G8Zm]ZKnfOf0eCFYo6?=D8?<`6HU5SXh1;=:23LmV_FSi;OJfV<^?GkIDPISeHg1LaGE:V3Y3K3H<QJfbY?=;ldZRhnhQT_mGXDLFXXhSONE6Do_0iNZagB:BPGOTH;VhHUTd6LhQm^[;dO]5Hlkg<R:F<Kn\\:I:EGojgWZ2X@SYO_dlH;G8S<>oEKabY`:oU;=JW7ig?S?EYb86b7n8ce\\]IRa]koiWY<RfO;5kUI;7lVeC?[@ZaXDiF04B8R]bg@>O<mQDoUcBLcf^f>m2kMBUloD>Ze@NN^Z11TM`inXYhE_I=kA`:ZF4d\\>`L@;ZP[`ENU5cL[BV6\\Z?Di76:jg3hE6oG6jFc8kP=[GS1;WSedYQW1:U4\\OF32GgmMC<AjO]872bdBb`bKAA?8j78b>T3VfcUB2m4J^CPRU;8dScI]LU]^bBYA5_3:Y0N5i^?200000";var MersenneTwister=class MersenneTwister2{constructor(states,index2){this.states=states;this.index=index2}clone(){return new MersenneTwister2(this.states.slice(),this.index)}next(){let y=this.states[this.index];y^=y>>>U;y^=y<<S&B;y^=y<<T&C;y^=y>>>L;this.index=twistedNext(this.states,this.index);return y}getState(){return[this.index,...this.states]}jump(){const originalStates=this.states.slice();const originalIndex=this.index;this.index=twistedNext(this.states,this.index);for(let i=19932;i>0;--i){if(JUMP_COEFS.charCodeAt(i/6|0)-48&1<<i%6)addState(this.states,this.index,originalStates,originalIndex);this.index=twistedNext(this.states,this.index)}addState(this.states,this.index,originalStates,originalIndex)}};function addState(mt,idx,originalMt,originalIdx){let i=0;if(originalIdx>=idx){for(;i<N-originalIdx;i++)mt[i+idx]^=originalMt[i+originalIdx];for(;i<N-idx;i++)mt[i+idx]^=originalMt[i+originalIdx-N];for(;i<N;i++)mt[i+idx-N]^=originalMt[i+originalIdx-N]}else{for(;i<N-idx;i++)mt[i+idx]^=originalMt[i+originalIdx];for(;i<N-originalIdx;i++)mt[i+idx-N]^=originalMt[i+originalIdx];for(;i<N;i++)mt[i+idx-N]^=originalMt[i+originalIdx-N]}}function twistedNext(mt,idx){if(idx<N-M){const y=mt[idx]&MASK_UPPER|mt[idx+1]&MASK_LOWER;mt[idx]=mt[idx+M]^y>>>1^-(y&1)&A;return idx+1}else if(idx<N-1){const y=mt[idx]&MASK_UPPER|mt[idx+1]&MASK_LOWER;mt[idx]=mt[idx+M-N]^y>>>1^-(y&1)&A;return idx+1}else{const y=mt[idx]&MASK_UPPER|mt[0]&MASK_LOWER;mt[idx]=mt[M-1]^y>>>1^-(y&1)&A;return 0}}function twist(mt){for(let idx=0;idx!==N;++idx)twistedNext(mt,idx)}function mersenne(seed){const out=[seed|0];for(let idx=1;idx!==N;++idx){const xored=out[idx-1]^out[idx-1]>>>30;out.push(Math.imul(F,xored)+idx|0)}twist(out);return new MersenneTwister(out,0)}var jumps=[1667051007,2321340297,1548169110,304075285];var XorShift128Plus=class XorShift128Plus2{constructor(s01,s00,s11,s10){this.s01=s01;this.s00=s00;this.s11=s11;this.s10=s10}clone(){return new XorShift128Plus2(this.s01,this.s00,this.s11,this.s10)}next(){const a0=this.s00^this.s00<<23;const a1=this.s01^(this.s01<<23|this.s00>>>9);const s10=this.s10;const s11=this.s11;const out=this.s00+s10|0;this.s01=s11;this.s00=s10;this.s11=a1^s11^a1>>>18^s11>>>5;this.s10=a0^s10^(a0>>>18|a1<<14)^(s10>>>5|s11<<27);return out}jump(){let ns01=0;let ns00=0;let ns11=0;let ns10=0;let s01=this.s01;let s00=this.s00;let s11=this.s11;let s10=this.s10;for(let i=0;i!==4;++i){const ji=jumps[i];for(let mask2=1;mask2;mask2<<=1){if(ji&mask2){ns01^=s01;ns00^=s00;ns11^=s11;ns10^=s10}const a0=s00^s00<<23;const a1=s01^(s01<<23|s00>>>9);s01=s11;s00=s10;s10=a0^s10^(a0>>>18|a1<<14)^(s10>>>5|s11<<27);s11=a1^s11^a1>>>18^s11>>>5}}this.s01=ns01;this.s00=ns00;this.s11=ns11;this.s10=ns10}getState(){return[this.s01,this.s00,this.s11,this.s10]}};function xorshift128plus(seed){return new XorShift128Plus(-1,~seed,seed|0,0)}var jumps2=[3639956645,3750757012,1261568508,386426335];var XoroShiro128Plus=class XoroShiro128Plus2{constructor(s01,s00,s11,s10){this.s01=s01;this.s00=s00;this.s11=s11;this.s10=s10}clone(){return new XoroShiro128Plus2(this.s01,this.s00,this.s11,this.s10)}next(){const out=this.s00+this.s10|0;const a0=this.s10^this.s00;const a1=this.s11^this.s01;const s00=this.s00;const s01=this.s01;this.s00=s00<<24^s01>>>8^a0^a0<<16;this.s01=s01<<24^s00>>>8^a1^(a1<<16|a0>>>16);this.s10=a1<<5^a0>>>27;this.s11=a0<<5^a1>>>27;return out}jump(){let ns01=0;let ns00=0;let ns11=0;let ns10=0;let s01=this.s01;let s00=this.s00;let s11=this.s11;let s10=this.s10;for(let i=0;i!==4;++i){const ji=jumps2[i];for(let mask2=1;mask2;mask2<<=1){if(ji&mask2){ns01^=s01;ns00^=s00;ns11^=s11;ns10^=s10}const a0=s10^s00;const a1=s11^s01;const s00_=s00;const s01_=s01;s00=s00_<<24^s01_>>>8^a0^a0<<16;s01=s01_<<24^s00_>>>8^a1^(a1<<16|a0>>>16);s10=a1<<5^a0>>>27;s11=a0<<5^a1>>>27}}this.s01=ns01;this.s00=ns00;this.s11=ns11;this.s10=ns10}getState(){return[this.s01,this.s00,this.s11,this.s10]}};function xoroshiro128plus(seed){return new XoroShiro128Plus(-1,~seed,seed|0,0)}function skipN(rng,num){for(let idx=0;idx!==num;++idx)rng.next()}var SBigInt=BigInt;var NumValues=4294967296n;function uniformBigInt(rng,from,to){const diff=to-from+1n;let FinalNumValues=NumValues;let NumIterations=1;while(FinalNumValues<diff){FinalNumValues<<=32n;++NumIterations}let value3=generateNext(NumIterations,rng);if(value3<diff)return value3+from;if(value3+diff<FinalNumValues)return value3%diff+from;const MaxAcceptedRandom=FinalNumValues-FinalNumValues%diff;while(value3>=MaxAcceptedRandom)value3=generateNext(NumIterations,rng);return value3%diff+from}function generateNext(NumIterations,rng){let value3=SBigInt(rng.next()+2147483648);for(let num=1;num<NumIterations;++num){const out=rng.next();value3=(value3<<32n)+SBigInt(out+2147483648)}return value3}function uniformIntInternal(rng,rangeSize){const MaxAllowed=rangeSize>2?~~(4294967296/rangeSize)*rangeSize:4294967296;let deltaV=rng.next()+2147483648;while(deltaV>=MaxAllowed)deltaV=rng.next()+2147483648;return deltaV%rangeSize}function fromNumberToArrayInt64(out,n){if(n<0){const posN=-n;out.sign=-1;out.data[0]=~~(posN/4294967296);out.data[1]=posN>>>0}else{out.sign=1;out.data[0]=~~(n/4294967296);out.data[1]=n>>>0}return out}function substractArrayInt64(out,arrayIntA,arrayIntB){const lowA=arrayIntA.data[1];const highA=arrayIntA.data[0];const signA=arrayIntA.sign;const lowB=arrayIntB.data[1];const highB=arrayIntB.data[0];const signB=arrayIntB.sign;out.sign=1;if(signA===1&&signB===-1){const low2=lowA+lowB;const high=highA+highB+(low2>4294967295?1:0);out.data[0]=high>>>0;out.data[1]=low2>>>0;return out}let lowFirst=lowA;let highFirst=highA;let lowSecond=lowB;let highSecond=highB;if(signA===-1){lowFirst=lowB;highFirst=highB;lowSecond=lowA;highSecond=highA}let reminderLow=0;let low=lowFirst-lowSecond;if(low<0){reminderLow=1;low=low>>>0}out.data[0]=highFirst-highSecond-reminderLow;out.data[1]=low;return out}function uniformArrayIntInternal(rng,out,rangeSize){const maxIndex0=rangeSize[0]+1;out[0]=uniformIntInternal(rng,maxIndex0);out[1]=uniformIntInternal(rng,4294967296);while(out[0]>=rangeSize[0]&&(out[0]!==rangeSize[0]||out[1]>=rangeSize[1])){out[0]=uniformIntInternal(rng,maxIndex0);out[1]=uniformIntInternal(rng,4294967296)}return out}var safeNumberMaxSafeInteger=Number.MAX_SAFE_INTEGER;var sharedA={sign:1,data:[0,0]};var sharedB={sign:1,data:[0,0]};var sharedC={sign:1,data:[0,0]};var sharedData=[0,0];function uniformLargeIntInternal(rng,from,to,rangeSize){const rangeSizeArrayIntValue=rangeSize<=safeNumberMaxSafeInteger?fromNumberToArrayInt64(sharedC,rangeSize):substractArrayInt64(sharedC,fromNumberToArrayInt64(sharedA,to),fromNumberToArrayInt64(sharedB,from));if(rangeSizeArrayIntValue.data[1]===4294967295){rangeSizeArrayIntValue.data[0]+=1;rangeSizeArrayIntValue.data[1]=0}else rangeSizeArrayIntValue.data[1]+=1;uniformArrayIntInternal(rng,sharedData,rangeSizeArrayIntValue.data);return sharedData[0]*4294967296+sharedData[1]+from}function uniformInt(rng,from,to){const rangeSize=to-from;if(rangeSize<=4294967295)return uniformIntInternal(rng,rangeSize+1)+from;return uniformLargeIntInternal(rng,from,to,rangeSize)}var SharedFootPrint=Symbol.for("fast-check/PreconditionFailure");var PreconditionFailure=class extends Error{constructor(interruptExecution=false){super();this.interruptExecution=interruptExecution;this.footprint=SharedFootPrint}static isFailure(err){return err!==null&&err!==undefined&&err.footprint===SharedFootPrint}};function pre(expectTruthy){if(!expectTruthy)throw new PreconditionFailure}var Nil=class{[Symbol.iterator](){return this}next(value3){return{value:value3,done:true}}};var nil=new Nil;function nilHelper(){return nil}function*mapHelper(g,f){for(const v of g)yield f(v)}function*flatMapHelper(g,f){for(const v of g)yield*f(v)}function*filterHelper(g,f){for(const v of g)if(f(v))yield v}function*takeNHelper(g,n){for(let i=0;i<n;++i){const cur=g.next();if(cur.done)break;yield cur.value}}function*takeWhileHelper(g,f){let cur=g.next();while(!cur.done&&f(cur.value)){yield cur.value;cur=g.next()}}function*joinHelper(g,others){for(let cur=g.next();!cur.done;cur=g.next())yield cur.value;for(const s of others)for(let cur=s.next();!cur.done;cur=s.next())yield cur.value}var safeSymbolIterator$1=Symbol.iterator;var Stream=class Stream2{static nil(){return new Stream2(nilHelper())}static of(...elements){return new Stream2(elements[safeSymbolIterator$1]())}constructor(g){this.g=g}next(){return this.g.next()}[Symbol.iterator](){return this.g}map(f){return new Stream2(mapHelper(this.g,f))}flatMap(f){return new Stream2(flatMapHelper(this.g,f))}dropWhile(f){let foundEligible=false;function*helper(v){if(foundEligible||!f(v)){foundEligible=true;yield v}}return this.flatMap(helper)}drop(n){if(n<=0)return this;let idx=0;function helper(){return idx++<n}return this.dropWhile(helper)}takeWhile(f){return new Stream2(takeWhileHelper(this.g,f))}take(n){return new Stream2(takeNHelper(this.g,n))}filter(f){return new Stream2(filterHelper(this.g,f))}every(f){for(const v of this.g)if(!f(v))return false;return true}has(f){for(const v of this.g)if(f(v))return[true,v];return[false,null]}join(...others){return new Stream2(joinHelper(this.g,others))}getNthOrLast(nth){let remaining=nth;let last=null;for(const v of this.g){if(remaining--===0)return v;last=v}return last}};function stream(g){return new Stream(g)}var cloneMethod=Symbol.for("fast-check/cloneMethod");function hasCloneMethod(instance){return instance!==null&&(typeof instance==="object"||typeof instance==="function")&&cloneMethod in instance&&typeof instance[cloneMethod]==="function"}function cloneIfNeeded(instance){return hasCloneMethod(instance)?instance[cloneMethod]():instance}var safeObjectDefineProperty$4=Object.defineProperty;var Value=class{constructor(value_,context3,customGetValue){this.value_=value_;this.context=context3;this.hasToBeCloned=customGetValue!==undefined||hasCloneMethod(value_);this.readOnce=false;this.value=value_;if(this.hasToBeCloned)safeObjectDefineProperty$4(this,"value",{get:customGetValue!==undefined?customGetValue:this.getValue,enumerable:false,configurable:false})}getValue(){if(this.hasToBeCloned){if(!this.readOnce){this.readOnce=true;return this.value_}return this.value_[cloneMethod]()}return this.value_}};var Arbitrary=class{filter(refinement){return new FilterArbitrary(this,refinement)}map(mapper,unmapper){return new MapArbitrary(this,mapper,unmapper)}chain(chainer){return new ChainArbitrary(this,chainer)}};var ChainArbitrary=class extends Arbitrary{constructor(arb,chainer){super();this.arb=arb;this.chainer=chainer}generate(mrng,biasFactor){const clonedMrng=mrng.clone();const src=this.arb.generate(mrng,biasFactor);return this.valueChainer(src,mrng,clonedMrng,biasFactor)}canShrinkWithoutContext(_value){return false}shrink(value3,context3){if(this.isSafeContext(context3))return(!context3.stoppedForOriginal?this.arb.shrink(context3.originalValue,context3.originalContext).map((v)=>this.valueChainer(v,context3.clonedMrng.clone(),context3.clonedMrng,context3.originalBias)):Stream.nil()).join(context3.chainedArbitrary.shrink(value3,context3.chainedContext).map((dst)=>{const newContext={...context3,chainedContext:dst.context,stoppedForOriginal:true};return new Value(dst.value_,newContext)}));return Stream.nil()}valueChainer(v,generateMrng,clonedMrng,biasFactor){const chainedArbitrary=this.chainer(v.value_);const dst=chainedArbitrary.generate(generateMrng,biasFactor);const context3={originalBias:biasFactor,originalValue:v.value_,originalContext:v.context,stoppedForOriginal:false,chainedArbitrary,chainedContext:dst.context,clonedMrng};return new Value(dst.value_,context3)}isSafeContext(context3){return context3!==null&&context3!==undefined&&typeof context3==="object"&&"originalBias"in context3&&"originalValue"in context3&&"originalContext"in context3&&"stoppedForOriginal"in context3&&"chainedArbitrary"in context3&&"chainedContext"in context3&&"clonedMrng"in context3}};function mapperWithCloneIfNeeded(v,mapper){const sourceValue=v.value;const mappedValue=mapper(sourceValue);if(v.hasToBeCloned&&(typeof mappedValue==="object"&&mappedValue!==null||typeof mappedValue==="function")&&Object.isExtensible(mappedValue)&&!hasCloneMethod(mappedValue))Object.defineProperty(mappedValue,cloneMethod,{get:()=>()=>mapperWithCloneIfNeeded(v,mapper)[0]});return[mappedValue,sourceValue]}function valueMapper(v,mapper){const[mappedValue,sourceValue]=mapperWithCloneIfNeeded(v,mapper);return new Value(mappedValue,{originalValue:sourceValue,originalContext:v.context})}var MapArbitrary=class extends Arbitrary{constructor(arb,mapper,unmapper){super();this.arb=arb;this.mapper=mapper;this.unmapper=unmapper;this.bindValueMapper=(v)=>valueMapper(v,mapper)}generate(mrng,biasFactor){const g=this.arb.generate(mrng,biasFactor);if(!g.hasToBeCloned){const sourceValue=g.value;return new Value(this.mapper(sourceValue),{originalValue:sourceValue,originalContext:g.context})}return valueMapper(g,this.mapper)}canShrinkWithoutContext(value3){if(this.unmapper!==undefined)try{const unmapped=this.unmapper(value3);return this.arb.canShrinkWithoutContext(unmapped)}catch{return false}return false}shrink(value3,context3){if(this.isSafeContext(context3))return this.arb.shrink(context3.originalValue,context3.originalContext).map(this.bindValueMapper);if(this.unmapper!==undefined){const unmapped=this.unmapper(value3);return this.arb.shrink(unmapped,undefined).map(this.bindValueMapper)}return Stream.nil()}isSafeContext(context3){return context3!==null&&context3!==undefined&&typeof context3==="object"&&"originalValue"in context3&&"originalContext"in context3}};var FilterArbitrary=class extends Arbitrary{constructor(arb,refinement){super();this.arb=arb;this.refinement=refinement;this.bindRefinementOnValue=(v)=>this.refinementOnValue(v)}generate(mrng,biasFactor){while(true){const g=this.arb.generate(mrng,biasFactor);if(this.refinementOnValue(g))return g}}canShrinkWithoutContext(value3){return this.arb.canShrinkWithoutContext(value3)&&this.refinement(value3)}shrink(value3,context3){return this.arb.shrink(value3,context3).filter(this.bindRefinementOnValue)}refinementOnValue(v){return this.refinement(v.value)}};function isArbitrary(instance){return typeof instance==="object"&&instance!==null&&"generate"in instance&&"shrink"in instance&&"canShrinkWithoutContext"in instance}function assertIsArbitrary(instance){if(!isArbitrary(instance))throw new Error("Unexpected value received: not an instance of Arbitrary")}var untouchedApply=Function.prototype.apply;var ApplySymbol=Symbol("apply");function safeExtractApply(f){try{return f.apply}catch{return}}function safeApplyHacky(f,instance,args2){const ff=f;ff[ApplySymbol]=untouchedApply;const out=ff[ApplySymbol](instance,args2);delete ff[ApplySymbol];return out}function safeApply(f,instance,args2){if(safeExtractApply(f)===untouchedApply)return f.apply(instance,args2);return safeApplyHacky(f,instance,args2)}var SArray=Array;var SBigInt2=BigInt;var SBigInt64Array=BigInt64Array;var SBigUint64Array=BigUint64Array;var SBoolean=Boolean;var SDate=Date;var SError=Error;var SFloat32Array=Float32Array;var SFloat64Array=Float64Array;var SInt8Array=Int8Array;var SInt16Array=Int16Array;var SInt32Array=Int32Array;var SNumber=Number;var SString=String;var SSet=Set;var SUint8Array=Uint8Array;var SUint8ClampedArray=Uint8ClampedArray;var SUint16Array=Uint16Array;var SUint32Array=Uint32Array;var SencodeURIComponent=encodeURIComponent;var SMap$1=Map;var SSymbol=Symbol;var untouchedForEach=Array.prototype.forEach;var untouchedIndexOf=Array.prototype.indexOf;var untouchedJoin=Array.prototype.join;var untouchedMap=Array.prototype.map;var untouchedFlat=Array.prototype.flat;var untouchedFilter=Array.prototype.filter;var untouchedPush=Array.prototype.push;var untouchedPop=Array.prototype.pop;var untouchedSplice=Array.prototype.splice;var untouchedSlice=Array.prototype.slice;var untouchedSort=Array.prototype.sort;var untouchedEvery=Array.prototype.every;function extractForEach(instance){try{return instance.forEach}catch{return}}function extractIndexOf(instance){try{return instance.indexOf}catch{return}}function extractJoin(instance){try{return instance.join}catch{return}}function extractMap(instance){try{return instance.map}catch{return}}function extractFlat(instance){try{return instance.flat}catch{return}}function extractFilter(instance){try{return instance.filter}catch{return}}function extractPush(instance){try{return instance.push}catch{return}}function extractPop(instance){try{return instance.pop}catch{return}}function extractSplice(instance){try{return instance.splice}catch{return}}function extractSlice(instance){try{return instance.slice}catch{return}}function extractSort(instance){try{return instance.sort}catch{return}}function extractEvery(instance){try{return instance.every}catch{return}}function safeForEach(instance,fn3){if(extractForEach(instance)===untouchedForEach)return instance.forEach(fn3);return safeApply(untouchedForEach,instance,[fn3])}function safeIndexOf(instance,...args2){if(extractIndexOf(instance)===untouchedIndexOf)return instance.indexOf(...args2);return safeApply(untouchedIndexOf,instance,args2)}function safeJoin(instance,...args2){if(extractJoin(instance)===untouchedJoin)return instance.join(...args2);return safeApply(untouchedJoin,instance,args2)}function safeMap(instance,fn3){if(extractMap(instance)===untouchedMap)return instance.map(fn3);return safeApply(untouchedMap,instance,[fn3])}function safeFlat(instance,depth){if(extractFlat(instance)===untouchedFlat){[].flat();return instance.flat(depth)}return safeApply(untouchedFlat,instance,[depth])}function safeFilter(instance,predicate){if(extractFilter(instance)===untouchedFilter)return instance.filter(predicate);return safeApply(untouchedFilter,instance,[predicate])}function safePush(instance,...args2){if(extractPush(instance)===untouchedPush)return instance.push(...args2);return safeApply(untouchedPush,instance,args2)}function safePop$1(instance){if(extractPop(instance)===untouchedPop)return instance.pop();return safeApply(untouchedPop,instance,[])}function safeSplice(instance,...args2){if(extractSplice(instance)===untouchedSplice)return instance.splice(...args2);return safeApply(untouchedSplice,instance,args2)}function safeSlice(instance,...args2){if(extractSlice(instance)===untouchedSlice)return instance.slice(...args2);return safeApply(untouchedSlice,instance,args2)}function safeSort(instance,...args2){if(extractSort(instance)===untouchedSort)return instance.sort(...args2);return safeApply(untouchedSort,instance,args2)}function safeEvery(instance,...args2){if(extractEvery(instance)===untouchedEvery)return instance.every(...args2);return safeApply(untouchedEvery,instance,args2)}var untouchedGetTime=Date.prototype.getTime;var untouchedToISOString=Date.prototype.toISOString;function extractGetTime(instance){try{return instance.getTime}catch{return}}function extractToISOString(instance){try{return instance.toISOString}catch{return}}function safeGetTime(instance){if(extractGetTime(instance)===untouchedGetTime)return instance.getTime();return safeApply(untouchedGetTime,instance,[])}function safeToISOString(instance){if(extractToISOString(instance)===untouchedToISOString)return instance.toISOString();return safeApply(untouchedToISOString,instance,[])}var untouchedAdd=Set.prototype.add;var untouchedHas=Set.prototype.has;function extractAdd(instance){try{return instance.add}catch{return}}function extractHas(instance){try{return instance.has}catch(err){return}}function safeAdd(instance,value3){if(extractAdd(instance)===untouchedAdd)return instance.add(value3);return safeApply(untouchedAdd,instance,[value3])}function safeHas(instance,value3){if(extractHas(instance)===untouchedHas)return instance.has(value3);return safeApply(untouchedHas,instance,[value3])}var untouchedSet=WeakMap.prototype.set;var untouchedGet=WeakMap.prototype.get;function extractSet(instance){try{return instance.set}catch(err){return}}function extractGet(instance){try{return instance.get}catch(err){return}}function safeSet(instance,key,value3){if(extractSet(instance)===untouchedSet)return instance.set(key,value3);return safeApply(untouchedSet,instance,[key,value3])}function safeGet(instance,key){if(extractGet(instance)===untouchedGet)return instance.get(key);return safeApply(untouchedGet,instance,[key])}var untouchedMapSet=Map.prototype.set;var untouchedMapGet=Map.prototype.get;var untouchedMapHas=Map.prototype.has;function extractMapSet(instance){try{return instance.set}catch(err){return}}function extractMapGet(instance){try{return instance.get}catch(err){return}}function extractMapHas(instance){try{return instance.has}catch(err){return}}function safeMapSet(instance,key,value3){if(extractMapSet(instance)===untouchedMapSet)return instance.set(key,value3);return safeApply(untouchedMapSet,instance,[key,value3])}function safeMapGet(instance,key){if(extractMapGet(instance)===untouchedMapGet)return instance.get(key);return safeApply(untouchedMapGet,instance,[key])}function safeMapHas(instance,key){if(extractMapHas(instance)===untouchedMapHas)return instance.has(key);return safeApply(untouchedMapHas,instance,[key])}var untouchedSplit=String.prototype.split;var untouchedStartsWith=String.prototype.startsWith;var untouchedEndsWith=String.prototype.endsWith;var untouchedSubstring=String.prototype.substring;var untouchedToLowerCase=String.prototype.toLowerCase;var untouchedToUpperCase=String.prototype.toUpperCase;var untouchedPadStart=String.prototype.padStart;var untouchedCharCodeAt=String.prototype.charCodeAt;var untouchedNormalize=String.prototype.normalize;var untouchedReplace=String.prototype.replace;function extractSplit(instance){try{return instance.split}catch{return}}function extractStartsWith(instance){try{return instance.startsWith}catch{return}}function extractEndsWith(instance){try{return instance.endsWith}catch{return}}function extractSubstring(instance){try{return instance.substring}catch{return}}function extractToLowerCase(instance){try{return instance.toLowerCase}catch{return}}function extractToUpperCase(instance){try{return instance.toUpperCase}catch{return}}function extractPadStart(instance){try{return instance.padStart}catch{return}}function extractCharCodeAt(instance){try{return instance.charCodeAt}catch{return}}function extractNormalize(instance){try{return instance.normalize}catch(err){return}}function extractReplace(instance){try{return instance.replace}catch{return}}function safeSplit(instance,...args2){if(extractSplit(instance)===untouchedSplit)return instance.split(...args2);return safeApply(untouchedSplit,instance,args2)}function safeStartsWith(instance,...args2){if(extractStartsWith(instance)===untouchedStartsWith)return instance.startsWith(...args2);return safeApply(untouchedStartsWith,instance,args2)}function safeEndsWith(instance,...args2){if(extractEndsWith(instance)===untouchedEndsWith)return instance.endsWith(...args2);return safeApply(untouchedEndsWith,instance,args2)}function safeSubstring(instance,...args2){if(extractSubstring(instance)===untouchedSubstring)return instance.substring(...args2);return safeApply(untouchedSubstring,instance,args2)}function safeToLowerCase(instance){if(extractToLowerCase(instance)===untouchedToLowerCase)return instance.toLowerCase();return safeApply(untouchedToLowerCase,instance,[])}function safeToUpperCase(instance){if(extractToUpperCase(instance)===untouchedToUpperCase)return instance.toUpperCase();return safeApply(untouchedToUpperCase,instance,[])}function safePadStart(instance,...args2){if(extractPadStart(instance)===untouchedPadStart)return instance.padStart(...args2);return safeApply(untouchedPadStart,instance,args2)}function safeCharCodeAt(instance,index2){if(extractCharCodeAt(instance)===untouchedCharCodeAt)return instance.charCodeAt(index2);return safeApply(untouchedCharCodeAt,instance,[index2])}function safeNormalize(instance,form){if(extractNormalize(instance)===untouchedNormalize)return instance.normalize(form);return safeApply(untouchedNormalize,instance,[form])}function safeReplace(instance,pattern,replacement){if(extractReplace(instance)===untouchedReplace)return instance.replace(pattern,replacement);return safeApply(untouchedReplace,instance,[pattern,replacement])}var untouchedNumberToString=Number.prototype.toString;function extractNumberToString(instance){try{return instance.toString}catch{return}}function safeNumberToString(instance,...args2){if(extractNumberToString(instance)===untouchedNumberToString)return instance.toString(...args2);return safeApply(untouchedNumberToString,instance,args2)}var untouchedHasOwnProperty=Object.prototype.hasOwnProperty;var untouchedToString=Object.prototype.toString;function safeHasOwnProperty(instance,v){return safeApply(untouchedHasOwnProperty,instance,[v])}function safeToString2(instance){return safeApply(untouchedToString,instance,[])}var untouchedErrorToString=Error.prototype.toString;function safeErrorToString(instance){return safeApply(untouchedErrorToString,instance,[])}var LazyIterableIterator=class{constructor(producer){this.producer=producer}[Symbol.iterator](){if(this.it===undefined)this.it=this.producer();return this.it}next(){if(this.it===undefined)this.it=this.producer();return this.it.next()}};function makeLazy2(producer){return new LazyIterableIterator(producer)}var safeArrayIsArray$4=Array.isArray;var safeObjectDefineProperty$3=Object.defineProperty;function tupleMakeItCloneable(vs,ctxs,values3){return safeObjectDefineProperty$3(vs,cloneMethod,{value:()=>{const cloned=[];for(let idx=0;idx!==values3.length;++idx){let current=values3[idx];if(current===undefined)current=new Value(vs[idx],ctxs[idx]);safePush(cloned,current.value)}tupleMakeItCloneable(cloned,ctxs,values3);return cloned}})}function tupleShrink(arbs,value3,context3){const shrinks=[];const safeContext=safeArrayIsArray$4(context3)?context3:[];for(let idx=0;idx!==arbs.length;++idx)safePush(shrinks,makeLazy2(()=>arbs[idx].shrink(value3[idx],safeContext[idx]).map((v)=>{let cloneable=false;const vs=[];const ctxs=[];const mapped=[];for(let nestedIdx=0;nestedIdx!==arbs.length;++nestedIdx){const nestedV=nestedIdx===idx?v:new Value(cloneIfNeeded(value3[nestedIdx]),safeContext[nestedIdx]);if(nestedV.hasToBeCloned){cloneable=true;mapped[nestedIdx]=nestedV}safePush(vs,nestedV.value);safePush(ctxs,nestedV.context)}if(cloneable)tupleMakeItCloneable(vs,ctxs,mapped);return new Value(vs,ctxs)})));return Stream.nil().join(...shrinks)}var TupleArbitrary=class extends Arbitrary{constructor(arbs){super();this.arbs=arbs;for(let idx=0;idx!==arbs.length;++idx){const arb=arbs[idx];if(arb===null||arb===undefined||arb.generate===null||arb.generate===undefined)throw new Error(`Invalid parameter encountered at index ${idx}: expecting an Arbitrary`)}}generate(mrng,biasFactor){let cloneable=false;const vs=[];const ctxs=[];const mapped=[];for(let idx=0;idx!==this.arbs.length;++idx){const v=this.arbs[idx].generate(mrng,biasFactor);if(v.hasToBeCloned){cloneable=true;mapped[idx]=v}safePush(vs,v.value);safePush(ctxs,v.context)}if(cloneable)tupleMakeItCloneable(vs,ctxs,mapped);return new Value(vs,ctxs)}canShrinkWithoutContext(value3){if(!safeArrayIsArray$4(value3)||value3.length!==this.arbs.length)return false;for(let index2=0;index2!==this.arbs.length;++index2)if(!this.arbs[index2].canShrinkWithoutContext(value3[index2]))return false;return true}shrink(value3,context3){return tupleShrink(this.arbs,value3,context3)}};function tuple2(...arbs){return new TupleArbitrary(arbs)}var safeMathLog$3=Math.log;function runIdToFrequency(runId){return 2+~~(safeMathLog$3(runId+1)*0.4342944819032518)}var globalParameters={};function configureGlobal(parameters){globalParameters=parameters}function readConfigureGlobal(){return globalParameters}function resetConfigureGlobal(){globalParameters={}}var UndefinedContextPlaceholder=Symbol("UndefinedContextPlaceholder");function noUndefinedAsContext(value3){if(value3.context!==undefined)return value3;if(value3.hasToBeCloned)return new Value(value3.value_,UndefinedContextPlaceholder,()=>value3.value);return new Value(value3.value_,UndefinedContextPlaceholder)}var dummyHook$1=()=>{};var AsyncProperty=class{constructor(arb,predicate){this.arb=arb;this.predicate=predicate;const{asyncBeforeEach,asyncAfterEach,beforeEach,afterEach}=readConfigureGlobal()||{};if(asyncBeforeEach!==undefined&&beforeEach!==undefined)throw SError(`Global "asyncBeforeEach" and "beforeEach" parameters can't be set at the same time when running async properties`);if(asyncAfterEach!==undefined&&afterEach!==undefined)throw SError(`Global "asyncAfterEach" and "afterEach" parameters can't be set at the same time when running async properties`);this.beforeEachHook=asyncBeforeEach||beforeEach||dummyHook$1;this.afterEachHook=asyncAfterEach||afterEach||dummyHook$1}isAsync(){return true}generate(mrng,runId){return noUndefinedAsContext(this.arb.generate(mrng,runId!==undefined?runIdToFrequency(runId):undefined))}shrink(value3){if(value3.context===undefined&&!this.arb.canShrinkWithoutContext(value3.value_))return Stream.nil();const safeContext=value3.context!==UndefinedContextPlaceholder?value3.context:undefined;return this.arb.shrink(value3.value_,safeContext).map(noUndefinedAsContext)}async runBeforeEach(){await this.beforeEachHook()}async runAfterEach(){await this.afterEachHook()}async run(v){try{const output=await this.predicate(v);return output===undefined||output===true?null:{error:new SError("Property failed by returning false")}}catch(err){if(PreconditionFailure.isFailure(err))return err;return{error:err}}}beforeEach(hookFunction){const previousBeforeEachHook=this.beforeEachHook;this.beforeEachHook=()=>hookFunction(previousBeforeEachHook);return this}afterEach(hookFunction){const previousAfterEachHook=this.afterEachHook;this.afterEachHook=()=>hookFunction(previousAfterEachHook);return this}};var AlwaysShrinkableArbitrary=class extends Arbitrary{constructor(arb){super();this.arb=arb}generate(mrng,biasFactor){return noUndefinedAsContext(this.arb.generate(mrng,biasFactor))}canShrinkWithoutContext(_value){return true}shrink(value3,context3){if(context3===undefined&&!this.arb.canShrinkWithoutContext(value3))return Stream.nil();const safeContext=context3!==UndefinedContextPlaceholder?context3:undefined;return this.arb.shrink(value3,safeContext).map(noUndefinedAsContext)}};function asyncProperty(...args2){if(args2.length<2)throw new Error("asyncProperty expects at least two parameters");const arbs=safeSlice(args2,0,args2.length-1);const p=args2[args2.length-1];safeForEach(arbs,assertIsArbitrary);return new AsyncProperty(tuple2(...safeMap(arbs,(arb)=>new AlwaysShrinkableArbitrary(arb))),(t)=>p(...t))}var dummyHook=()=>{};var Property=class{constructor(arb,predicate){this.arb=arb;this.predicate=predicate;const{beforeEach=dummyHook,afterEach=dummyHook,asyncBeforeEach,asyncAfterEach}=readConfigureGlobal()||{};if(asyncBeforeEach!==undefined)throw SError(`"asyncBeforeEach" can't be set when running synchronous properties`);if(asyncAfterEach!==undefined)throw SError(`"asyncAfterEach" can't be set when running synchronous properties`);this.beforeEachHook=beforeEach;this.afterEachHook=afterEach}isAsync(){return false}generate(mrng,runId){return noUndefinedAsContext(this.arb.generate(mrng,runId!==undefined?runIdToFrequency(runId):undefined))}shrink(value3){if(value3.context===undefined&&!this.arb.canShrinkWithoutContext(value3.value_))return Stream.nil();const safeContext=value3.context!==UndefinedContextPlaceholder?value3.context:undefined;return this.arb.shrink(value3.value_,safeContext).map(noUndefinedAsContext)}runBeforeEach(){this.beforeEachHook()}runAfterEach(){this.afterEachHook()}run(v){try{const output=this.predicate(v);return output===undefined||output===true?null:{error:new SError("Property failed by returning false")}}catch(err){if(PreconditionFailure.isFailure(err))return err;return{error:err}}}beforeEach(hookFunction){const previousBeforeEachHook=this.beforeEachHook;this.beforeEachHook=()=>hookFunction(previousBeforeEachHook);return this}afterEach(hookFunction){const previousAfterEachHook=this.afterEachHook;this.afterEachHook=()=>hookFunction(previousAfterEachHook);return this}};function property(...args2){if(args2.length<2)throw new Error("property expects at least two parameters");const arbs=safeSlice(args2,0,args2.length-1);const p=args2[args2.length-1];safeForEach(arbs,assertIsArbitrary);return new Property(tuple2(...safeMap(arbs,(arb)=>new AlwaysShrinkableArbitrary(arb))),(t)=>p(...t))}var VerbosityLevel=function(VerbosityLevel2){VerbosityLevel2[VerbosityLevel2["None"]=0]="None";VerbosityLevel2[VerbosityLevel2["Verbose"]=1]="Verbose";VerbosityLevel2[VerbosityLevel2["VeryVerbose"]=2]="VeryVerbose";return VerbosityLevel2}({});function adaptRandomGeneratorTo8x(rng){if("unsafeNext"in rng){if(rng.unsafeJump===undefined)return{clone:()=>adaptRandomGeneratorTo8x(rng),next:()=>rng.unsafeNext(),getState:()=>rng.getState()};return{clone:()=>adaptRandomGeneratorTo8x(rng),next:()=>rng.unsafeNext(),jump:()=>rng.unsafeJump(),getState:()=>rng.getState()}}return rng}function adaptRandomGeneratorToInternal(rng){if("jump"in rng&&typeof rng.jump==="function")return rng;return{clone:()=>adaptRandomGeneratorToInternal(rng),next:()=>rng.next(),jump:()=>skipN(rng,42),getState:()=>rng.getState()}}function adaptRandomGenerator(rng){return adaptRandomGeneratorToInternal(adaptRandomGeneratorTo8x(rng))}var safeDateNow$1=Date.now;var safeMathMin$6=Math.min;var safeMathRandom=Math.random;var QualifiedParameters=class{constructor(op){const p=op||{};this.seed=readSeed(p);this.randomType=readRandomType(p);this.numRuns=readNumRuns(p);this.verbose=readVerbose(p);this.maxSkipsPerRun=p.maxSkipsPerRun!==undefined?p.maxSkipsPerRun:100;this.timeout=safeTimeout(p.timeout);this.skipAllAfterTimeLimit=safeTimeout(p.skipAllAfterTimeLimit);this.interruptAfterTimeLimit=safeTimeout(p.interruptAfterTimeLimit);this.markInterruptAsFailure=p.markInterruptAsFailure===true;this.skipEqualValues=p.skipEqualValues===true;this.ignoreEqualValues=p.ignoreEqualValues===true;this.logger=p.logger!==undefined?p.logger:(v)=>{console.log(v)};this.path=p.path!==undefined?p.path:"";this.unbiased=p.unbiased===true;this.examples=p.examples!==undefined?p.examples:[];this.endOnFailure=p.endOnFailure===true;this.reporter=p.reporter;this.asyncReporter=p.asyncReporter;this.includeErrorInReport=p.includeErrorInReport===true}toParameters(){return{seed:this.seed,randomType:this.randomType,numRuns:this.numRuns,maxSkipsPerRun:this.maxSkipsPerRun,timeout:this.timeout,skipAllAfterTimeLimit:this.skipAllAfterTimeLimit,interruptAfterTimeLimit:this.interruptAfterTimeLimit,markInterruptAsFailure:this.markInterruptAsFailure,skipEqualValues:this.skipEqualValues,ignoreEqualValues:this.ignoreEqualValues,path:this.path,logger:this.logger,unbiased:this.unbiased,verbose:this.verbose,examples:this.examples,endOnFailure:this.endOnFailure,reporter:this.reporter,asyncReporter:this.asyncReporter,includeErrorInReport:this.includeErrorInReport}}};function createQualifiedRandomGenerator(random2){return(seed)=>{return adaptRandomGenerator(random2(seed))}}function readSeed(p){if(p.seed===undefined)return safeDateNow$1()^safeMathRandom()*4294967296;const seed32=p.seed|0;if(p.seed===seed32)return seed32;return seed32^(p.seed-seed32)*4294967296}function readRandomType(p){if(p.randomType===undefined)return xorshift128plus;if(typeof p.randomType==="string")switch(p.randomType){case"mersenne":return createQualifiedRandomGenerator(mersenne);case"congruential":case"congruential32":return createQualifiedRandomGenerator(congruential32);case"xorshift128plus":return xorshift128plus;case"xoroshiro128plus":return xoroshiro128plus;default:throw new Error(`Invalid random specified: '${p.randomType}'`)}const mrng=p.randomType(0);if("min"in mrng&&mrng.min!==-2147483648)throw new Error(`Invalid random number generator: min must equal -0x80000000, got ${String(mrng.min)}`);if("max"in mrng&&mrng.max!==2147483647)throw new Error(`Invalid random number generator: max must equal 0x7fffffff, got ${String(mrng.max)}`);if(mrng===adaptRandomGenerator(mrng))return p.randomType;return createQualifiedRandomGenerator(p.randomType)}function readNumRuns(p){const defaultValue=100;if(p.numRuns!==undefined)return p.numRuns;if(p.num_runs!==undefined)return p.num_runs;return defaultValue}function readVerbose(p){if(p.verbose===undefined)return 0;if(typeof p.verbose==="boolean")return p.verbose===true?1:0;if(p.verbose<=0)return 0;if(p.verbose>=2)return 2;return p.verbose|0}function safeTimeout(value3){if(value3===undefined)return;return safeMathMin$6(value3,2147483647)}function read(op){return new QualifiedParameters(op)}function interruptAfter(timeMs,setTimeoutSafe,clearTimeoutSafe){let timeoutHandle=null;return{clear:()=>clearTimeoutSafe(timeoutHandle),promise:new Promise((resolve4)=>{timeoutHandle=setTimeoutSafe(()=>{resolve4(new PreconditionFailure(true))},timeMs)})}}var SkipAfterProperty=class{constructor(property2,getTime,timeLimit,interruptExecution,setTimeoutSafe,clearTimeoutSafe){this.property=property2;this.getTime=getTime;this.interruptExecution=interruptExecution;this.setTimeoutSafe=setTimeoutSafe;this.clearTimeoutSafe=clearTimeoutSafe;this.skipAfterTime=this.getTime()+timeLimit}isAsync(){return this.property.isAsync()}generate(mrng,runId){return this.property.generate(mrng,runId)}shrink(value3){return this.property.shrink(value3)}run(v){const remainingTime=this.skipAfterTime-this.getTime();if(remainingTime<=0){const preconditionFailure=new PreconditionFailure(this.interruptExecution);if(this.isAsync())return Promise.resolve(preconditionFailure);else return preconditionFailure}if(this.interruptExecution&&this.isAsync()){const t=interruptAfter(remainingTime,this.setTimeoutSafe,this.clearTimeoutSafe);const propRun=Promise.race([this.property.run(v),t.promise]);propRun.then(t.clear,t.clear);return propRun}return this.property.run(v)}runBeforeEach(){return this.property.runBeforeEach()}runAfterEach(){return this.property.runAfterEach()}};var timeoutAfter=(timeMs,setTimeoutSafe,clearTimeoutSafe)=>{let timeoutHandle=null;return{clear:()=>clearTimeoutSafe(timeoutHandle),promise:new Promise((resolve4)=>{timeoutHandle=setTimeoutSafe(()=>{resolve4({error:new SError(`Property timeout: exceeded limit of ${timeMs} milliseconds`)})},timeMs)})}};var TimeoutProperty=class{constructor(property2,timeMs,setTimeoutSafe,clearTimeoutSafe){this.property=property2;this.timeMs=timeMs;this.setTimeoutSafe=setTimeoutSafe;this.clearTimeoutSafe=clearTimeoutSafe}isAsync(){return true}generate(mrng,runId){return this.property.generate(mrng,runId)}shrink(value3){return this.property.shrink(value3)}async run(v){const t=timeoutAfter(this.timeMs,this.setTimeoutSafe,this.clearTimeoutSafe);const propRun=Promise.race([this.property.run(v),t.promise]);propRun.then(t.clear,t.clear);return propRun}runBeforeEach(){return Promise.resolve(this.property.runBeforeEach())}runAfterEach(){return Promise.resolve(this.property.runAfterEach())}};var UnbiasedProperty=class{constructor(property2){this.property=property2}isAsync(){return this.property.isAsync()}generate(mrng,_runId){return this.property.generate(mrng,undefined)}shrink(value3){return this.property.shrink(value3)}run(v){return this.property.run(v)}runBeforeEach(){return this.property.runBeforeEach()}runAfterEach(){return this.property.runAfterEach()}};var safeArrayFrom=Array.from;var safeBufferIsBuffer=typeof Buffer!=="undefined"?Buffer.isBuffer:undefined;var safeJsonStringify$1=JSON.stringify;var safeNumberIsNaN$5=Number.isNaN;var safeObjectKeys$5=Object.keys;var safeObjectGetOwnPropertySymbols$2=Object.getOwnPropertySymbols;var safeObjectGetOwnPropertyDescriptor$3=Object.getOwnPropertyDescriptor;var safeObjectGetPrototypeOf$2=Object.getPrototypeOf;var safeNegativeInfinity$7=Number.NEGATIVE_INFINITY;var safePositiveInfinity$8=Number.POSITIVE_INFINITY;var toStringMethod=Symbol.for("fast-check/toStringMethod");function hasToStringMethod(instance){return instance!==null&&(typeof instance==="object"||typeof instance==="function")&&toStringMethod in instance&&typeof instance[toStringMethod]==="function"}var asyncToStringMethod=Symbol.for("fast-check/asyncToStringMethod");function hasAsyncToStringMethod(instance){return instance!==null&&(typeof instance==="object"||typeof instance==="function")&&asyncToStringMethod in instance&&typeof instance[asyncToStringMethod]==="function"}var findSymbolNameRegex=/^Symbol\((.*)\)$/;function getSymbolDescription(s){if(s.description!==undefined)return s.description;const m=findSymbolNameRegex.exec(SString(s));return m&&m[1].length?m[1]:null}function stringifyNumber(numValue){switch(numValue){case 0:return 1/numValue===safeNegativeInfinity$7?"-0":"0";case safeNegativeInfinity$7:return"Number.NEGATIVE_INFINITY";case safePositiveInfinity$8:return"Number.POSITIVE_INFINITY";default:return numValue===numValue?SString(numValue):"Number.NaN"}}function isSparseArray(arr){let previousNumberedIndex=-1;for(const index2 in arr){const numberedIndex=Number(index2);if(numberedIndex!==previousNumberedIndex+1)return true;previousNumberedIndex=numberedIndex}return previousNumberedIndex+1!==arr.length}function stringifyInternal(value3,previousValues,getAsyncContent){const currentValues=[...previousValues,value3];if(typeof value3==="object"){if(safeIndexOf(previousValues,value3)!==-1)return"[cyclic]"}if(hasAsyncToStringMethod(value3)){const content=getAsyncContent(value3);if(content.state==="fulfilled")return content.value}if(hasToStringMethod(value3))try{return value3[toStringMethod]()}catch{}switch(safeToString2(value3)){case"[object Array]":{const arr=value3;if(arr.length>=50&&isSparseArray(arr)){const assignments=[];for(const index2 in arr)if(!safeNumberIsNaN$5(Number(index2)))safePush(assignments,`${index2}:${stringifyInternal(arr[index2],currentValues,getAsyncContent)}`);return assignments.length!==0?`Object.assign(Array(${arr.length}),{${safeJoin(assignments,",")}})`:`Array(${arr.length})`}const stringifiedArray=safeJoin(safeMap(arr,(v)=>stringifyInternal(v,currentValues,getAsyncContent)),",");return arr.length===0||arr.length-1 in arr?`[${stringifiedArray}]`:`[${stringifiedArray},]`}case"[object BigInt]":return`${value3}n`;case"[object Boolean]":{const unboxedToString=value3==true?"true":"false";return typeof value3==="boolean"?unboxedToString:`new Boolean(${unboxedToString})`}case"[object Date]":{const d=value3;return safeNumberIsNaN$5(safeGetTime(d))?`new Date(NaN)`:`new Date(${safeJsonStringify$1(safeToISOString(d))})`}case"[object Map]":return`new Map(${stringifyInternal(Array.from(value3),currentValues,getAsyncContent)})`;case"[object Null]":return`null`;case"[object Number]":return typeof value3==="number"?stringifyNumber(value3):`new Number(${stringifyNumber(Number(value3))})`;case"[object Object]":{try{const toStringAccessor=value3.toString;if(typeof toStringAccessor==="function"&&toStringAccessor!==Object.prototype.toString)return value3.toString()}catch{return"[object Object]"}const mapper=(k)=>`${k==="__proto__"?'["__proto__"]':typeof k==="symbol"?`[${stringifyInternal(k,currentValues,getAsyncContent)}]`:safeJsonStringify$1(k)}:${stringifyInternal(value3[k],currentValues,getAsyncContent)}`;return"{"+safeJoin([...safeObjectGetPrototypeOf$2(value3)===null?["__proto__:null"]:[],...safeMap(safeObjectKeys$5(value3),mapper),...safeMap(safeFilter(safeObjectGetOwnPropertySymbols$2(value3),(s)=>{const descriptor=safeObjectGetOwnPropertyDescriptor$3(value3,s);return descriptor&&descriptor.enumerable}),mapper)],",")+"}"}case"[object Set]":return`new Set(${stringifyInternal(Array.from(value3),currentValues,getAsyncContent)})`;case"[object String]":return typeof value3==="string"?safeJsonStringify$1(value3):`new String(${safeJsonStringify$1(value3)})`;case"[object Symbol]":{const s=value3;if(SSymbol.keyFor(s)!==undefined)return`Symbol.for(${safeJsonStringify$1(SSymbol.keyFor(s))})`;const desc=getSymbolDescription(s);if(desc===null)return"Symbol()";return s===(desc.startsWith("Symbol.")&&SSymbol[desc.substring(7)])?desc:`Symbol(${safeJsonStringify$1(desc)})`}case"[object Promise]":{const promiseContent=getAsyncContent(value3);switch(promiseContent.state){case"fulfilled":return`Promise.resolve(${stringifyInternal(promiseContent.value,currentValues,getAsyncContent)})`;case"rejected":return`Promise.reject(${stringifyInternal(promiseContent.value,currentValues,getAsyncContent)})`;case"pending":return`new Promise(() => {/*pending*/})`;default:return`new Promise(() => {/*unknown*/})`}}case"[object Error]":if(value3 instanceof Error)return`new Error(${stringifyInternal(value3.message,currentValues,getAsyncContent)})`;break;case"[object Undefined]":return`undefined`;case"[object Int8Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Int16Array]":case"[object Uint16Array]":case"[object Int32Array]":case"[object Uint32Array]":case"[object Float32Array]":case"[object Float64Array]":case"[object BigInt64Array]":case"[object BigUint64Array]":{if(typeof safeBufferIsBuffer==="function"&&safeBufferIsBuffer(value3))return`Buffer.from(${value3.buffer.detached?"/*detached ArrayBuffer*/":stringifyInternal(safeArrayFrom(value3.values()),currentValues,getAsyncContent)})`;const valuePrototype=safeObjectGetPrototypeOf$2(value3);const className=valuePrototype&&valuePrototype.constructor&&valuePrototype.constructor.name;if(typeof className==="string"){const typedArray=value3;if(typedArray.buffer.detached)return`${className}.from(/*detached ArrayBuffer*/)`;const valuesFromTypedArr=typedArray.values();return`${className}.from(${stringifyInternal(safeArrayFrom(valuesFromTypedArr),currentValues,getAsyncContent)})`}break}}try{return value3.toString()}catch{return safeToString2(value3)}}function stringify(value3){return stringifyInternal(value3,[],()=>({state:"unknown",value:undefined}))}function possiblyAsyncStringify(value3){const stillPendingMarker=SSymbol();const pendingPromisesForCache=[];const cache=new SMap$1;function createDelay0(){let handleId=null;const cancel=()=>{if(handleId!==null)clearTimeout(handleId)};return{delay:new Promise((resolve4)=>{handleId=setTimeout(()=>{handleId=null;resolve4(stillPendingMarker)},0)}),cancel}}const unknownState={state:"unknown",value:undefined};const getAsyncContent=function getAsyncContent2(data){const cacheKey=data;if(cache.has(cacheKey))return cache.get(cacheKey);const delay0=createDelay0();const p=asyncToStringMethod in data?Promise.resolve().then(()=>data[asyncToStringMethod]()):data;p.catch(()=>{});pendingPromisesForCache.push(Promise.race([p,delay0.delay]).then((successValue)=>{if(successValue===stillPendingMarker)cache.set(cacheKey,{state:"pending",value:undefined});else cache.set(cacheKey,{state:"fulfilled",value:successValue});delay0.cancel()},(errorValue)=>{cache.set(cacheKey,{state:"rejected",value:errorValue});delay0.cancel()}));cache.set(cacheKey,unknownState);return unknownState};function loop(){const stringifiedValue=stringifyInternal(value3,[],getAsyncContent);if(pendingPromisesForCache.length===0)return stringifiedValue;return Promise.all(pendingPromisesForCache.splice(0)).then(loop)}return loop()}async function asyncStringify(value3){return Promise.resolve(possiblyAsyncStringify(value3))}function fromSyncCached(cachedValue){return cachedValue===null?new PreconditionFailure:cachedValue}function fromCached(...data){if(data[1])return data[0].then(fromSyncCached);return fromSyncCached(data[0])}function fromCachedUnsafe(cachedValue,isAsync){return fromCached(cachedValue,isAsync)}var IgnoreEqualValuesProperty=class{constructor(property2,skipRuns){this.property=property2;this.skipRuns=skipRuns;this.coveredCases=new Map}isAsync(){return this.property.isAsync()}generate(mrng,runId){return this.property.generate(mrng,runId)}shrink(value3){return this.property.shrink(value3)}run(v){const stringifiedValue=stringify(v);if(this.coveredCases.has(stringifiedValue)){const lastOutput=this.coveredCases.get(stringifiedValue);if(!this.skipRuns)return lastOutput;return fromCachedUnsafe(lastOutput,this.property.isAsync())}const out=this.property.run(v);this.coveredCases.set(stringifiedValue,out);return out}runBeforeEach(){return this.property.runBeforeEach()}runAfterEach(){return this.property.runAfterEach()}};var safeDateNow=Date.now;var safeSetTimeout=setTimeout;var safeClearTimeout=clearTimeout;function decorateProperty(rawProperty,qParams){let prop=rawProperty;if(rawProperty.isAsync()&&qParams.timeout!==undefined)prop=new TimeoutProperty(prop,qParams.timeout,safeSetTimeout,safeClearTimeout);if(qParams.unbiased)prop=new UnbiasedProperty(prop);if(qParams.skipAllAfterTimeLimit!==undefined)prop=new SkipAfterProperty(prop,safeDateNow,qParams.skipAllAfterTimeLimit,false,safeSetTimeout,safeClearTimeout);if(qParams.interruptAfterTimeLimit!==undefined)prop=new SkipAfterProperty(prop,safeDateNow,qParams.interruptAfterTimeLimit,true,safeSetTimeout,safeClearTimeout);if(qParams.skipEqualValues)prop=new IgnoreEqualValuesProperty(prop,true);if(qParams.ignoreEqualValues)prop=new IgnoreEqualValuesProperty(prop,false);return prop}var ExecutionStatus=function(ExecutionStatus2){ExecutionStatus2[ExecutionStatus2["Success"]=0]="Success";ExecutionStatus2[ExecutionStatus2["Skipped"]=-1]="Skipped";ExecutionStatus2[ExecutionStatus2["Failure"]=1]="Failure";return ExecutionStatus2}({});var RunExecution=class RunExecution2{constructor(verbosity,interruptedAsFailure){this.verbosity=verbosity;this.interruptedAsFailure=interruptedAsFailure;this.rootExecutionTrees=[];this.currentLevelExecutionTrees=this.rootExecutionTrees;this.failure=null;this.numSkips=0;this.numSuccesses=0;this.interrupted=false}appendExecutionTree(status,value3){const currentTree={status,value:value3,children:[]};this.currentLevelExecutionTrees.push(currentTree);return currentTree}fail(value3,id2,failure){if(this.verbosity>=1){const currentTree=this.appendExecutionTree(1,value3);this.currentLevelExecutionTrees=currentTree.children}if(this.pathToFailure===undefined)this.pathToFailure=`${id2}`;else this.pathToFailure+=`:${id2}`;this.value=value3;this.failure=failure}skip(value3){if(this.verbosity>=2)this.appendExecutionTree(-1,value3);if(this.pathToFailure===undefined)++this.numSkips}success(value3){if(this.verbosity>=2)this.appendExecutionTree(0,value3);if(this.pathToFailure===undefined)++this.numSuccesses}interrupt(){this.interrupted=true}isSuccess(){return this.pathToFailure===undefined}firstFailure(){return this.pathToFailure!==undefined?+safeSplit(this.pathToFailure,":")[0]:-1}numShrinks(){return this.pathToFailure!==undefined?safeSplit(this.pathToFailure,":").length-1:0}extractFailures(){if(this.isSuccess())return[];const failures=[];let cursor=this.rootExecutionTrees;while(cursor.length>0&&cursor[cursor.length-1].status===1){const failureTree=cursor[cursor.length-1];failures.push(failureTree.value);cursor=failureTree.children}return failures}static mergePaths(offsetPath,path){if(offsetPath.length===0)return path;const offsetItems=offsetPath.split(":");const remainingItems=path.split(":");const middle=+offsetItems[offsetItems.length-1]+ +remainingItems[0];return[...offsetItems.slice(0,offsetItems.length-1),`${middle}`,...remainingItems.slice(1)].join(":")}toRunDetails(seed,basePath,maxSkips,qParams){if(!this.isSuccess())return{failed:true,interrupted:this.interrupted,numRuns:this.firstFailure()+1-this.numSkips,numSkips:this.numSkips,numShrinks:this.numShrinks(),seed,counterexample:this.value,counterexamplePath:RunExecution2.mergePaths(basePath,this.pathToFailure),errorInstance:this.failure.error,failures:this.extractFailures(),executionSummary:this.rootExecutionTrees,verbose:this.verbosity,runConfiguration:qParams.toParameters()};const considerInterruptedAsFailure=this.interruptedAsFailure||this.numSuccesses===0;return{failed:this.numSkips>maxSkips||this.interrupted&&considerInterruptedAsFailure,interrupted:this.interrupted,numRuns:this.numSuccesses,numSkips:this.numSkips,numShrinks:0,seed,counterexample:null,counterexamplePath:null,error:null,errorInstance:null,failures:[],executionSummary:this.rootExecutionTrees,verbose:this.verbosity,runConfiguration:qParams.toParameters()}}};var RunnerIterator=class{constructor(sourceValues,shrink,verbose,interruptedAsFailure){this.sourceValues=sourceValues;this.shrink=shrink;this.runExecution=new RunExecution(verbose,interruptedAsFailure);this.currentIdx=-1;this.nextValues=sourceValues}[Symbol.iterator](){return this}next(){const nextValue=this.nextValues.next();if(nextValue.done||this.runExecution.interrupted)return{done:true,value:undefined};this.currentValue=nextValue.value;++this.currentIdx;return{done:false,value:nextValue.value.value_}}handleResult(result3){if(result3!==null&&typeof result3==="object"&&!PreconditionFailure.isFailure(result3)){this.runExecution.fail(this.currentValue.value_,this.currentIdx,result3);this.currentIdx=-1;this.nextValues=this.shrink(this.currentValue)}else if(result3!==null)if(!result3.interruptExecution){this.runExecution.skip(this.currentValue.value_);this.sourceValues.skippedOne()}else this.runExecution.interrupt();else this.runExecution.success(this.currentValue.value_)}};var SourceValuesIterator=class{constructor(initialValues,maxInitialIterations,remainingSkips){this.initialValues=initialValues;this.maxInitialIterations=maxInitialIterations;this.remainingSkips=remainingSkips}[Symbol.iterator](){return this}next(){if(--this.maxInitialIterations!==-1&&this.remainingSkips>=0){const n=this.initialValues.next();if(!n.done)return{value:n.value,done:false}}return{value:undefined,done:true}}skippedOne(){--this.remainingSkips;++this.maxInitialIterations}};var MIN_INT=-2147483648;var MAX_INT=2147483647;var DBL_FACTOR=Math.pow(2,27);var DBL_DIVISOR=Math.pow(2,-53);var Random=class Random2{constructor(sourceRng){this.internalRng=adaptRandomGenerator(sourceRng.clone())}clone(){return new Random2(this.internalRng)}next(bits){return uniformInt(this.internalRng,0,(1<<bits)-1)}nextBoolean(){return uniformInt(this.internalRng,0,1)===1}nextInt(min5,max5){return uniformInt(this.internalRng,min5===undefined?MIN_INT:min5,max5===undefined?MAX_INT:max5)}nextBigInt(min5,max5){return uniformBigInt(this.internalRng,min5,max5)}nextDouble(){const a=this.next(26);const b=this.next(27);return(a*DBL_FACTOR+b)*DBL_DIVISOR}getState(){if("getState"in this.internalRng&&typeof this.internalRng.getState==="function")return this.internalRng.getState()}};function tossNext(generator,rng,index2){rng.jump();return generator.generate(new Random(rng),index2)}function*toss(generator,seed,random2,examples){for(let idx=0;idx!==examples.length;++idx)yield new Value(examples[idx],undefined);for(let idx=0,rng=random2(seed);;++idx)yield tossNext(generator,rng,idx)}function lazyGenerate(generator,rng,idx){return()=>generator.generate(new Random(rng),idx)}function*lazyToss(generator,seed,random2,examples){yield*safeMap(examples,(e)=>()=>new Value(e,undefined));let idx=0;const rng=adaptRandomGenerator(random2(seed));for(;;){rng.jump();yield lazyGenerate(generator,rng,idx++)}}function produce(producer){return producer()}function pathWalk(path,initialProducers,shrink){const producers=initialProducers;const segments=path.split(":").map((text)=>+text);if(segments.length===0)return producers.map(produce);if(!segments.every((v)=>!Number.isNaN(v)))throw new Error(`Unable to replay, got invalid path=${path}`);let values3=producers.drop(segments[0]).map(produce);for(const s of segments.slice(1)){const valueToShrink=values3.getNthOrLast(0);if(valueToShrink===null)throw new Error(`Unable to replay, got wrong path=${path}`);values3=shrink(valueToShrink).drop(s)}return values3}var safeObjectAssign$6=Object.assign;function formatHints(hints){if(hints.length===1)return`Hint: ${hints[0]}`;return hints.map((h,idx)=>`Hint (${idx+1}): ${h}`).join(`
189
+ at ${formatPath(path)}`}return new Error(message)}var arbitraryMemoMap=new WeakMap;var suspendDepthIdentifierMap=new WeakMap;var emptyRecursionStack=[];function makeReport(){return{warnings:[]}}function toReport(report){return{warnings:report.warnings.slice()}}function arbitraryError(what){return new Error(`Unable to derive an arbitrary for ${what}`)}var entryComparator=([a],[b])=>equals(a,b);function applyChecks(ast,filters,arbitrary){return filters.reduce((acc,filter10)=>acc.filter((a)=>filter10.run(a,ast,defaultParseOptions)===undefined),arbitrary)}function validateArrayConstraints(constraint,label){if(constraint?.minLength!==undefined&&constraint.maxLength!==undefined&&constraint.minLength>constraint.maxLength){throw arbitraryError(`${label} constraints`)}}function lengthToFastCheckConstraints(constraint){return constraint===undefined||constraint.minLength===undefined&&constraint.maxLength===undefined?undefined:{...constraint.minLength!==undefined?{minLength:constraint.minLength}:{},...constraint.maxLength!==undefined?{maxLength:constraint.maxLength}:{}}}function arrayWithConstraints(fc,item,constraint,comparator){return comparator?fc.uniqueArray(item,{...constraint,comparator}):fc.array(item,constraint)}function array2(fc,ctx,item,terminal=false){const constraint=ctx.constraint;const arrayConstraints=lengthToFastCheckConstraints(constraint);validateArrayConstraints(arrayConstraints,"array");return arrayWithConstraints(fc,item,terminal?{...arrayConstraints,maxLength:arrayConstraints?.minLength??0}:arrayConstraints,constraint?.unique?equals:undefined)}function appendArray(fc,out,len,rest){return out.chain((as3)=>as3.length<len?fc.constant(as3):rest.map((rest2)=>[...as3,...rest2]))}function appendObjectEntries(out,entries3){return out.chain((o)=>entries3.map((entries4)=>({...Object.fromEntries(entries4),...o})))}var max4=makeReducer(ReducerMax);var min4=makeReducer(ReducerMin);var or2=makeReducer(ReducerOr);var concat=makeReducer(makeReducerConcat());var combiner=makeCombiner({integer:or2,maxLength:min4,minLength:max4,noInfinity:or2,noNaN:or2,patterns:concat,unique:or2,valid:or2},{omitKeyWhen:isUndefined});function mergeOrderedBound(order,self,selfExclusive,that,thatExclusive,takeComparison){if(that===undefined||self===undefined){return that===undefined?[self,selfExclusive]:[that,thatExclusive]}const comparison=order(self,that);return comparison===takeComparison?[that,thatExclusive]:comparison===0?[self,selfExclusive||thatExclusive]:[self,selfExclusive]}function mergeOrderedConstraints(self,that){if(self===undefined){return that}if(self.order!==that.order){throw new Error("Cannot merge ordered arbitrary constraints with different Order instances")}const[minimum,exclusiveMinimum]=mergeOrderedBound(self.order,self.minimum,self.exclusiveMinimum,that.minimum,that.exclusiveMinimum,-1);const[maximum,exclusiveMaximum]=mergeOrderedBound(self.order,self.maximum,self.exclusiveMaximum,that.maximum,that.exclusiveMaximum,1);return{order:self.order,...minimum!==undefined?{minimum}:{},...exclusiveMinimum!==undefined?{exclusiveMinimum}:{},...maximum!==undefined?{maximum}:{},...exclusiveMaximum!==undefined?{exclusiveMaximum}:{}}}function mergeConstraint(self,that){const{ordered:selfOrdered,...selfRest}=self??{};const{ordered:thatOrdered,...thatRest}=that;const ordered=thatOrdered===undefined?selfOrdered:mergeOrderedConstraints(selfOrdered,thatOrdered);const out=combiner.combine(selfRest,thatRest);return{...out,...ordered===undefined?{}:{ordered}}}function collectChecks(checks){const filters=[];const arbitraries=[];function visit(check){if(check.annotations?.arbitrary){arbitraries.push(check.annotations.arbitrary)}if(check._tag!=="Filter"){for(const child of check.checks){visit(child)}}else{filters.push(check)}}checks?.forEach(visit);return{filters,arbitraries}}function constraintContext(arbitraries){const constraintAnnotations=arbitraries.map(({constraint})=>constraint).filter(isNotUndefined);return(ctx)=>{const constraint=constraintAnnotations.reduce((acc,c)=>mergeConstraint(acc,c),ctx.constraint);return{...ctx,constraint}}}function resetContext(ctx){return{...ctx,constraint:undefined}}function objectEntriesConstraints(ast,constraint,requiredKeys){if(constraint===undefined||constraint.minLength===undefined&&constraint.maxLength===undefined){return}if(constraint.minLength!==undefined&&ast.indexSignatures.length===0&&constraint.minLength>ast.propertySignatures.length){throw arbitraryError("object property constraints")}const out={};if(constraint.minLength!==undefined){out.minLength=Math.max(0,constraint.minLength-requiredKeys)}if(constraint.maxLength!==undefined){out.maxLength=constraint.maxLength-requiredKeys;if(out.maxLength<0){throw arbitraryError("object property constraints")}}validateArrayConstraints(out,"object property");return out}function objectWithOptionalCount(fc,pss,orderedNames,requiredKeys,optionalNames,constraint){const requiredCount=requiredKeys.length;if(constraint.maxLength!==undefined&&constraint.maxLength<requiredCount){throw arbitraryError("object property constraints")}const minOptional=constraint.minLength===undefined?0:Math.max(0,constraint.minLength-requiredCount);const maxOptional=constraint.maxLength===undefined?optionalNames.length:Math.min(optionalNames.length,constraint.maxLength-requiredCount);if(minOptional>maxOptional){throw arbitraryError("object property constraints")}const full=fc.record(pss,{requiredKeys:[...requiredKeys,...optionalNames]});const chosen=fc.shuffledSubarray([...optionalNames],{minLength:minOptional,maxLength:maxOptional});return fc.tuple(full,chosen).map(([base,names])=>{const keep=new Set([...requiredKeys,...names]);const out={};for(const name of orderedNames){if(keep.has(name)){out[name]=base[name]}}return out})}function toRangeConstraints(ordered,min5,max5,error){const out={};if(ordered?.minimum!==undefined){out.min=min5(ordered.minimum,ordered.exclusiveMinimum===true)}if(ordered?.maximum!==undefined){out.max=max5(ordered.maximum,ordered.exclusiveMaximum===true)}if(out.min!==undefined&&out.max!==undefined&&out.min>out.max){throw arbitraryError(error)}return out}function toIntegerConstraints(ordered){return toRangeConstraints(ordered,(minimum,excluded)=>excluded?Math.floor(minimum)+1:Math.ceil(minimum),(maximum,excluded)=>excluded?Math.ceil(maximum)-1:Math.floor(maximum),"integer constraints")}function toFloatConstraints(constraint,ordered){const out={...constraint?.noInfinity?{noDefaultInfinity:true}:{},...constraint?.noNaN?{noNaN:true}:{},...ordered?.minimum!==undefined?{min:ordered.minimum}:{},...ordered?.exclusiveMinimum!==undefined?{minExcluded:ordered.exclusiveMinimum}:{},...ordered?.maximum!==undefined?{max:ordered.maximum}:{},...ordered?.exclusiveMaximum!==undefined?{maxExcluded:ordered.exclusiveMaximum}:{}};if(out.min!==undefined&&out.max!==undefined&&(out.min>out.max||out.min===out.max&&(out.minExcluded||out.maxExcluded))){throw arbitraryError("number constraints")}return out}function toBigIntConstraints(ordered){return toRangeConstraints(ordered,(minimum,excluded)=>excluded?minimum+BigInt(1):minimum,(maximum,excluded)=>excluded?maximum-BigInt(1):maximum,"the ordered bigint constraints")}function makeLazy(normal,terminal){const out=(fc,ctx,recursionStack=emptyRecursionStack)=>normal(fc,ctx,recursionStack);out.terminal=(fc,ctx,recursionStack=emptyRecursionStack)=>terminal(fc,ctx,recursionStack);return out}function same(f){return makeLazy(f,f)}function getSuspendRecursion(fc,ast){const depthIdentifier=suspendDepthIdentifierMap.get(ast)??fc.createDepthIdentifier();suspendDepthIdentifierMap.set(ast,depthIdentifier);return{maxDepth:2,depthIdentifier}}function oneOf(fc,arbitraries){return arbitraries.length===0?undefined:arbitraries.length===1?arbitraries[0]:fc.oneof(...arbitraries)}var finiteNumberConstraint={noInfinity:true,noNaN:true};function finiteNumberContext(ctx){return{...ctx,constraint:finiteNumberConstraint}}function reportChecks(report,checks,path){function visit(check,covered){const arbitrary=check.annotations?.arbitrary;const nextCovered=covered||arbitrary?.constraint!==undefined||arbitrary?.candidate!==undefined;if(check._tag!=="Filter"){for(const child of check.checks){visit(child,nextCovered)}}else if(!nextCovered){const meta=check.annotations?.meta;const description=typeof meta==="object"&&meta!==null&&"_tag"in meta&&typeof meta._tag==="string"?meta._tag:check.annotations?.identifier??check.annotations?.expected;report.warnings.push({_tag:"OpaqueFilter",path,...description===undefined?{}:{description}})}}checks?.forEach((check)=>visit(check,false))}function collectReport(ast,report){const stack=new WeakSet;function visit(ast2,path){if(stack.has(ast2)){return}stack.add(ast2);reportChecks(report,ast2.checks,path);switch(ast2._tag){case"Declaration":ast2.typeParameters.forEach((tp)=>visit(tp,path));break;case"Arrays":{for(const[i,type]of[...ast2.elements,...ast2.rest].entries()){visit(type,[...path,i])}break}case"Objects":ast2.propertySignatures.forEach((ps)=>visit(ps.type,[...path,ps.name]));ast2.indexSignatures.forEach((is)=>{visit(is.parameter,path);visit(is.type,path)});break;case"Union":ast2.types.forEach((type)=>visit(type,path));break;case"TemplateLiteral":ast2.parts.forEach((part,i)=>visit(toEncoded(part),[...path,i]));break;case"Suspend":visit(ast2.thunk(),path);break}stack.delete(ast2)}visit(ast,[])}function applyCandidates(fc,ctx,arbitraries,base){const weighted=base===undefined?[]:[{arbitrary:base,weight:1}];for(const{candidate}of arbitraries){if(!candidate){continue}const arbitrary=candidate.make(fc,ctx);if(arbitrary===undefined){continue}const weight=candidate.weight??1;if(!globalThis.Number.isInteger(weight)||weight<=0){throw arbitraryError("a candidate with an invalid weight")}weighted.push({arbitrary,weight})}return weighted.length===0?undefined:weighted.length===1?weighted[0].arbitrary:fc.oneof(...weighted)}function applyFilterLayer(ast,checks,fc,ctx,base){const out=applyCandidates(fc,ctx,checks.arbitraries,base);return out===undefined?undefined:applyChecks(ast,checks.filters,out)}function normalizeDerivation(output,hasTypeParameters){if(!(typeof output==="object"&&output!==null&&("arbitrary"in output))){return{arbitrary:output,terminal:hasTypeParameters?undefined:output}}const terminal="terminal"in output?output.terminal:hasTypeParameters?undefined:output.arbitrary;return{arbitrary:output.arbitrary,terminal}}function makeTypeParameters(typeParameters,fc,ctx,recursionStack,lazyNormal){return typeParameters.map((tp)=>({arbitrary:lazyNormal?fc.constant(null).chain(()=>tp(fc,ctx,recursionStack)):tp(fc,ctx,recursionStack),terminal:tp.terminal(fc,ctx,recursionStack)}))}function filterLayer(ast,checks,normalBase,terminalBase){const f=constraintContext(checks.arbitraries);return makeLazy((fc,ctx,recursionStack)=>{const nextCtx=f(ctx);return applyFilterLayer(ast,checks,fc,nextCtx,normalBase(fc,ctx,nextCtx,recursionStack))},(fc,ctx,recursionStack)=>{const nextCtx=f(ctx);return applyFilterLayer(ast,checks,fc,nextCtx,terminalBase(fc,ctx,nextCtx,recursionStack))})}var memoized=memoize((ast)=>recur(ast,[]));function recur(ast,path){const annotation=resolve(ast)?.toArbitrary;if(annotation){const typeParameters=isDeclaration(ast)?ast.typeParameters.map((tp)=>recur(tp,path)):[];const checks=collectChecks(ast.checks);const derive=(lazyNormal)=>(fc,ctx,nextCtx,recursionStack)=>normalizeDerivation(annotation(makeTypeParameters(typeParameters,fc,resetContext(ctx),recursionStack,lazyNormal))(fc,nextCtx),typeParameters.length>0)[lazyNormal?"terminal":"arbitrary"];return filterLayer(ast,checks,derive(false),derive(true))}if(ast.checks){const checks=collectChecks(ast.checks);const lawc=recur(replaceChecks(ast,undefined),path);return filterLayer(ast,checks,(fc,_ctx,nextCtx,recursionStack)=>lawc(fc,nextCtx,recursionStack),(fc,_ctx,nextCtx,recursionStack)=>lawc.terminal(fc,nextCtx,recursionStack))}return base(ast,path)}function base(ast,path){switch(ast._tag){case"Never":case"Declaration":throw errorWithPath(`Unsupported AST ${ast._tag}`,path);case"Null":return same((fc)=>fc.constant(null));case"Void":case"Undefined":return same((fc)=>fc.constant(undefined));case"Unknown":case"Any":return same((fc)=>fc.anything());case"String":return same((fc,ctx)=>{const constraint=ctx.constraint;const patterns=constraint?.patterns;return patterns?fc.oneof(...patterns.map((pattern)=>fc.stringMatching(new RegExp(pattern)))):fc.string(lengthToFastCheckConstraints(constraint))});case"Number":return same((fc,ctx)=>{const constraint=ctx.constraint;const ordered=constraint?.ordered?.order===Number2?constraint.ordered:undefined;return constraint?.integer?fc.integer(toIntegerConstraints(ordered)):fc.float(toFloatConstraints(constraint,ordered))});case"Boolean":return same((fc)=>fc.boolean());case"BigInt":return same((fc,ctx)=>{const ordered=ctx.constraint?.ordered?.order===BigInt2?ctx.constraint.ordered:undefined;return fc.bigInt(toBigIntConstraints(ordered))});case"Symbol":return same((fc)=>fc.string().map(Symbol.for));case"Literal":return same((fc)=>fc.constant(ast.literal));case"UniqueSymbol":return same((fc)=>fc.constant(ast.symbol));case"ObjectKeyword":return same((fc)=>fc.oneof(fc.object(),fc.array(fc.anything())));case"Enum":return recur(enumsToLiterals(ast),path);case"TemplateLiteral":{const parts=ast.parts.map((part,i)=>recur(toEncoded(part),[...path,i]));return same((fc,ctx,recursionStack)=>fc.tuple(...parts.map((part)=>part(fc,finiteNumberContext(ctx),recursionStack))).map((segments)=>segments.map((segment)=>globalThis.String(segment)).join("")))}case"Arrays":{const elements=ast.elements.map((ast2,i)=>({ast:ast2,arbitrary:recur(ast2,[...path,i])}));const len=ast.elements.length;const rest=ast.rest.map((ast2,i)=>({ast:ast2,arbitrary:recur(ast2,[...path,len+i])}));const terminal=(fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const elementArbitraries=[];const optionals=[];let length=0;for(const element of elements){const out2=element.arbitrary.terminal(fc,reset,recursionStack);if(isOptional(element.ast)){optionals.push(out2);continue}if(out2===undefined){return}length++;elementArbitraries.push(out2.map(some2))}const minLength=ctx.constraint?.minLength??0;const needsRest=isReadonlyArrayNonEmpty(rest)&&minLength>length+optionals.length;const optionalTarget=needsRest?optionals.length:Math.max(0,minLength-length);let includedOptionals=0;for(const out2 of optionals){if(includedOptionals>=optionalTarget||out2===undefined){elementArbitraries.push(fc.constant(none2()));continue}includedOptionals++;length++;elementArbitraries.push(out2.map(some2))}if(includedOptionals<optionalTarget){return}let out=fc.tuple(...elementArbitraries).map(getSomes);if(isReadonlyArrayNonEmpty(rest)){const[head,...tail]=rest;const restCtx=ast.elements.length===0?ctx:reset;const minRestLength=Math.max(0,minLength-length-tail.length);const headArbitrary=minRestLength===0?undefined:head.arbitrary.terminal(fc,reset,recursionStack);if(minRestLength>0&&headArbitrary===undefined){return}const restArbitrary=minRestLength===0?fc.constant([]):array2(fc,{...restCtx,constraint:{...restCtx.constraint,minLength:minRestLength}},headArbitrary,true);out=appendArray(fc,out,len,restArbitrary);if(tail.length>0){const tailArbitraries=[];for(const element of tail){const out2=element.arbitrary.terminal(fc,reset,recursionStack);if(out2===undefined){return}tailArbitraries.push(out2)}const t=fc.tuple(...tailArbitraries);out=appendArray(fc,out,len,t)}}return out};return makeLazy((fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const elementArbitraries=elements.map(({ast:ast2,arbitrary})=>{const out2=arbitrary(fc,reset,recursionStack);return isOptional(ast2)?out2.chain((a)=>fc.boolean().map((b)=>b?some2(a):none2())):out2.map(some2)});let out=fc.tuple(...elementArbitraries).map(getSomes);if(isReadonlyArrayNonEmpty(rest)){const[head,...tail]=rest.map(({arbitrary})=>arbitrary(fc,reset,recursionStack));const restArbitrary=array2(fc,ast.elements.length===0?ctx:reset,head);out=appendArray(fc,out,len,restArbitrary);if(tail.length>0){const t=fc.tuple(...tail);out=appendArray(fc,out,len,t)}}if(ctx.recursion){const terminalOut=terminal(fc,ctx,recursionStack);if(terminalOut!==undefined){return fc.oneof(ctx.recursion,terminalOut,out)}}return out},terminal)}case"Objects":{const propertySignatures=ast.propertySignatures.map((ps)=>({ps,arbitrary:recur(ps.type,[...path,ps.name])}));const indexSignatures=ast.indexSignatures.map((is)=>({is,parameter:recur(is.parameter,path),type:recur(is.type,path)}));const terminal=(fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const pss={};const requiredKeys=[];const optionals=[];for(const{ps,arbitrary}of propertySignatures){const name=ps.name;const out2=arbitrary.terminal(fc,reset,recursionStack);if(isOptional(ps.type)){if(out2!==undefined){optionals.push([name,out2])}continue}if(out2===undefined){return}requiredKeys.push(name);pss[name]=out2}let optionalCount=Math.max(0,(ctx.constraint?.minLength??0)-requiredKeys.length);for(const[name,out2]of optionals){if(optionalCount===0){break}optionalCount--;requiredKeys.push(name);pss[name]=out2}if(optionalCount>0&&ast.indexSignatures.length===0){return}let out=fc.record(pss,{requiredKeys});const entriesConstraints=objectEntriesConstraints(ast,ctx.constraint,requiredKeys.length);const minEntries=entriesConstraints?.minLength??0;for(const{parameter,type}of indexSignatures){let entries3;if(minEntries===0){entries3=fc.constant([])}else{const key=parameter.terminal(fc,reset,recursionStack);const value3=type.terminal(fc,reset,recursionStack);if(key===undefined||value3===undefined){return}entries3=arrayWithConstraints(fc,fc.tuple(key,value3),{...entriesConstraints,maxLength:minEntries},entryComparator)}out=appendObjectEntries(out,entries3)}return out};return makeLazy((fc,ctx,recursionStack)=>{const reset=resetContext(ctx);const pss={};const orderedNames=[];const requiredKeys=[];const optionalNames=[];for(const{ps,arbitrary}of propertySignatures){const name=ps.name;orderedNames.push(name);if(isOptional(ps.type)){optionalNames.push(name)}else{requiredKeys.push(name)}pss[name]=arbitrary(fc,reset,recursionStack)}const constraint=ctx.constraint;if(optionalNames.length>0&&indexSignatures.length===0&&constraint!==undefined&&(constraint.minLength!==undefined||constraint.maxLength!==undefined)){return objectWithOptionalCount(fc,pss,orderedNames,requiredKeys,optionalNames,constraint)}let out=fc.record(pss,{requiredKeys});const entriesConstraints=objectEntriesConstraints(ast,ctx.constraint,requiredKeys.length);for(const{parameter,type}of indexSignatures){const entry=fc.tuple(parameter(fc,reset,recursionStack),type(fc,reset,recursionStack));const entries3=arrayWithConstraints(fc,entry,entriesConstraints,entryComparator);out=appendObjectEntries(out,entries3)}return out},terminal)}case"Union":{const types=ast.types.map((ast2)=>recur(ast2,path));const terminal=(fc,ctx,recursionStack)=>oneOf(fc,types.map((type)=>type.terminal(fc,ctx,recursionStack)).filter(isNotUndefined));return makeLazy((fc,ctx,recursionStack)=>{const arbitraries=types.map((type)=>type(fc,ctx,recursionStack));if(ctx.recursion){const terminalOut=terminal(fc,ctx,recursionStack);if(terminalOut!==undefined){return fc.oneof(ctx.recursion,terminalOut,...arbitraries)}}const out=oneOf(fc,arbitraries);if(out===undefined){throw arbitraryError("a union with no members")}return out},terminal)}case"Suspend":{const memo=arbitraryMemoMap.get(ast);if(memo)return memo;const get5=memoizeThunk(()=>recur(ast.thunk(),path));const out=makeLazy((fc,ctx,recursionStack)=>{const recursion=getSuspendRecursion(fc,ast);const nextCtx={...ctx,recursion};const nextStack=recursionStack.includes(ast)?recursionStack:[...recursionStack,ast];const terminal=get5().terminal(fc,nextCtx,nextStack);if(terminal===undefined){throw errorWithPath("Unable to derive an arbitrary for a recursive schema without a finite generation path",path)}return fc.oneof(recursion,terminal,fc.constant(null).chain(()=>get5()(fc,nextCtx,nextStack)))},(fc,ctx,recursionStack)=>{if(recursionStack.includes(ast)){return}const recursion=getSuspendRecursion(fc,ast);return get5().terminal(fc,{...ctx,recursion},[...recursionStack,ast])});arbitraryMemoMap.set(ast,out);return out}}}var toConstructorAST=memoize((ast)=>{switch(ast._tag){case"Declaration":{const getLink=ast.annotations?.[ClassTypeId];if(isFunction(getLink)){const link=getLink(ast.typeParameters);const to=toConstructorAST(link.to);return replaceEncoding(ast,to===link.to?[link]:[new Link(to,link.transformation)])}return ast}case"Objects":case"Arrays":return ast.recur((ast2)=>{const defaultValue=ast2.context?.defaultValue;if(defaultValue){const out=toConstructorAST(ast2);return replaceEncoding(out,out.encoding?[...out.encoding,...defaultValue]:defaultValue)}return toConstructorAST(ast2)});case"Suspend":return ast.recur(toConstructorAST);default:return ast}});function makeEffect(schema){const ast=toConstructorAST(toType(schema.ast));const parser=run2(ast);return(input,options)=>{return parser(input,options?.disableChecks?options?.parseOptions?{...options.parseOptions,disableChecks:true}:{disableChecks:true}:options?.parseOptions)}}function makeOption(schema){const parser=makeEffect(schema);return(input,options)=>{const exit3=runSyncExit2(parser(input,options));if(isSuccess4(exit3)){return some2(exit3.value)}getSchemaIssueOrThrow(exit3.cause,"Option adapter can only return none for schema issues");return none2()}}function make23(schema){const parser=makeEffect(schema);return(input,options)=>{const exit3=runSyncExit2(parser(input,options));if(isSuccess4(exit3)){return exit3.value}const issue=getSchemaIssueOrThrow(exit3.cause,"Constructor adapter can only throw schema issues");throw new Error(issue.toString(),{cause:issue})}}function is(schema){return _is(schema.ast)}function _is(ast){const parser=asExit(run2(toType(ast)));return(input)=>{const exit3=parser(input,defaultParseOptions);if(isSuccess4(exit3)){return true}getSchemaIssueOrThrow(exit3.cause,"Type guard adapter can only return false for schema issues");return false}}function _issue(ast){const parser=run2(ast);return(input,options)=>{const exit3=runSyncExit2(parser(input,options));if(isSuccess4(exit3)){return}return getSchemaIssueOrThrow(exit3.cause,"Issue adapter can only return schema issues")}}function asserts(schema,input){const parser=asExit(run2(toType(schema.ast)));const exit3=parser(input,defaultParseOptions);if(isFailure4(exit3)){const issue=getSchemaIssueOrThrow(exit3.cause,"Assertion adapter can only throw schema issues");throw new Error(issue.toString(),{cause:issue})}}function decodeUnknownEffect(schema,options){const parser=run2(schema.ast);return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}var decodeEffect=decodeUnknownEffect;function decodeUnknownExit(schema,options){return asExit(decodeUnknownEffect(schema,options))}function decodeUnknownOption(schema,options){return asOption(decodeUnknownEffect(schema,options))}var decodeOption=decodeUnknownOption;function decodeUnknownResult(schema,options){return asResult(decodeUnknownEffect(schema,options))}function decodeUnknownSync(schema,options){return asSync(decodeUnknownEffect(schema,options))}var decodeSync=decodeUnknownSync;function encodeUnknownEffect(schema,options){const parser=run2(flip3(schema.ast));return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}function encodeUnknownExit(schema,options){return asExit(encodeUnknownEffect(schema,options))}function encodeUnknownOption(schema,options){return asOption(encodeUnknownEffect(schema,options))}var encodeOption=encodeUnknownOption;function encodeUnknownResult(schema,options){return asResult(encodeUnknownEffect(schema,options))}function encodeUnknownSync(schema,options){return asSync(encodeUnknownEffect(schema,options))}var encodeSync=encodeUnknownSync;var mergeParseOptions=(options,overrideOptions)=>overrideOptions===undefined?options:{...options,...overrideOptions};function run2(ast){const parser=recur2(ast);return(input,options)=>flatMapEager2(parser(some2(input),options??defaultParseOptions),(oa)=>{if(oa._tag==="None"){return fail6(new InvalidValue(oa))}return succeed6(oa.value)})}function asExit(parser){return(input,options)=>runSyncExit2(parser(input,options))}function asOption(parser){const parserExit=asExit(parser);return(input,options)=>{const exit3=parserExit(input,options);if(isSuccess4(exit3)){return some2(exit3.value)}getSchemaIssueOrThrow(exit3.cause,"Option adapter can only return none for schema issues");return none2()}}function asResult(parser){const parserExit=asExit(parser);return(input,options)=>{const exit3=parserExit(input,options);if(isSuccess4(exit3)){return succeed2(exit3.value)}return fail2(getSchemaIssueOrThrow(exit3.cause,"Result adapter can only return schema issues"))}}function asSync(parser){const parserExit=asExit(parser);return(input,options)=>{const exit3=parserExit(input,options);if(isSuccess4(exit3)){return exit3.value}const issue=getSchemaIssueOrThrow(exit3.cause,"Sync adapter can only throw schema issues");throw new Error(issue.toString(),{cause:issue})}}function mapSchemaIssueEffect(self,f){return catchCause2(self,(cause)=>failCauseSync2(()=>map6(cause,f)))}var recur2=memoize((ast)=>{let parser;const checks=ast.checks;const encoding=ast.encoding;const links=encoding;const len=links?.length??0;const encodingChecks=ast.encodingChecks;const astOptions=(checks?checks[checks.length-1].annotations:ast.annotations)?.["parseOptions"];if(!ast.context&&!encoding&&!checks&&!encodingChecks){return(ou,options)=>{parser??=ast.getParser(recur2);if(astOptions){options={...options,...astOptions}}return parser(ou,options)}}const isStructural=isArrays(ast)||isObjects(ast)||isDeclaration(ast)&&ast.typeParameters.length>0;const structuralChecks=checks&&isStructural?checks.filter((check)=>check.annotations?.[STRUCTURAL_ANNOTATION_KEY]):undefined;return(ou,options)=>{if(astOptions){options={...options,...astOptions}}let srou;if(links){for(let i=len-1;i>=0;i--){const link=links[i];const to=link.to;const parser2=recur2(to);srou=srou?flatMapEager2(srou,(ou2)=>parser2(ou2,options)):parser2(ou,options);if(link.transformation._tag==="Transformation"){const getter=link.transformation.decode;srou=flatMapEager2(srou,(ou2)=>getter.run(ou2,options))}else{srou=link.transformation.decode(srou,options)}}srou=mapSchemaIssueEffect(srou,(issue)=>new Encoding(ast,ou,issue))}parser??=ast.getParser(recur2);const parseLocal=(localOu)=>{let sroa2=parser(localOu,options);if(encodingChecks&&!options?.disableChecks){sroa2=flatMapEager2(sroa2,(oa)=>{if(isSome2(localOu)&&isSome2(oa)){const issues=[];collectIssues(encodingChecks,localOu.value,issues,ast,options);if(isArrayNonEmpty2(issues)){return fail6(new Composite(ast,localOu,issues))}}return succeed6(oa)})}if(checks&&!options?.disableChecks){if(options?.errors==="all"&&structuralChecks&&structuralChecks.length>0&&isSome2(localOu)){sroa2=mapSchemaIssueEffect(sroa2,(issue)=>{const issues=[];collectIssues(structuralChecks,localOu.value,issues,ast,options);const out=isArrayNonEmpty2(issues)?issue._tag==="Composite"&&issue.ast===ast?new Composite(ast,issue.actual,[...issue.issues,...issues]):new Composite(ast,localOu,[issue,...issues]):issue;return out})}sroa2=flatMapEager2(sroa2,(oa)=>{if(isSome2(oa)){const value3=oa.value;const issues=[];collectIssues(checks,value3,issues,ast,options);if(isArrayNonEmpty2(issues)){return fail6(new Composite(ast,oa,issues))}}return succeed6(oa)})}return sroa2};const sroa=srou?flatMapEager2(srou,parseLocal):parseLocal(ou);return sroa}});var toEquivalence=memoize((ast)=>{return recur3(ast,[])});function recur3(ast,path){const annotation=resolve(ast)?.["toEquivalence"];if(annotation){return annotation(isDeclaration(ast)?ast.typeParameters.map((tp)=>recur3(tp,path)):[])}switch(ast._tag){case"Never":throw errorWithPath(`Unsupported AST ${ast._tag}`,path);case"Declaration":case"Null":case"Undefined":case"Void":case"Unknown":case"Any":case"String":case"Number":case"Boolean":case"BigInt":case"Symbol":case"Literal":case"UniqueSymbol":case"ObjectKeyword":case"Enum":case"TemplateLiteral":return equals;case"Arrays":{const elements=ast.elements.map((e,i)=>recur3(e,[...path,i]));const len=ast.elements.length;const rest=ast.rest.map((r,i)=>recur3(r,[...path,len+i]));return make3((a,b)=>{if(!Array.isArray(a)||!Array.isArray(b)){return false}const len2=a.length;if(len2!==b.length){return false}let i=0;for(;i<Math.min(len2,ast.elements.length);i++){if(!elements[i](a[i],b[i])){return false}}if(rest.length>0){const[head,...tail]=rest;for(;i<len2-tail.length;i++){if(!head(a[i],b[i])){return false}}for(let j=0;j<tail.length;j++){if(!tail[j](a[i+j],b[i+j])){return false}}}return true})}case"Objects":{if(ast.propertySignatures.length===0&&ast.indexSignatures.length===0){return equals}const propertySignatures=ast.propertySignatures.map((ps)=>recur3(ps.type,[...path,ps.name]));const indexSignatures=ast.indexSignatures.map((is2)=>recur3(is2.type,path));return make3((a,b)=>{if(!isObject(a)||!isObject(b)){return false}for(let i=0;i<propertySignatures.length;i++){const ps=ast.propertySignatures[i];const name=ps.name;const aHas=Object.hasOwn(a,name);const bHas=Object.hasOwn(b,name);if(isOptional(ps.type)){if(aHas!==bHas){return false}}if(aHas&&bHas&&!propertySignatures[i](a[name],b[name])){return false}}for(let i=0;i<indexSignatures.length;i++){const is2=ast.indexSignatures[i];const aKeys=getIndexSignatureKeys(a,is2.parameter);const bKeys=getIndexSignatureKeys(b,is2.parameter);if(aKeys.length!==bKeys.length)return false;for(let j=0;j<aKeys.length;j++){const key=aKeys[j];if(!Object.hasOwn(b,key)||!indexSignatures[i](a[key],b[key])){return false}}}return true})}case"Union":return make3((a,b)=>{const candidates=getCandidates(a,ast.types);const types=candidates.map(_is);for(let i=0;i<candidates.length;i++){const is2=types[i];if(is2(a)&&is2(b)){return recur3(candidates[i],path)(a,b)}}return false});case"Suspend":{const get5=memoizeThunk(()=>recur3(ast.thunk(),path));return make3((a,b)=>get5()(a,b))}}}function escapeToken(token){return token.replace(/~/g,"~0").replace(/\//g,"~1")}function unescapeToken(token){return token.replace(/~1/g,"/").replace(/~0/g,"~")}var RegExp2=globalThis.RegExp;var escape=(string3)=>string3.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var TypeId30="~effect/SchemaError/SchemaError";class SchemaError extends TaggedError2("SchemaError"){[TypeId30]=TypeId30;constructor(issue){super({issue})}get message(){return this.issue.toString()}toString(){return`SchemaError(${this.message})`}}function isSchemaError(u){return hasProperty(u,TypeId30)}var TypeId31="~effect/Schema/Schema";var SchemaProto={[TypeId31]:TypeId31,pipe(){return pipeArguments(this,arguments)},annotate(annotations){return this.rebuild(annotate(this.ast,annotations))},annotateKey(annotations){return this.rebuild(annotateKey(this.ast,annotations))},check(...checks){return this.rebuild(appendChecks(this.ast,checks))}};function make24(ast,options){const self=Object.create(SchemaProto);if(options){Object.assign(self,options)}self.ast=ast;self.rebuild=(ast2)=>make24(ast2,options);const makeEffect2=makeEffect(self);self.makeEffect=(input,options2)=>fromIssueEffect(makeEffect2(input,options2));self.make=make23(self);self.makeOption=makeOption(self);return self}function fromIssueEffect(self){return catchCause2(self,(cause)=>failCauseSync2(()=>map6(cause,(issue)=>new SchemaError(issue))))}var jsonReorder=makeReorder(getJsonPriority);function getJsonPriority(ast){switch(ast._tag){case"BigInt":case"Symbol":case"UniqueSymbol":return 0;default:return 1}}function makeReorder(getPriority){return(types)=>{const indexMap=new Map;for(let i=0;i<types.length;i++){indexMap.set(toEncoded(types[i]),i)}const sortedTypes=[...types].sort((a,b)=>{a=toEncoded(a);b=toEncoded(b);const pa=getPriority(a);const pb=getPriority(b);if(pa!==pb)return pa-pb;return indexMap.get(a)-indexMap.get(b)});const orderChanged=sortedTypes.some((ast,index2)=>ast!==types[index2]);if(!orderChanged)return types;return sortedTypes}}function fromAST(ast){const{references,representations:schemas}=fromASTs([ast]);return{representation:schemas[0],references}}function fromASTs(asts){const references={};const referenceMap=new Map;const uniqueReferences=new Set;const visiting=new Set;const schemas=map4(asts,(ast)=>recur4(ast));return{representations:schemas,references};function gen3(prefix){let candidate=prefix;let suffix=0;while(uniqueReferences.has(candidate)){candidate=`${prefix}${++suffix}`}uniqueReferences.add(candidate);return candidate}function recur4(ast,prefix){const found=referenceMap.get(ast);if(found!==undefined){return{_tag:"Reference",$ref:found}}const last=getLastEncoding(ast);const identifier2=resolveIdentifier(ast)??prefix;if(ast!==last){return recur4(last,identifier2)}if(identifier2!==undefined){const reference=gen3(identifier2);referenceMap.set(ast,reference);const out2=on(ast);const found2=references[identifier2];if(found2!==undefined&&equals(out2,found2)){referenceMap.set(ast,identifier2);return{_tag:"Reference",$ref:identifier2}}references[reference]=out2;return{_tag:"Reference",$ref:reference}}if(visiting.has(ast)){const reference=gen3(`${ast._tag}_`);referenceMap.set(ast,reference);return{_tag:"Reference",$ref:reference}}visiting.add(ast);const out=on(ast);visiting.delete(ast);const ref=referenceMap.get(ast);if(ref!==undefined){references[ref]=out;return{_tag:"Reference",$ref:ref}}return out}function getEncodedSchema(last){const getLink=last.annotations?.toCodecJson??last.annotations?.toCodec;if(isFunction(getLink)){return replaceEncoding(last,[getLink(last.typeParameters.map((tp)=>make24(toEncoded(tp))))])}return null_}function on(last){const annotations=fromASTAnnotations(last.annotations);switch(last._tag){case"Declaration":{const encodedSchema=recur4(getEncodedSchema(last));return{_tag:"Declaration",typeParameters:last.typeParameters.map((ast)=>recur4(ast)),encodedSchema,checks:fromASTChecks(last.checks),...annotations}}case"Null":case"Undefined":case"Void":case"Never":case"Unknown":case"Any":case"Boolean":case"Symbol":case"ObjectKeyword":return{_tag:last._tag,...annotations};case"String":{const contentMediaType=last.annotations?.contentMediaType;const contentSchema=last.annotations?.contentSchema;return{_tag:last._tag,checks:fromASTChecks(last.checks),...annotations,...typeof contentMediaType==="string"&&isAST(contentSchema)?{contentSchema:recur4(contentSchema)}:undefined}}case"Number":case"BigInt":return{_tag:last._tag,checks:fromASTChecks(last.checks),...annotations};case"Literal":return{_tag:last._tag,literal:last.literal,...annotations};case"UniqueSymbol":return{_tag:last._tag,symbol:last.symbol,...annotations};case"Enum":return{_tag:last._tag,enums:last.enums,...annotations};case"TemplateLiteral":return{_tag:last._tag,parts:last.parts.map((ast)=>recur4(ast)),...annotations};case"Arrays":return{_tag:last._tag,elements:last.elements.map((e)=>{const last2=getLastEncoding(e);return{isOptional:isOptional(last2),type:recur4(e),...fromASTAnnotations(last2.context?.annotations)}}),rest:last.rest.map((ast)=>recur4(ast)),checks:fromASTChecks(last.checks),...annotations};case"Objects":return{_tag:last._tag,propertySignatures:last.propertySignatures.map((ps)=>{const last2=getLastEncoding(ps.type);return{name:ps.name,type:recur4(ps.type),isOptional:isOptional(last2),isMutable:isMutable(last2),...fromASTAnnotations(last2.context?.annotations)}}),indexSignatures:last.indexSignatures.map((is2)=>({parameter:recur4(is2.parameter),type:recur4(is2.type)})),checks:fromASTChecks(last.checks),...annotations};case"Union":{const types=jsonReorder(last.types);return{_tag:last._tag,types:types.map((ast)=>recur4(ast)),mode:last.mode,...annotations}}case"Suspend":{return{_tag:"Suspend",checks:[],thunk:recur4(last.thunk()),...annotations}}}}function fromASTChecks(checks){if(!checks)return[];return checks.map(getCheck).filter((c)=>c!==undefined);function getCheck(c){switch(c._tag){case"Filter":{const meta=c.annotations?.meta;if(meta){return{_tag:"Filter",meta:meta._tag==="isPropertyNames"?{_tag:"isPropertyNames",propertyNames:recur4(meta.propertyNames)}:meta,...fromASTAnnotations(c.annotations)}}return}case"FilterGroup":{const checks2=fromASTChecks(c.checks);if(isArrayNonEmpty2(checks2)){return{_tag:"FilterGroup",checks:checks2,...fromASTAnnotations(c.annotations)}}}}}}}var fromASTBlacklist=new Set(["~structural","~sentinels","meta","arbitrary","toArbitrary","toEquivalence","toFormatter","toCodec","toCodecJson","toCodecIso",ClassTypeId]);var standardJsonSchemaAnnotationKeys=new Set(["title","description","default","examples","readOnly","writeOnly","format","contentEncoding","contentMediaType","contentSchema"]);function fromASTAnnotations(annotations){if(annotations!==undefined){const filtered=filter3(annotations,(_,k)=>!fromASTBlacklist.has(k));if(!isEmptyRecord(filtered)){return{annotations:filtered}}}return}function toJsonSchemaDocument(document,options){const{definitions,dialect:source,schemas}=toJsonSchemaMultiDocument({representations:[document.representation],references:document.references},options);const schema=schemas[0];return{dialect:source,schema,definitions}}function toJsonSchemaMultiDocument(multiDocument,options){const generateDescriptions=options?.generateDescriptions??false;const additionalProperties=options?.additionalProperties??false;const includeAnnotationKey=options?.includeAnnotationKey;const definitions=map3(multiDocument.references,(d)=>recur4(d));return{dialect:"draft-2020-12",schemas:map4(multiDocument.representations,(s)=>recur4(s)),definitions};function recur4(s){let js=on(s);if("annotations"in s){const a=collectJsonSchemaAnnotations(s.annotations);if(a){js={...js,...a}}}if("checks"in s){const checks=collectJsonSchemaChecks(s.checks,js.type);for(const check of checks){js=appendJsonSchema(js,check)}}return js}function on(schema){switch(schema._tag){case"Any":case"Unknown":return{};case"ObjectKeyword":return{anyOf:[{type:"object"},{type:"array"}]};case"Void":case"Undefined":return{type:"null"};case"BigInt":return{type:"string",allOf:[{pattern:"^-?\\d+$"}]};case"Symbol":case"UniqueSymbol":return{type:"string",allOf:[{pattern:"^Symbol\\((.*)\\)$"}]};case"Declaration":return recur4(schema.encodedSchema);case"Suspend":return recur4(schema.thunk);case"Reference":return{$ref:`#/$defs/${escapeToken(schema.$ref)}`};case"Null":return{type:"null"};case"Never":return{not:{}};case"String":{const out={type:"string"};if(schema.contentMediaType!==undefined){out.contentMediaType=schema.contentMediaType}if(schema.contentSchema!==undefined){out.contentSchema=recur4(schema.contentSchema)}return out}case"Number":return hasCheck2(schema.checks,"isInt")?{type:"integer"}:hasCheck2(schema.checks,"isFinite")?{type:"number"}:{anyOf:[{type:"number"},{type:"string",enum:["NaN"]},{type:"string",enum:["Infinity"]},{type:"string",enum:["-Infinity"]}]};case"Boolean":return{type:"boolean"};case"Literal":{const literal=schema.literal;if(typeof literal==="string"){return{type:"string",enum:[literal]}}if(typeof literal==="number"){return{type:"number",enum:[literal]}}if(typeof literal==="boolean"){return{type:"boolean",enum:[literal]}}return{type:"string",enum:[String(literal)]}}case"Enum":{return recur4({_tag:"Union",types:schema.enums.map(([title,value3])=>({_tag:"Literal",literal:value3,annotations:{title}})),mode:"anyOf",annotations:schema.annotations})}case"TemplateLiteral":{const pattern=schema.parts.map(getPartPattern).join("");return{type:"string",pattern:`^${pattern}$`}}case"Arrays":{if(schema.rest.length>1){throw new globalThis.Error("Generating a JSON Schema for post-rest elements is not supported")}const out={type:"array"};let minItems=schema.elements.length;const prefixItems=schema.elements.map((e)=>{if(e.isOptional){minItems--}const v=recur4(e.type);const a=collectJsonSchemaAnnotations(e.annotations);return a?appendJsonSchema(v,a):v});if(prefixItems.length>0){out.prefixItems=prefixItems;out.maxItems=schema.elements.length;if(minItems>0){out.minItems=minItems}}else{out.items=false}if(schema.rest.length>0){delete out.maxItems;const rest=recur4(schema.rest[0]);if(Object.keys(rest).length>0){out.items=rest}else{delete out.items}}return out}case"Objects":{if(schema.propertySignatures.length===0&&schema.indexSignatures.length===0){return{anyOf:[{type:"object"},{type:"array"}]}}const out={type:"object"};const properties={};const required=[];for(const ps of schema.propertySignatures){const name=ps.name;if(typeof name!=="string"){throw new globalThis.Error(`Unsupported property signature name: ${format(name)}`)}const v=recur4(ps.type);const a=collectJsonSchemaAnnotations(ps.annotations);properties[name]=a?appendJsonSchema(v,a):v;if(!ps.isOptional){required.push(name)}}if(Object.keys(properties).length>0){out.properties=properties}if(required.length>0){out.required=required}out.additionalProperties=additionalProperties;const patternProperties={};for(const is2 of schema.indexSignatures){let type=recur4(is2.type);if(Object.keys(type).length===1&&"not"in type){type=false}const patterns=getParameterPatterns(is2.parameter);if(patterns.length>0){for(const pattern of patterns){patternProperties[pattern]=type}}else{out.additionalProperties=type}}if(Object.keys(patternProperties).length>0){out.patternProperties=patternProperties;delete out.additionalProperties}if(isObject(out.additionalProperties)&&isEmptyRecord(out.additionalProperties)){delete out.additionalProperties}return out}case"Union":{const types=schema.types.map(recur4);if(types.length===0){return{not:{}}}if(types.length>1){const compacted=compactEnums(types);if(compacted)return compacted}return schema.mode==="anyOf"?{anyOf:types}:{oneOf:types}}}}function compactEnums(types){let sharedType;const values3=[];for(const t of types){const keys3=Object.keys(t);if(keys3.length!==2||t.type===undefined||!Array.isArray(t.enum)||t.enum.length===0){return}if(sharedType===undefined){sharedType=t.type}else if(t.type!==sharedType){return}for(const v of t.enum){values3.push(v)}}return{type:sharedType,enum:values3}}function collectJsonSchemaAnnotations(annotations){if(annotations===undefined)return;const out={};if(typeof annotations.title==="string")out.title=annotations.title;if(typeof annotations.description==="string")out.description=annotations.description;else if(generateDescriptions&&typeof annotations.expected==="string")out.description=annotations.expected;if(annotations.default!==undefined)out.default=annotations.default;if(Array.isArray(annotations.examples))out.examples=annotations.examples;if(typeof annotations.readOnly==="boolean")out.readOnly=annotations.readOnly;if(typeof annotations.writeOnly==="boolean")out.writeOnly=annotations.writeOnly;if(typeof annotations.format==="string")out.format=annotations.format;if(typeof annotations.contentEncoding==="string")out.contentEncoding=annotations.contentEncoding;if(typeof annotations.contentMediaType==="string")out.contentMediaType=annotations.contentMediaType;if(includeAnnotationKey){for(const[key,value3]of Object.entries(annotations)){if(value3===undefined)continue;if(standardJsonSchemaAnnotationKeys.has(key))continue;if(!includeAnnotationKey(key))continue;out[key]=value3}}if(Object.keys(out).length>0)return out}function collectJsonSchemaChecks(checks,type){return checks.map(collectJsonSchemaCheck).filter((c)=>c!==undefined);function collectJsonSchemaCheck(check){switch(check._tag){case"Filter":return filterToJsonSchema(check,type);case"FilterGroup":{const checks2=check.checks.map(collectJsonSchemaCheck).filter((c)=>c!==undefined);if(checks2.length===0)return;let out={allOf:checks2};const a=collectJsonSchemaAnnotations(check.annotations);if(a){out={...out,...a}}return out}}}}function filterToJsonSchema(filter10,type){const meta=filter10.meta;if(!meta)return;let out=on2(meta);const a=collectJsonSchemaAnnotations(filter10.annotations);if(a){out={...out,...a}}return out;function on2(meta2){switch(meta2._tag){case"isMinLength":return type==="array"?{minItems:meta2.minLength}:{minLength:meta2.minLength};case"isMaxLength":return type==="array"?{maxItems:meta2.maxLength}:{maxLength:meta2.maxLength};case"isLengthBetween":return type==="array"?{allOf:[{minItems:meta2.minimum},{maxItems:meta2.maximum}]}:{allOf:[{minLength:meta2.minimum},{maxLength:meta2.maximum}]};case"isPattern":case"isGUID":case"isULID":case"isBase64":case"isBase64Url":case"isStartsWith":case"isEndsWith":case"isIncludes":case"isUppercased":case"isLowercased":case"isCapitalized":case"isUncapitalized":case"isTrimmed":case"isStringFinite":case"isStringBigInt":case"isStringSymbol":return{pattern:meta2.regExp.source};case"isUUID":return{pattern:meta2.regExp.source,format:"uuid"};case"isFinite":case"isInt":return;case"isMultipleOf":return{multipleOf:meta2.divisor};case"isGreaterThanOrEqualTo":return{minimum:meta2.minimum};case"isLessThanOrEqualTo":return{maximum:meta2.maximum};case"isGreaterThan":return{exclusiveMinimum:meta2.exclusiveMinimum};case"isLessThan":return{exclusiveMaximum:meta2.exclusiveMaximum};case"isBetween":{return{[meta2.exclusiveMinimum?"exclusiveMinimum":"minimum"]:meta2.minimum,[meta2.exclusiveMaximum?"exclusiveMaximum":"maximum"]:meta2.maximum}}case"isUnique":return{uniqueItems:true};case"isMinProperties":return{minProperties:meta2.minProperties};case"isMaxProperties":return{maxProperties:meta2.maxProperties};case"isPropertiesLengthBetween":return{minProperties:meta2.minimum,maxProperties:meta2.maximum};case"isPropertyNames":return{propertyNames:recur4(meta2.propertyNames)};case"isDateValid":return{format:"date-time"}}}}function getParameterPatterns(parameter){switch(parameter._tag){default:throw new globalThis.Error(`Unsupported index signature parameter: ${parameter._tag}`);case"Reference":return getParameterPatterns(multiDocument.references[parameter.$ref]);case"String":return getPatterns(parameter);case"TemplateLiteral":return[`^${parameter.parts.map(getPartPattern).join("")}$`];case"Union":return parameter.types.flatMap(getParameterPatterns)}}}function getPatterns(s){return recur4(s.checks);function recur4(checks){return checks.flatMap((c)=>{switch(c._tag){case"Filter":{if("regExp"in c.meta){return[c.meta.regExp.source]}return[]}case"FilterGroup":return recur4(c.checks)}})}}function hasCheck2(checks,tag){return checks.some((c)=>{switch(c._tag){case"Filter":return c.meta._tag===tag;case"FilterGroup":return hasCheck2(c.checks,tag)}})}function appendJsonSchema(a,b){if(Object.keys(a).length===0)return b;const len=Object.keys(b).length;if(len===0)return a;const members=Array.isArray(b.allOf)&&len===1?b.allOf:[b];if(Array.isArray(a.allOf)){return{...a,allOf:[...a.allOf,...members]}}if(typeof a.$ref==="string"){return{allOf:[a,...members]}}return{...a,allOf:members}}function getPartPattern(part){switch(part._tag){case"Literal":return escape(globalThis.String(part.literal));case"String":return STRING_PATTERN;case"Number":return FINITE_PATTERN;case"TemplateLiteral":return part.parts.map(getPartPattern).join("");case"Union":return part.types.map(getPartPattern).join("|");default:throw new globalThis.Error("Unsupported part",{cause:part})}}function get5(oldValue,newValue){if(Object.is(oldValue,newValue))return[];const patches=[];if(Array.isArray(oldValue)&&Array.isArray(newValue)){const len1=oldValue.length;const len2=newValue.length;const shared=Math.min(len1,len2);for(let i=0;i<shared;i++){const path=`/${i}`;const patch=get5(oldValue[i],newValue[i]);for(const op of patch){prefixPathInPlace(op,path);patches.push(op)}}for(let i=len1-1;i>=len2;i--){patches.push({op:"remove",path:`/${i}`})}for(let i=len1;i<len2;i++){patches.push({op:"add",path:`/${i}`,value:newValue[i]})}return patches}if(isJsonObject(oldValue)&&isJsonObject(newValue)){const keys1=Object.keys(oldValue);const keys22=Object.keys(newValue);const allKeys=Array.from(new Set([...keys1,...keys22])).sort();for(const key of allKeys){const esc=escapeToken(key);const path=`/${esc}`;const hasKey1=Object.hasOwn(oldValue,key);const hasKey2=Object.hasOwn(newValue,key);if(hasKey1&&hasKey2){const patch=get5(oldValue[key],newValue[key]);for(const op of patch){prefixPathInPlace(op,path);patches.push(op)}}else if(!hasKey1&&hasKey2){patches.push({op:"add",path,value:newValue[key]})}else if(hasKey1&&!hasKey2){patches.push({op:"remove",path})}}return patches}patches.push({op:"replace",path:"",value:newValue});return patches}function apply(patch,oldValue){let doc=oldValue;for(const op of patch){switch(op.op){case"replace":{doc=op.path===""?op.value:setAt(doc,op.path,op.value,"replace");break}case"add":{doc=addAt(doc,op.path,op.value);break}case"remove":{doc=setAt(doc,op.path,undefined,"remove");break}}}return doc}function prefixPathInPlace(op,parent){op.path=op.path===""?parent:parent+op.path}function isJsonObject(value3){return isObject(value3)}function tokenize(pointer){if(pointer==="")return[];if(pointer.charCodeAt(0)!==47){throw new Error(`Invalid JSON Pointer, it must start with "/": ${format(pointer)}`)}return pointer.split("/").slice(1).map(unescapeToken)}function toIndex(token){if(!/^(0|[1-9]\d*)$/.test(token)){throw new Error(`Invalid array index: "${token}"`)}return Number(token)}function addAt(doc,pointer,val){if(pointer==="")return val;const resolved=resolveParent(doc,pointer);if(resolved===null){throw new Error(`Cannot add at "${pointer}" (parent not found or not a container).`)}const{lastToken,parent,stack}=resolved;if(Array.isArray(parent)){const idx=lastToken==="-"?parent.length:toIndex(lastToken);if(idx<0||idx>parent.length)throw new Error(`Array index out of bounds at "${pointer}".`);const updated=parent.slice();updated.splice(idx,0,val);return rebuildFromStack(stack,updated)}if(isJsonObject(parent)){const updated={...parent};updated[lastToken]=val;return rebuildFromStack(stack,updated)}throw new Error(`Cannot add at "${pointer}" (parent not found or not a container).`)}function setAt(doc,pointer,val,mode){if(pointer===""){if(mode==="remove"||val===undefined)throw new Error("Unsupported operation at the root");return val}const resolved=resolveParent(doc,pointer);if(resolved===null){throw new Error(`Cannot ${mode} at "${pointer}" (parent not found or not a container).`)}const{lastToken,parent,stack}=resolved;if(Array.isArray(parent)){if(lastToken==="-")throw new Error(`"-" is not valid for ${mode} at "${pointer}".`);const idx=toIndex(lastToken);if(idx<0||idx>=parent.length)throw new Error(`Array index out of bounds at "${pointer}".`);const updated=parent.slice();if(mode==="remove")updated.splice(idx,1);else updated[idx]=val;return rebuildFromStack(stack,updated)}if(isJsonObject(parent)){if(!Object.hasOwn(parent,lastToken)){throw new Error(`Property "${lastToken}" does not exist at "${pointer}".`)}const updated={...parent};if(mode==="remove")delete updated[lastToken];else updated[lastToken]=val;return rebuildFromStack(stack,updated)}throw new Error(`Cannot ${mode} at "${pointer}" (parent not found or not a container).`)}function resolveParent(doc,pointer){const tokens=tokenize(pointer);if(tokens.length===0)return null;const lastToken=tokens[tokens.length-1];const stack=[];let cur=doc;for(let i=0;i<tokens.length-1;i++){const token=tokens[i];if(cur==null)return null;if(Array.isArray(cur)){const idx=toIndex(token);if(idx<0||idx>=cur.length)return null;stack.push({container:cur,token:idx});cur=cur[idx];continue}if(cur&&typeof cur==="object"){if(!Object.hasOwn(cur,token))return null;stack.push({container:cur,token});cur=cur[token];continue}return null}return{stack,parent:cur,lastToken}}function rebuildFromStack(stack,newParent){let acc=newParent;for(let i=stack.length-1;i>=0;i--){const{container,token}=stack[i];if(Array.isArray(container)){const copy2=container.slice();copy2[token]=acc;acc=copy2}else{const copy2={...container};copy2[token]=acc;acc=copy2}}return acc}var RE_DEFS=/^#\/\$defs(?=\/|$)/;function toDocumentDraft07(document){return{dialect:"draft-07",schema:toSchemaDraft07(document.schema),definitions:map3(document.definitions,toSchemaDraft07)}}function toSchemaDraft07(schema){return rewrite(schema);function rewrite(node){return walk(rewrite_refs(node,(ref)=>ref.replace(RE_DEFS,"#/definitions")),true)}function walk(node,_isRoot){if(Array.isArray(node))return node.map((v)=>walk(v,false));if(!isObject(node))return node;const src=node;const out={};let prefixItems=undefined;let items=undefined;for(const k of Object.keys(src)){const v=src[k];switch(k){case"$ref":case"type":case"required":case"enum":case"const":case"title":case"description":case"default":case"examples":case"format":case"pattern":case"minimum":case"maximum":case"exclusiveMinimum":case"exclusiveMaximum":case"minLength":case"maxLength":case"minItems":case"maxItems":case"minProperties":case"maxProperties":case"multipleOf":case"uniqueItems":out[k]=v;break;case"properties":case"patternProperties":{const mapped=walk_object(v,walk);out[k]=mapped??v;break}case"additionalProperties":case"propertyNames":out[k]=walk(v,false);break;case"allOf":case"anyOf":case"oneOf":out[k]=Array.isArray(v)?v.map((x)=>walk(x,false)):v;break;case"prefixItems":prefixItems=v;break;case"items":items=v;break;default:break}}if(prefixItems!==undefined){if(Array.isArray(prefixItems)){out.items=prefixItems.map((x)=>walk(x,false));if(items!==undefined)out.additionalItems=walk(items,false)}else{out.items=walk(prefixItems,false)}}else if(items!==undefined){out.items=walk(items,false)}return out}}function toMultiDocumentOpenApi3_1(multiDocument){const keyMap2=new Map;for(const key of Object.keys(multiDocument.definitions)){const sanitized=sanitizeOpenApiComponentsSchemasKey(key);if(sanitized!==key){keyMap2.set(key,sanitized)}}function rewrite(schema){return rewrite_refs(schema,($ref)=>{const tokens=$ref.split("/");if(tokens.length>0){const identifier2=unescapeToken(tokens[tokens.length-1]);const sanitized=keyMap2.get(identifier2);if(sanitized!==undefined){$ref=tokens.slice(0,-1).join("/")+"/"+sanitized}}return $ref.replace(RE_DEFS,"#/components/schemas")})}return{dialect:"openapi-3.1",schemas:map4(multiDocument.schemas,rewrite),definitions:mapEntries(multiDocument.definitions,(definition,key)=>[keyMap2.get(key)??key,rewrite(definition)])}}var VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP=/^[a-zA-Z0-9.\-_]+$/;function sanitizeOpenApiComponentsSchemasKey(s){if(s.length===0)return"_";if(VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP.test(s))return s;const out=[];for(const ch of s){const code=ch.codePointAt(0);if(code!==undefined&&(code>=48&&code<=57||code>=65&&code<=90||code>=97&&code<=122||code===46||code===45||code===95)){out.push(ch)}else{out.push("_")}}return out.join("")}function rewrite_refs(node,f){if(Array.isArray(node))return node.map((v)=>rewrite_refs(v,f));if(!isObject(node))return node;const out={};for(const k of Object.keys(node)){const v=node[k];if(k==="$ref"){out[k]=typeof v==="string"?f(v):v}else if(Array.isArray(v)||isObject(v)){out[k]=rewrite_refs(v,f)}else{out[k]=v}}return out}function walk_object(value3,walk){if(!isObject(value3))return;const out={};for(const k of Object.keys(value3))out[k]=walk(value3[k],false);return out}function makeIso(get6,set3){return make25(new IsoNode(get6,set3))}function makeLens(get6,replace){return make25(new LensNode(get6,replace))}class IdentityNode{_tag="IdentityNode"}var identityNode=new IdentityNode;class CompositionNode{_tag="CompositionNode";nodes;constructor(nodes){this.nodes=nodes}}class IsoNode{_tag="IsoNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class LensNode{_tag="LensNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class PrismNode{_tag="PrismNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class OptionalNode{_tag="OptionalNode";get;set;constructor(get6,set3){this.get=get6;this.set=set3}}class PathNode{_tag="PathNode";path;constructor(path){this.path=path}}class CheckNode{_tag="CheckNode";checks;constructor(checks){this.checks=checks}}function pushNormalized(acc,node){const last=acc[acc.length-1];if(last){if(last._tag==="PathNode"&&node._tag==="PathNode"){acc[acc.length-1]=new PathNode([...last.path,...node.path]);return}if(last._tag==="CheckNode"&&node._tag==="CheckNode"){acc[acc.length-1]=new CheckNode([...last.checks,...node.checks]);return}}acc.push(node)}function collect(node,acc){if(node._tag==="IdentityNode")return;if(node._tag==="CompositionNode"){for(let i=0;i<node.nodes.length;i++)collect(node.nodes[i],acc);return}pushNormalized(acc,node)}function compose(a,b){const nodes=[];collect(a,nodes);collect(b,nodes);switch(nodes.length){case 0:return identityNode;case 1:return nodes[0];default:return new CompositionNode(nodes)}}function makeOptional(getResult,set3){return make25(new OptionalNode(getResult,set3))}class OptionalImpl{node;getResult;replaceResult;constructor(node,getResult,replaceResult){this.node=node;this.getResult=getResult;this.replaceResult=replaceResult}replace(a,s){return getOrElse3(this.replaceResult(a,s),()=>s)}modify(f){return(s)=>getOrElse3(flatMap2(this.getResult(s),(a)=>this.replaceResult(f(a),s)),()=>s)}compose(that){return make25(compose(this.node,that.node))}key(key){return make25(compose(this.node,new PathNode([key])))}optionalKey(key){return make25(compose(this.node,new LensNode((s)=>s[key],(a,s)=>{const copy2=cloneShallow(s);if(a===undefined){if(Array.isArray(copy2)&&typeof key==="number"){copy2.splice(key,1)}else{delete copy2[key]}}else{copy2[key]=a}return copy2})))}check(...checks){return make25(compose(this.node,new CheckNode(checks)))}refine(refinement,annotations){return make25(compose(this.node,new CheckNode([makeFilterByGuard(refinement,annotations)])))}tag(tag){return make25(compose(this.node,new PrismNode((s)=>s._tag===tag?succeed2(s):fail2(`Expected ${format(tag)} tag, got ${format(s._tag)}`),identity)))}at(key,..._rest){const err=fail2(`Key ${format(key)} not found`);return make25(compose(this.node,new OptionalNode((s)=>Object.hasOwn(s,key)?succeed2(s[key]):err,(a,s)=>{if(Object.hasOwn(s,key)){const copy2=cloneShallow(s);copy2[key]=a;return succeed2(copy2)}else{return err}})))}pick(keys3){return this.compose(makeLens(pick(keys3),(p,a)=>({...a,...p})))}omit(keys3){return this.compose(makeLens(omit2(keys3),(o,a)=>({...a,...o})))}notUndefined(){return this.refine(isNotUndefined,{expected:"a value other than `undefined`"})}forEach(f){const inner=f(id());return makeOptional((s)=>map2(this.getResult(s),(as3)=>{const bs=[];for(let i=0;i<as3.length;i++){const r=inner.getResult(as3[i]);if(isSuccess2(r))bs.push(r.success)}return bs}),(bs,s)=>flatMap2(this.getResult(s),(as3)=>{const idxs=[];for(let i=0;i<as3.length;i++){if(isSuccess2(inner.getResult(as3[i])))idxs.push(i)}if(bs.length!==idxs.length){return fail2(`each: replacement length mismatch: ${bs.length} !== ${idxs.length}`)}const out=as3.slice();for(let k=0;k<idxs.length;k++){const i=idxs[k];const r=inner.replaceResult(bs[k],as3[i]);if(isFailure2(r)){return fail2(`each: could not set element ${i}`)}out[i]=r.success}return this.replaceResult(out,s)}))}modifyAll(f){return(s)=>getOrElse3(flatMap2(this.getResult(s),(as3)=>this.replaceResult(as3.map(f),s)),()=>s)}}class IsoImpl extends OptionalImpl{get;set;constructor(node,get6,set3){super(node,(s)=>succeed2(get6(s)),(a)=>succeed2(set3(a)));this.get=get6;this.set=set3}replace(a,_){return this.set(a)}modify(f){return(s)=>this.set(f(this.get(s)))}}class LensImpl extends OptionalImpl{get;constructor(node,get6,replace){super(node,(s)=>succeed2(get6(s)),(a,s)=>succeed2(replace(a,s)));this.get=get6;this.replace=replace}modify(f){return(s)=>this.replace(f(this.get(s)),s)}}class PrismImpl extends OptionalImpl{set;constructor(node,getResult,set3){super(node,getResult,(a,_)=>succeed2(set3(a)));this.set=set3}replace(a,_){return this.set(a)}modify(f){return(s)=>getOrElse3(map2(this.getResult(s),(a)=>this.set(f(a))),()=>s)}}function make25(node){const op=recur4(node);switch(op._tag){case"IsoNode":return new IsoImpl(node,op.get,op.set);case"LensNode":return new LensImpl(node,op.get,op.set);case"PrismNode":return new PrismImpl(node,op.get,op.set);case"OptionalNode":return new OptionalImpl(node,op.get,op.set)}}function cloneShallow(pojo){if(Array.isArray(pojo))return pojo.slice();if(typeof pojo==="object"&&pojo!==null){const proto=Object.getPrototypeOf(pojo);if(proto!==Object.prototype&&proto!==null){throw new Error("Cannot clone object with non-Object constructor or null prototype")}return{...pojo}}return pojo}var recur4=memoize((node)=>{switch(node._tag){case"IdentityNode":return{_tag:"IsoNode",get:identity,set:identity};case"IsoNode":case"LensNode":case"PrismNode":case"OptionalNode":return{_tag:node._tag,get:node.get,set:node.set};case"PathNode":{return{_tag:"LensNode",get:(s)=>{const path=node.path;let out=s;for(let i=0,n=path.length;i<n;i++){out=out[path[i]]}return out},set:(a,s)=>{const path=node.path;const out=cloneShallow(s);let current=out;let i=0;for(;i<path.length-1;i++){const key=path[i];current[key]=cloneShallow(current[key]);current=current[key]}const finalKey=path[i];current[finalKey]=a;return out}}}case"CheckNode":return{_tag:"PrismNode",get:(s)=>mapError(runChecks(node.checks,s),String),set:identity};case"CompositionNode":{const ops=node.nodes.map(recur4);const _tag=ops.reduce((tag,op)=>getCompositionTag(tag,op._tag),"IsoNode");return{_tag,get:(s)=>{for(let i=0;i<ops.length;i++){const op=ops[i];const result3=op.get(s);if(hasFailingGet(op._tag)){if(isFailure2(result3)){return result3}s=result3.success}else{s=result3}}return hasFailingGet(_tag)?succeed2(s):s},set:(a,s)=>{const source=s;const len=ops.length;const ss=new Array(len+1);ss[0]=s;for(let i=0;i<len;i++){const op=ops[i];if(hasFailingGet(op._tag)){const result3=op.get(s);if(isFailure2(result3)){return _tag==="OptionalNode"?result3:source}s=result3.success}else{s=op.get(s)}ss[i+1]=s}for(let i=len-1;i>=0;i--){const op=ops[i];if(hasSet(op._tag)){a=op.set(a)}else if(op._tag==="LensNode"){a=op.set(a,ss[i])}else{const result3=op.set(a,ss[i]);if(isFailure2(result3)){return result3}a=result3.success}}return _tag==="OptionalNode"?succeed2(a):a}}}}});function hasFailingGet(tag){return tag==="PrismNode"||tag==="OptionalNode"}function hasSet(tag){return tag==="IsoNode"||tag==="PrismNode"}function getCompositionTag(a,b){switch(a){case"IsoNode":return b;case"LensNode":return hasFailingGet(b)?"OptionalNode":"LensNode";case"PrismNode":return hasSet(b)?"PrismNode":"OptionalNode";case"OptionalNode":return"OptionalNode"}}var identityIso=make25(identityNode);function id(){return identityIso}var exports_FastCheck={};__export(exports_FastCheck,{webUrl:()=>webUrl,webSegment:()=>webSegment,webQueryParameters:()=>webQueryParameters,webPath:()=>webPath,webFragments:()=>webFragments,webAuthority:()=>webAuthority,uuid:()=>uuid,uniqueArray:()=>uniqueArray,ulid:()=>ulid,uint8ClampedArray:()=>uint8ClampedArray,uint8Array:()=>uint8Array,uint32Array:()=>uint32Array,uint16Array:()=>uint16Array,tuple:()=>tuple2,toStringMethod:()=>toStringMethod,subarray:()=>subarray,stringify:()=>stringify,stringMatching:()=>stringMatching,string:()=>string3,stream:()=>stream,statistics:()=>statistics,sparseArray:()=>sparseArray,shuffledSubarray:()=>shuffledSubarray,set:()=>set3,schedulerFor:()=>schedulerFor,scheduler:()=>scheduler,scheduledModelRun:()=>scheduledModelRun,sample:()=>sample,resetConfigureGlobal:()=>resetConfigureGlobal,record:()=>record2,readConfigureGlobal:()=>readConfigureGlobal,property:()=>property,pre:()=>pre,option:()=>option3,oneof:()=>oneof,object:()=>object,noShrink:()=>noShrink,noBias:()=>noBias,nat:()=>nat,modelRun:()=>modelRun,mixedCase:()=>mixedCase,memo:()=>memo,maxSafeNat:()=>maxSafeNat,maxSafeInteger:()=>maxSafeInteger,mapToConstant:()=>mapToConstant,map:()=>map13,lorem:()=>lorem,limitShrink:()=>limitShrink,letrec:()=>letrec,jsonValue:()=>jsonValue,json:()=>json,ipV6:()=>ipV6,ipV4Extended:()=>ipV4Extended,ipV4:()=>ipV4,integer:()=>integer,int8Array:()=>int8Array,int32Array:()=>int32Array,int16Array:()=>int16Array,infiniteStream:()=>infiniteStream,hash:()=>hash2,hasToStringMethod:()=>hasToStringMethod,hasCloneMethod:()=>hasCloneMethod,hasAsyncToStringMethod:()=>hasAsyncToStringMethod,getDepthContextFor:()=>getDepthContextFor,gen:()=>gen3,func:()=>func,float64Array:()=>float64Array,float32Array:()=>float32Array,float:()=>float,falsy:()=>falsy,entityGraph:()=>entityGraph,emailAddress:()=>emailAddress,double:()=>double,domain:()=>domain,dictionary:()=>dictionary,defaultReportMessage:()=>defaultReportMessage,date:()=>date,createDepthIdentifier:()=>createDepthIdentifier,context:()=>context3,constantFrom:()=>constantFrom,constant:()=>constant2,configureGlobal:()=>configureGlobal,compareFunc:()=>compareFunc,compareBooleanFunc:()=>compareBooleanFunc,commands:()=>commands,cloneMethod:()=>cloneMethod,cloneIfNeeded:()=>cloneIfNeeded,clone:()=>clone,check:()=>check,chainUntil:()=>chainUntil,boolean:()=>boolean2,bigUint64Array:()=>bigUint64Array,bigInt64Array:()=>bigInt64Array,bigInt:()=>bigInt2,base64String:()=>base64String,asyncToStringMethod:()=>asyncToStringMethod,asyncStringify:()=>asyncStringify,asyncProperty:()=>asyncProperty,asyncModelRun:()=>asyncModelRun,asyncDefaultReportMessage:()=>asyncDefaultReportMessage,assert:()=>assert,array:()=>array3,anything:()=>anything,__version:()=>__version,__type:()=>__type,__commitHash:()=>__commitHash,VerbosityLevel:()=>VerbosityLevel,Value:()=>Value,Stream:()=>Stream,Random:()=>Random,PreconditionFailure:()=>PreconditionFailure,ExecutionStatus:()=>ExecutionStatus,Arbitrary:()=>Arbitrary});var MULTIPLIER=214013;var INCREMENT=2531011;var MASK=4294967295;var MASK_2=-2147483649;var MULTIPLIER_2=-1443076087;var INCREMENT_2=505908858;var MULTIPLIER_3=1170746341;var INCREMENT_3=-755606699;var JUMP_MULTIPLIER=1994129409;var JUMP_INCREMENT=916127744;var LinearCongruential32=class LinearCongruential322{constructor(seed){this.seed=seed}clone(){return new LinearCongruential322(this.seed)}next(){const s0=this.seed;const s1=Math.imul(s0,MULTIPLIER)+INCREMENT|0;const s2=Math.imul(s0,MULTIPLIER_2)+INCREMENT_2|0;const s3=Math.imul(s0,MULTIPLIER_3)+INCREMENT_3|0;this.seed=s3;const v1=(s1&MASK_2)>>16;const v2=(s2&MASK_2)>>16;return(s3&MASK_2)>>16|v2<<15|v1<<30}jump(){this.seed=Math.imul(this.seed,JUMP_MULTIPLIER)+JUMP_INCREMENT&MASK}getState(){return[this.seed]}};function congruential32(seed){return new LinearCongruential32(seed)}var N=624;var M=397;var A=2567483615;var F=1812433253;var U=11;var S=7;var B=2636928640;var T=15;var C=4022730752;var L=18;var MASK_LOWER=2147483647;var MASK_UPPER=2147483648;var JUMP_COEFS="SUSgbA\\W`E[]KN2RUSo8XVU?HKBFRl11E\\KoWOg5B]XEWG;BE;1:oVK[`B^Z9Qd23^XTnhL>]Unda4f[X;_j9H5QD=cN<5H`3bW>9bk1mjoI2fK0obmAAINOV:>Mek_V9dd<hZ\\gC3?Fm7FEk07QH_3PLm^@?^i\\QMkgP<]oLHmFnlecg5F@7U^@4jhZ?WZS0k@GHehmM36:5^9;>Hmm`co>k:KOSkSbIINb1VFf>LXgP>GUAQTD>Ci>XMGkUflLlb?_FaFUk@?5N7i70@;1o68ah@I<HFH7R2^J:G][Gf962ITWID9GWK8ElD2G5=DcHcL]cA]P2n7A=[<bInM;IHDQnJMReRXDWbVldnGEIPij`E08Xdci3@0c:IBbD4:Nk]?lEN9j^;T`0blZX7eiWE8c`<ak7j05FZi>AjUDh?M1B?^??FAXKThf<aBOXZf7jXYGK>R<;NHk3S9YhM7STJ6`:MIE`S@7298X8W>PNK=@;lLX<i\\TXLL<W@X[X54H]in8M;;n?kkQbajgAMY=Tf9b;ZKf0QUB2FHYWfnfkDoU9YkcLd95T>lK6GM1YL\\lid:J>KYS=iJ]Y>QlF>?R5_[5QeYC=66;A32Ac>OHk_ne^0g>bK:g;KFPgbGUcPR_Z=TX3H9d03bKZ2IhEPKBo>LSGWd0iFdV8C<Y:<>T[O6lC\\blaZ>GoAYP4clf^j1IfnZJ]QeDe2X<HE[LJNWnaCg[P]Co^:IRbWPY?97UePBlZNNHY6LOBM8P>=h?Ye:_f_Sb9Ki5GDYBF4dWeMfdg^ccPllNWM7G1\\UMdoYeOOD5^e@foA22G?ADYo5:FVG[bWo96;>3kc_c1Ab30>30;1@4F8g2hY?DJ4[LOL;ZLLKo2]jo>[KMDUcR279N_kF=3WL@Dd620bMTdA\\U9k``ef2iD9JgJ8CZBHS>F^Uk;<laeaeHS<15OSeS`PcSSKBRBFY]aQ=EgUXGNg=?d56`KA@2BejY0^[_DCX`L=CGMT=BW^6S1i@2ATBVk>3_ocRA>2U:4GPQ6o>5jX2HIcV3S@On6KB<[SKB?FC_AAji9agbBFkAi\\;4I\\UJ]c36Ub@[;gQACVGY<V]SDJBUU]La\\_a@JdOO8gm2T0DJMa:8Hf7>E]noQ[1Kambn??QQ]S?1i0oMGOijb\\aGY6lQ^CJ?9bFle8<eH4UUjBINX;n8@VOA5ah^URV49B[A?ONHhHAC1J5;;h0SXYlG^0W=eJdHh^K4SGe=1HZLLam;D<Q3AOdbPcdX``82\\jo0En8jRVGC73WMCF9`d:0heS?80?C188cSn7H9<daZ]MgS4Pb^1HkA:1PU^5>^h_g[RQV@PnYBRI_]`B]Bh@Uk03eXGY`I16L76H28X`R>IROMeNVUdU[:lghLhPCQZ:4a<30YBZCYnXe[?;jc8gKI2QH2MjnWBm4nGCZW`aVU2a;P<AMI25mlW_Nm][2?b6o851X@lAm]YZ`bWRF1g<Ga:T]1NXH5Veja5P9S9>:aNg:Th1Y=5o78K>LQ8hW@5S?I83Lk5Xk;j5@I3o[d:4RjE^oS30:WP9gC\\i8aSI>QRE@4lP:7lDg8g2`Ql[2I8aBU\\BQ?B4_clL9Q]S;^e1Ob5[>3JER2`c7B=o]fPOWO<DGi;Niba1PoWPPE_Q3aX0OB0mZej\\f_M[J4Y6]1`h2MkF[GiW8Q^d3^_=<I1N2Q7]2<2j[iP7V3V821FaI]A`93bC^Z\\G=WJ;^Ih?B97_iIF@\\Dl<eK1je8SNTWo_=XFMZH<<JYLZ^YQMPgYOV45K_:]kSI8^XlO0]GY=VUfe_C_F6TOcoAlVUH:o=WhhT@K`2KFhe<3\\KXQ>W:M?S_4S5d@J^`[AGA7@3]DnGSCO`\\?E8HT75^d9\\:m\\m1egIfk8cd6bD9\\eU8\\n[Pb0Cgd^S0n9kGJHb]i5XodlKHc34Fhi9K>0U5WK`>7Ff2^KL=WC6:kc?e5C^a1T1:4:^S5flXlGNIj08AfO?Dh7T7dWO>E]NI9?ob7B7P_h[4TEP[EU;GllFTnSmg9:\\[N]<SAoKP_kPlG56A:I3T6EG8Hj=XnUE`KT5U@OQ?]7[N^MFN1_NU4KO_3::Le`8IL9[1Z1H1;V3SC\\N3]S@4U[F2mhT5dYM7[4Pg_Na0_8WTH0`bgceQS8]EG;XgD4Ib4iLTP@kE79Mn>AYRJA1U5^Blhgno:aHVYc03c3J0Vc9FjEV^M75Zfd8kVC9>iJDk`AJ[6f7DK2D^DL\\AX:6b5h31XH;RQB\\N<ZSM=J;6L[`UW^eOIFc1Y]6_dfedIe4ARh72mTXC0WND_IDHVCZRDE0eODARCEETQI5TPUQE=jEH5bS?LP[ai`F5ABRYDo2o\\@=]GT?_9;hc4Lm:\\SF9k1T<0E@fX9BG[]g0nY7k[Qmi@la8`PF0j6@Q?Ii7bLkXQ<lLHf]`:DCh@9JY5>hEVLTdhL\\b1EB0lLh<=WaO@F<;8g<d:@e:LA:cFIEdmQh7hNHfSRToW?8N4:Z1K;XEDRO;OIDh<UdVln?bjgL>?VE98[B\\K<BVjkG8LiSX;fb>jf?DUK00Aih<WY6QD6cEnHBZ8iN_fd<G8Ci`11RUW2QlW]IXV:m?;J0GXXHfGNQ>:D`=fLPbO?VOTEYLj^cNj5PM>jKB5HVjJ4U7lXaTQNL9<@\\1`m\\Ug@VQHd7>jW=ca0`miF7;N0F=GjoQ`RFchKMGTmn8cF@Oh4GGCm7m2`U9j93Tb>=kSERjE_J939F01I1;`<ijk_=_Vn=7RVAI6fnQI5KlF:C44bN<<8K=Z<2TP<1]5?<dB>^LA=ebloE2Y2:9lkh0\\<YKbHD97iE`<C5oj^1>X:??`H6BXF2hG1Q[dF0Q=>W=J?7C\\k1T?<;R44oW?1hY^G8Zm]ZKnfOf0eCFYo6?=D8?<`6HU5SXh1;=:23LmV_FSi;OJfV<^?GkIDPISeHg1LaGE:V3Y3K3H<QJfbY?=;ldZRhnhQT_mGXDLFXXhSONE6Do_0iNZagB:BPGOTH;VhHUTd6LhQm^[;dO]5Hlkg<R:F<Kn\\:I:EGojgWZ2X@SYO_dlH;G8S<>oEKabY`:oU;=JW7ig?S?EYb86b7n8ce\\]IRa]koiWY<RfO;5kUI;7lVeC?[@ZaXDiF04B8R]bg@>O<mQDoUcBLcf^f>m2kMBUloD>Ze@NN^Z11TM`inXYhE_I=kA`:ZF4d\\>`L@;ZP[`ENU5cL[BV6\\Z?Di76:jg3hE6oG6jFc8kP=[GS1;WSedYQW1:U4\\OF32GgmMC<AjO]872bdBb`bKAA?8j78b>T3VfcUB2m4J^CPRU;8dScI]LU]^bBYA5_3:Y0N5i^?200000";var MersenneTwister=class MersenneTwister2{constructor(states,index2){this.states=states;this.index=index2}clone(){return new MersenneTwister2(this.states.slice(),this.index)}next(){let y=this.states[this.index];y^=y>>>U;y^=y<<S&B;y^=y<<T&C;y^=y>>>L;this.index=twistedNext(this.states,this.index);return y}getState(){return[this.index,...this.states]}jump(){const originalStates=this.states.slice();const originalIndex=this.index;this.index=twistedNext(this.states,this.index);for(let i=19932;i>0;--i){if(JUMP_COEFS.charCodeAt(i/6|0)-48&1<<i%6)addState(this.states,this.index,originalStates,originalIndex);this.index=twistedNext(this.states,this.index)}addState(this.states,this.index,originalStates,originalIndex)}};function addState(mt,idx,originalMt,originalIdx){let i=0;if(originalIdx>=idx){for(;i<N-originalIdx;i++)mt[i+idx]^=originalMt[i+originalIdx];for(;i<N-idx;i++)mt[i+idx]^=originalMt[i+originalIdx-N];for(;i<N;i++)mt[i+idx-N]^=originalMt[i+originalIdx-N]}else{for(;i<N-idx;i++)mt[i+idx]^=originalMt[i+originalIdx];for(;i<N-originalIdx;i++)mt[i+idx-N]^=originalMt[i+originalIdx];for(;i<N;i++)mt[i+idx-N]^=originalMt[i+originalIdx-N]}}function twistedNext(mt,idx){if(idx<N-M){const y=mt[idx]&MASK_UPPER|mt[idx+1]&MASK_LOWER;mt[idx]=mt[idx+M]^y>>>1^-(y&1)&A;return idx+1}else if(idx<N-1){const y=mt[idx]&MASK_UPPER|mt[idx+1]&MASK_LOWER;mt[idx]=mt[idx+M-N]^y>>>1^-(y&1)&A;return idx+1}else{const y=mt[idx]&MASK_UPPER|mt[0]&MASK_LOWER;mt[idx]=mt[M-1]^y>>>1^-(y&1)&A;return 0}}function twist(mt){for(let idx=0;idx!==N;++idx)twistedNext(mt,idx)}function mersenne(seed){const out=[seed|0];for(let idx=1;idx!==N;++idx){const xored=out[idx-1]^out[idx-1]>>>30;out.push(Math.imul(F,xored)+idx|0)}twist(out);return new MersenneTwister(out,0)}var jumps=[1667051007,2321340297,1548169110,304075285];var XorShift128Plus=class XorShift128Plus2{constructor(s01,s00,s11,s10){this.s01=s01;this.s00=s00;this.s11=s11;this.s10=s10}clone(){return new XorShift128Plus2(this.s01,this.s00,this.s11,this.s10)}next(){const a0=this.s00^this.s00<<23;const a1=this.s01^(this.s01<<23|this.s00>>>9);const s10=this.s10;const s11=this.s11;const out=this.s00+s10|0;this.s01=s11;this.s00=s10;this.s11=a1^s11^a1>>>18^s11>>>5;this.s10=a0^s10^(a0>>>18|a1<<14)^(s10>>>5|s11<<27);return out}jump(){let ns01=0;let ns00=0;let ns11=0;let ns10=0;let s01=this.s01;let s00=this.s00;let s11=this.s11;let s10=this.s10;for(let i=0;i!==4;++i){const ji=jumps[i];for(let mask2=1;mask2;mask2<<=1){if(ji&mask2){ns01^=s01;ns00^=s00;ns11^=s11;ns10^=s10}const a0=s00^s00<<23;const a1=s01^(s01<<23|s00>>>9);s01=s11;s00=s10;s10=a0^s10^(a0>>>18|a1<<14)^(s10>>>5|s11<<27);s11=a1^s11^a1>>>18^s11>>>5}}this.s01=ns01;this.s00=ns00;this.s11=ns11;this.s10=ns10}getState(){return[this.s01,this.s00,this.s11,this.s10]}};function xorshift128plus(seed){return new XorShift128Plus(-1,~seed,seed|0,0)}var jumps2=[3639956645,3750757012,1261568508,386426335];var XoroShiro128Plus=class XoroShiro128Plus2{constructor(s01,s00,s11,s10){this.s01=s01;this.s00=s00;this.s11=s11;this.s10=s10}clone(){return new XoroShiro128Plus2(this.s01,this.s00,this.s11,this.s10)}next(){const out=this.s00+this.s10|0;const a0=this.s10^this.s00;const a1=this.s11^this.s01;const s00=this.s00;const s01=this.s01;this.s00=s00<<24^s01>>>8^a0^a0<<16;this.s01=s01<<24^s00>>>8^a1^(a1<<16|a0>>>16);this.s10=a1<<5^a0>>>27;this.s11=a0<<5^a1>>>27;return out}jump(){let ns01=0;let ns00=0;let ns11=0;let ns10=0;let s01=this.s01;let s00=this.s00;let s11=this.s11;let s10=this.s10;for(let i=0;i!==4;++i){const ji=jumps2[i];for(let mask2=1;mask2;mask2<<=1){if(ji&mask2){ns01^=s01;ns00^=s00;ns11^=s11;ns10^=s10}const a0=s10^s00;const a1=s11^s01;const s00_=s00;const s01_=s01;s00=s00_<<24^s01_>>>8^a0^a0<<16;s01=s01_<<24^s00_>>>8^a1^(a1<<16|a0>>>16);s10=a1<<5^a0>>>27;s11=a0<<5^a1>>>27}}this.s01=ns01;this.s00=ns00;this.s11=ns11;this.s10=ns10}getState(){return[this.s01,this.s00,this.s11,this.s10]}};function xoroshiro128plus(seed){return new XoroShiro128Plus(-1,~seed,seed|0,0)}function skipN(rng,num){for(let idx=0;idx!==num;++idx)rng.next()}var SBigInt=BigInt;var NumValues=4294967296n;function uniformBigInt(rng,from,to){const diff=to-from+1n;let FinalNumValues=NumValues;let NumIterations=1;while(FinalNumValues<diff){FinalNumValues<<=32n;++NumIterations}let value3=generateNext(NumIterations,rng);if(value3<diff)return value3+from;if(value3+diff<FinalNumValues)return value3%diff+from;const MaxAcceptedRandom=FinalNumValues-FinalNumValues%diff;while(value3>=MaxAcceptedRandom)value3=generateNext(NumIterations,rng);return value3%diff+from}function generateNext(NumIterations,rng){let value3=SBigInt(rng.next()+2147483648);for(let num=1;num<NumIterations;++num){const out=rng.next();value3=(value3<<32n)+SBigInt(out+2147483648)}return value3}function uniformIntInternal(rng,rangeSize){const MaxAllowed=rangeSize>2?~~(4294967296/rangeSize)*rangeSize:4294967296;let deltaV=rng.next()+2147483648;while(deltaV>=MaxAllowed)deltaV=rng.next()+2147483648;return deltaV%rangeSize}function fromNumberToArrayInt64(out,n){if(n<0){const posN=-n;out.sign=-1;out.data[0]=~~(posN/4294967296);out.data[1]=posN>>>0}else{out.sign=1;out.data[0]=~~(n/4294967296);out.data[1]=n>>>0}return out}function substractArrayInt64(out,arrayIntA,arrayIntB){const lowA=arrayIntA.data[1];const highA=arrayIntA.data[0];const signA=arrayIntA.sign;const lowB=arrayIntB.data[1];const highB=arrayIntB.data[0];const signB=arrayIntB.sign;out.sign=1;if(signA===1&&signB===-1){const low2=lowA+lowB;const high=highA+highB+(low2>4294967295?1:0);out.data[0]=high>>>0;out.data[1]=low2>>>0;return out}let lowFirst=lowA;let highFirst=highA;let lowSecond=lowB;let highSecond=highB;if(signA===-1){lowFirst=lowB;highFirst=highB;lowSecond=lowA;highSecond=highA}let reminderLow=0;let low=lowFirst-lowSecond;if(low<0){reminderLow=1;low=low>>>0}out.data[0]=highFirst-highSecond-reminderLow;out.data[1]=low;return out}function uniformArrayIntInternal(rng,out,rangeSize){const maxIndex0=rangeSize[0]+1;out[0]=uniformIntInternal(rng,maxIndex0);out[1]=uniformIntInternal(rng,4294967296);while(out[0]>=rangeSize[0]&&(out[0]!==rangeSize[0]||out[1]>=rangeSize[1])){out[0]=uniformIntInternal(rng,maxIndex0);out[1]=uniformIntInternal(rng,4294967296)}return out}var safeNumberMaxSafeInteger=Number.MAX_SAFE_INTEGER;var sharedA={sign:1,data:[0,0]};var sharedB={sign:1,data:[0,0]};var sharedC={sign:1,data:[0,0]};var sharedData=[0,0];function uniformLargeIntInternal(rng,from,to,rangeSize){const rangeSizeArrayIntValue=rangeSize<=safeNumberMaxSafeInteger?fromNumberToArrayInt64(sharedC,rangeSize):substractArrayInt64(sharedC,fromNumberToArrayInt64(sharedA,to),fromNumberToArrayInt64(sharedB,from));if(rangeSizeArrayIntValue.data[1]===4294967295){rangeSizeArrayIntValue.data[0]+=1;rangeSizeArrayIntValue.data[1]=0}else rangeSizeArrayIntValue.data[1]+=1;uniformArrayIntInternal(rng,sharedData,rangeSizeArrayIntValue.data);return sharedData[0]*4294967296+sharedData[1]+from}function uniformInt(rng,from,to){const rangeSize=to-from;if(rangeSize<=4294967295)return uniformIntInternal(rng,rangeSize+1)+from;return uniformLargeIntInternal(rng,from,to,rangeSize)}var SharedFootPrint=Symbol.for("fast-check/PreconditionFailure");var PreconditionFailure=class extends Error{constructor(interruptExecution=false){super();this.interruptExecution=interruptExecution;this.footprint=SharedFootPrint}static isFailure(err){return err!==null&&err!==undefined&&err.footprint===SharedFootPrint}};function pre(expectTruthy){if(!expectTruthy)throw new PreconditionFailure}var Nil=class{[Symbol.iterator](){return this}next(value3){return{value:value3,done:true}}};var nil=new Nil;function nilHelper(){return nil}function*mapHelper(g,f){for(const v of g)yield f(v)}function*flatMapHelper(g,f){for(const v of g)yield*f(v)}function*filterHelper(g,f){for(const v of g)if(f(v))yield v}function*takeNHelper(g,n){for(let i=0;i<n;++i){const cur=g.next();if(cur.done)break;yield cur.value}}function*takeWhileHelper(g,f){let cur=g.next();while(!cur.done&&f(cur.value)){yield cur.value;cur=g.next()}}function*joinHelper(g,others){for(let cur=g.next();!cur.done;cur=g.next())yield cur.value;for(const s of others)for(let cur=s.next();!cur.done;cur=s.next())yield cur.value}var safeSymbolIterator$1=Symbol.iterator;var Stream=class Stream2{static nil(){return new Stream2(nilHelper())}static of(...elements){return new Stream2(elements[safeSymbolIterator$1]())}constructor(g){this.g=g}next(){return this.g.next()}[Symbol.iterator](){return this.g}map(f){return new Stream2(mapHelper(this.g,f))}flatMap(f){return new Stream2(flatMapHelper(this.g,f))}dropWhile(f){let foundEligible=false;function*helper(v){if(foundEligible||!f(v)){foundEligible=true;yield v}}return this.flatMap(helper)}drop(n){if(n<=0)return this;let idx=0;function helper(){return idx++<n}return this.dropWhile(helper)}takeWhile(f){return new Stream2(takeWhileHelper(this.g,f))}take(n){return new Stream2(takeNHelper(this.g,n))}filter(f){return new Stream2(filterHelper(this.g,f))}every(f){for(const v of this.g)if(!f(v))return false;return true}has(f){for(const v of this.g)if(f(v))return[true,v];return[false,null]}join(...others){return new Stream2(joinHelper(this.g,others))}getNthOrLast(nth){let remaining=nth;let last=null;for(const v of this.g){if(remaining--===0)return v;last=v}return last}};function stream(g){return new Stream(g)}var cloneMethod=Symbol.for("fast-check/cloneMethod");function hasCloneMethod(instance){return instance!==null&&(typeof instance==="object"||typeof instance==="function")&&cloneMethod in instance&&typeof instance[cloneMethod]==="function"}function cloneIfNeeded(instance){return hasCloneMethod(instance)?instance[cloneMethod]():instance}var safeObjectDefineProperty$4=Object.defineProperty;var Value=class{constructor(value_,context3,customGetValue){this.value_=value_;this.context=context3;this.hasToBeCloned=customGetValue!==undefined||hasCloneMethod(value_);this.readOnce=false;this.value=value_;if(this.hasToBeCloned)safeObjectDefineProperty$4(this,"value",{get:customGetValue!==undefined?customGetValue:this.getValue,enumerable:false,configurable:false})}getValue(){if(this.hasToBeCloned){if(!this.readOnce){this.readOnce=true;return this.value_}return this.value_[cloneMethod]()}return this.value_}};var Arbitrary=class{filter(refinement){return new FilterArbitrary(this,refinement)}map(mapper,unmapper){return new MapArbitrary(this,mapper,unmapper)}chain(chainer){return new ChainArbitrary(this,chainer)}};var ChainArbitrary=class extends Arbitrary{constructor(arb,chainer){super();this.arb=arb;this.chainer=chainer}generate(mrng,biasFactor){const clonedMrng=mrng.clone();const src=this.arb.generate(mrng,biasFactor);return this.valueChainer(src,mrng,clonedMrng,biasFactor)}canShrinkWithoutContext(_value){return false}shrink(value3,context3){if(this.isSafeContext(context3))return(!context3.stoppedForOriginal?this.arb.shrink(context3.originalValue,context3.originalContext).map((v)=>this.valueChainer(v,context3.clonedMrng.clone(),context3.clonedMrng,context3.originalBias)):Stream.nil()).join(context3.chainedArbitrary.shrink(value3,context3.chainedContext).map((dst)=>{const newContext={...context3,chainedContext:dst.context,stoppedForOriginal:true};return new Value(dst.value_,newContext)}));return Stream.nil()}valueChainer(v,generateMrng,clonedMrng,biasFactor){const chainedArbitrary=this.chainer(v.value_);const dst=chainedArbitrary.generate(generateMrng,biasFactor);const context3={originalBias:biasFactor,originalValue:v.value_,originalContext:v.context,stoppedForOriginal:false,chainedArbitrary,chainedContext:dst.context,clonedMrng};return new Value(dst.value_,context3)}isSafeContext(context3){return context3!==null&&context3!==undefined&&typeof context3==="object"&&"originalBias"in context3&&"originalValue"in context3&&"originalContext"in context3&&"stoppedForOriginal"in context3&&"chainedArbitrary"in context3&&"chainedContext"in context3&&"clonedMrng"in context3}};function mapperWithCloneIfNeeded(v,mapper){const sourceValue=v.value;const mappedValue=mapper(sourceValue);if(v.hasToBeCloned&&(typeof mappedValue==="object"&&mappedValue!==null||typeof mappedValue==="function")&&Object.isExtensible(mappedValue)&&!hasCloneMethod(mappedValue))Object.defineProperty(mappedValue,cloneMethod,{get:()=>()=>mapperWithCloneIfNeeded(v,mapper)[0]});return[mappedValue,sourceValue]}function valueMapper(v,mapper){const[mappedValue,sourceValue]=mapperWithCloneIfNeeded(v,mapper);return new Value(mappedValue,{originalValue:sourceValue,originalContext:v.context})}var MapArbitrary=class extends Arbitrary{constructor(arb,mapper,unmapper){super();this.arb=arb;this.mapper=mapper;this.unmapper=unmapper;this.bindValueMapper=(v)=>valueMapper(v,mapper)}generate(mrng,biasFactor){const g=this.arb.generate(mrng,biasFactor);if(!g.hasToBeCloned){const sourceValue=g.value;return new Value(this.mapper(sourceValue),{originalValue:sourceValue,originalContext:g.context})}return valueMapper(g,this.mapper)}canShrinkWithoutContext(value3){if(this.unmapper!==undefined)try{const unmapped=this.unmapper(value3);return this.arb.canShrinkWithoutContext(unmapped)}catch{return false}return false}shrink(value3,context3){if(this.isSafeContext(context3))return this.arb.shrink(context3.originalValue,context3.originalContext).map(this.bindValueMapper);if(this.unmapper!==undefined){const unmapped=this.unmapper(value3);return this.arb.shrink(unmapped,undefined).map(this.bindValueMapper)}return Stream.nil()}isSafeContext(context3){return context3!==null&&context3!==undefined&&typeof context3==="object"&&"originalValue"in context3&&"originalContext"in context3}};var FilterArbitrary=class extends Arbitrary{constructor(arb,refinement){super();this.arb=arb;this.refinement=refinement;this.bindRefinementOnValue=(v)=>this.refinementOnValue(v)}generate(mrng,biasFactor){while(true){const g=this.arb.generate(mrng,biasFactor);if(this.refinementOnValue(g))return g}}canShrinkWithoutContext(value3){return this.arb.canShrinkWithoutContext(value3)&&this.refinement(value3)}shrink(value3,context3){return this.arb.shrink(value3,context3).filter(this.bindRefinementOnValue)}refinementOnValue(v){return this.refinement(v.value)}};function isArbitrary(instance){return typeof instance==="object"&&instance!==null&&"generate"in instance&&"shrink"in instance&&"canShrinkWithoutContext"in instance}function assertIsArbitrary(instance){if(!isArbitrary(instance))throw new Error("Unexpected value received: not an instance of Arbitrary")}var untouchedApply=Function.prototype.apply;var ApplySymbol=Symbol("apply");function safeExtractApply(f){try{return f.apply}catch{return}}function safeApplyHacky(f,instance,args2){const ff=f;ff[ApplySymbol]=untouchedApply;const out=ff[ApplySymbol](instance,args2);delete ff[ApplySymbol];return out}function safeApply(f,instance,args2){if(safeExtractApply(f)===untouchedApply)return f.apply(instance,args2);return safeApplyHacky(f,instance,args2)}var SArray=Array;var SBigInt2=BigInt;var SBigInt64Array=BigInt64Array;var SBigUint64Array=BigUint64Array;var SBoolean=Boolean;var SDate=Date;var SError=Error;var SFloat32Array=Float32Array;var SFloat64Array=Float64Array;var SInt8Array=Int8Array;var SInt16Array=Int16Array;var SInt32Array=Int32Array;var SNumber=Number;var SString=String;var SSet=Set;var SUint8Array=Uint8Array;var SUint8ClampedArray=Uint8ClampedArray;var SUint16Array=Uint16Array;var SUint32Array=Uint32Array;var SencodeURIComponent=encodeURIComponent;var SMap$1=Map;var SSymbol=Symbol;var untouchedForEach=Array.prototype.forEach;var untouchedIndexOf=Array.prototype.indexOf;var untouchedJoin=Array.prototype.join;var untouchedMap=Array.prototype.map;var untouchedFlat=Array.prototype.flat;var untouchedFilter=Array.prototype.filter;var untouchedPush=Array.prototype.push;var untouchedPop=Array.prototype.pop;var untouchedSplice=Array.prototype.splice;var untouchedSlice=Array.prototype.slice;var untouchedSort=Array.prototype.sort;var untouchedEvery=Array.prototype.every;function extractForEach(instance){try{return instance.forEach}catch{return}}function extractIndexOf(instance){try{return instance.indexOf}catch{return}}function extractJoin(instance){try{return instance.join}catch{return}}function extractMap(instance){try{return instance.map}catch{return}}function extractFlat(instance){try{return instance.flat}catch{return}}function extractFilter(instance){try{return instance.filter}catch{return}}function extractPush(instance){try{return instance.push}catch{return}}function extractPop(instance){try{return instance.pop}catch{return}}function extractSplice(instance){try{return instance.splice}catch{return}}function extractSlice(instance){try{return instance.slice}catch{return}}function extractSort(instance){try{return instance.sort}catch{return}}function extractEvery(instance){try{return instance.every}catch{return}}function safeForEach(instance,fn3){if(extractForEach(instance)===untouchedForEach)return instance.forEach(fn3);return safeApply(untouchedForEach,instance,[fn3])}function safeIndexOf(instance,...args2){if(extractIndexOf(instance)===untouchedIndexOf)return instance.indexOf(...args2);return safeApply(untouchedIndexOf,instance,args2)}function safeJoin(instance,...args2){if(extractJoin(instance)===untouchedJoin)return instance.join(...args2);return safeApply(untouchedJoin,instance,args2)}function safeMap(instance,fn3){if(extractMap(instance)===untouchedMap)return instance.map(fn3);return safeApply(untouchedMap,instance,[fn3])}function safeFlat(instance,depth){if(extractFlat(instance)===untouchedFlat){[].flat();return instance.flat(depth)}return safeApply(untouchedFlat,instance,[depth])}function safeFilter(instance,predicate){if(extractFilter(instance)===untouchedFilter)return instance.filter(predicate);return safeApply(untouchedFilter,instance,[predicate])}function safePush(instance,...args2){if(extractPush(instance)===untouchedPush)return instance.push(...args2);return safeApply(untouchedPush,instance,args2)}function safePop$1(instance){if(extractPop(instance)===untouchedPop)return instance.pop();return safeApply(untouchedPop,instance,[])}function safeSplice(instance,...args2){if(extractSplice(instance)===untouchedSplice)return instance.splice(...args2);return safeApply(untouchedSplice,instance,args2)}function safeSlice(instance,...args2){if(extractSlice(instance)===untouchedSlice)return instance.slice(...args2);return safeApply(untouchedSlice,instance,args2)}function safeSort(instance,...args2){if(extractSort(instance)===untouchedSort)return instance.sort(...args2);return safeApply(untouchedSort,instance,args2)}function safeEvery(instance,...args2){if(extractEvery(instance)===untouchedEvery)return instance.every(...args2);return safeApply(untouchedEvery,instance,args2)}var untouchedGetTime=Date.prototype.getTime;var untouchedToISOString=Date.prototype.toISOString;function extractGetTime(instance){try{return instance.getTime}catch{return}}function extractToISOString(instance){try{return instance.toISOString}catch{return}}function safeGetTime(instance){if(extractGetTime(instance)===untouchedGetTime)return instance.getTime();return safeApply(untouchedGetTime,instance,[])}function safeToISOString(instance){if(extractToISOString(instance)===untouchedToISOString)return instance.toISOString();return safeApply(untouchedToISOString,instance,[])}var untouchedAdd=Set.prototype.add;var untouchedHas=Set.prototype.has;function extractAdd(instance){try{return instance.add}catch{return}}function extractHas(instance){try{return instance.has}catch(err){return}}function safeAdd(instance,value3){if(extractAdd(instance)===untouchedAdd)return instance.add(value3);return safeApply(untouchedAdd,instance,[value3])}function safeHas(instance,value3){if(extractHas(instance)===untouchedHas)return instance.has(value3);return safeApply(untouchedHas,instance,[value3])}var untouchedSet=WeakMap.prototype.set;var untouchedGet=WeakMap.prototype.get;function extractSet(instance){try{return instance.set}catch(err){return}}function extractGet(instance){try{return instance.get}catch(err){return}}function safeSet(instance,key,value3){if(extractSet(instance)===untouchedSet)return instance.set(key,value3);return safeApply(untouchedSet,instance,[key,value3])}function safeGet(instance,key){if(extractGet(instance)===untouchedGet)return instance.get(key);return safeApply(untouchedGet,instance,[key])}var untouchedMapSet=Map.prototype.set;var untouchedMapGet=Map.prototype.get;var untouchedMapHas=Map.prototype.has;function extractMapSet(instance){try{return instance.set}catch(err){return}}function extractMapGet(instance){try{return instance.get}catch(err){return}}function extractMapHas(instance){try{return instance.has}catch(err){return}}function safeMapSet(instance,key,value3){if(extractMapSet(instance)===untouchedMapSet)return instance.set(key,value3);return safeApply(untouchedMapSet,instance,[key,value3])}function safeMapGet(instance,key){if(extractMapGet(instance)===untouchedMapGet)return instance.get(key);return safeApply(untouchedMapGet,instance,[key])}function safeMapHas(instance,key){if(extractMapHas(instance)===untouchedMapHas)return instance.has(key);return safeApply(untouchedMapHas,instance,[key])}var untouchedSplit=String.prototype.split;var untouchedStartsWith=String.prototype.startsWith;var untouchedEndsWith=String.prototype.endsWith;var untouchedSubstring=String.prototype.substring;var untouchedToLowerCase=String.prototype.toLowerCase;var untouchedToUpperCase=String.prototype.toUpperCase;var untouchedPadStart=String.prototype.padStart;var untouchedCharCodeAt=String.prototype.charCodeAt;var untouchedNormalize=String.prototype.normalize;var untouchedReplace=String.prototype.replace;function extractSplit(instance){try{return instance.split}catch{return}}function extractStartsWith(instance){try{return instance.startsWith}catch{return}}function extractEndsWith(instance){try{return instance.endsWith}catch{return}}function extractSubstring(instance){try{return instance.substring}catch{return}}function extractToLowerCase(instance){try{return instance.toLowerCase}catch{return}}function extractToUpperCase(instance){try{return instance.toUpperCase}catch{return}}function extractPadStart(instance){try{return instance.padStart}catch{return}}function extractCharCodeAt(instance){try{return instance.charCodeAt}catch{return}}function extractNormalize(instance){try{return instance.normalize}catch(err){return}}function extractReplace(instance){try{return instance.replace}catch{return}}function safeSplit(instance,...args2){if(extractSplit(instance)===untouchedSplit)return instance.split(...args2);return safeApply(untouchedSplit,instance,args2)}function safeStartsWith(instance,...args2){if(extractStartsWith(instance)===untouchedStartsWith)return instance.startsWith(...args2);return safeApply(untouchedStartsWith,instance,args2)}function safeEndsWith(instance,...args2){if(extractEndsWith(instance)===untouchedEndsWith)return instance.endsWith(...args2);return safeApply(untouchedEndsWith,instance,args2)}function safeSubstring(instance,...args2){if(extractSubstring(instance)===untouchedSubstring)return instance.substring(...args2);return safeApply(untouchedSubstring,instance,args2)}function safeToLowerCase(instance){if(extractToLowerCase(instance)===untouchedToLowerCase)return instance.toLowerCase();return safeApply(untouchedToLowerCase,instance,[])}function safeToUpperCase(instance){if(extractToUpperCase(instance)===untouchedToUpperCase)return instance.toUpperCase();return safeApply(untouchedToUpperCase,instance,[])}function safePadStart(instance,...args2){if(extractPadStart(instance)===untouchedPadStart)return instance.padStart(...args2);return safeApply(untouchedPadStart,instance,args2)}function safeCharCodeAt(instance,index2){if(extractCharCodeAt(instance)===untouchedCharCodeAt)return instance.charCodeAt(index2);return safeApply(untouchedCharCodeAt,instance,[index2])}function safeNormalize(instance,form){if(extractNormalize(instance)===untouchedNormalize)return instance.normalize(form);return safeApply(untouchedNormalize,instance,[form])}function safeReplace(instance,pattern,replacement){if(extractReplace(instance)===untouchedReplace)return instance.replace(pattern,replacement);return safeApply(untouchedReplace,instance,[pattern,replacement])}var untouchedNumberToString=Number.prototype.toString;function extractNumberToString(instance){try{return instance.toString}catch{return}}function safeNumberToString(instance,...args2){if(extractNumberToString(instance)===untouchedNumberToString)return instance.toString(...args2);return safeApply(untouchedNumberToString,instance,args2)}var untouchedHasOwnProperty=Object.prototype.hasOwnProperty;var untouchedToString=Object.prototype.toString;function safeHasOwnProperty(instance,v){return safeApply(untouchedHasOwnProperty,instance,[v])}function safeToString2(instance){return safeApply(untouchedToString,instance,[])}var untouchedErrorToString=Error.prototype.toString;function safeErrorToString(instance){return safeApply(untouchedErrorToString,instance,[])}var LazyIterableIterator=class{constructor(producer){this.producer=producer}[Symbol.iterator](){if(this.it===undefined)this.it=this.producer();return this.it}next(){if(this.it===undefined)this.it=this.producer();return this.it.next()}};function makeLazy2(producer){return new LazyIterableIterator(producer)}var safeArrayIsArray$4=Array.isArray;var safeObjectDefineProperty$3=Object.defineProperty;function tupleMakeItCloneable(vs,ctxs,values3){return safeObjectDefineProperty$3(vs,cloneMethod,{value:()=>{const cloned=[];for(let idx=0;idx!==values3.length;++idx){let current=values3[idx];if(current===undefined)current=new Value(vs[idx],ctxs[idx]);safePush(cloned,current.value)}tupleMakeItCloneable(cloned,ctxs,values3);return cloned}})}function tupleShrink(arbs,value3,context3){const shrinks=[];const safeContext=safeArrayIsArray$4(context3)?context3:[];for(let idx=0;idx!==arbs.length;++idx)safePush(shrinks,makeLazy2(()=>arbs[idx].shrink(value3[idx],safeContext[idx]).map((v)=>{let cloneable=false;const vs=[];const ctxs=[];const mapped=[];for(let nestedIdx=0;nestedIdx!==arbs.length;++nestedIdx){const nestedV=nestedIdx===idx?v:new Value(cloneIfNeeded(value3[nestedIdx]),safeContext[nestedIdx]);if(nestedV.hasToBeCloned){cloneable=true;mapped[nestedIdx]=nestedV}safePush(vs,nestedV.value);safePush(ctxs,nestedV.context)}if(cloneable)tupleMakeItCloneable(vs,ctxs,mapped);return new Value(vs,ctxs)})));return Stream.nil().join(...shrinks)}var TupleArbitrary=class extends Arbitrary{constructor(arbs){super();this.arbs=arbs;for(let idx=0;idx!==arbs.length;++idx){const arb=arbs[idx];if(arb===null||arb===undefined||arb.generate===null||arb.generate===undefined)throw new Error(`Invalid parameter encountered at index ${idx}: expecting an Arbitrary`)}}generate(mrng,biasFactor){let cloneable=false;const vs=[];const ctxs=[];const mapped=[];for(let idx=0;idx!==this.arbs.length;++idx){const v=this.arbs[idx].generate(mrng,biasFactor);if(v.hasToBeCloned){cloneable=true;mapped[idx]=v}safePush(vs,v.value);safePush(ctxs,v.context)}if(cloneable)tupleMakeItCloneable(vs,ctxs,mapped);return new Value(vs,ctxs)}canShrinkWithoutContext(value3){if(!safeArrayIsArray$4(value3)||value3.length!==this.arbs.length)return false;for(let index2=0;index2!==this.arbs.length;++index2)if(!this.arbs[index2].canShrinkWithoutContext(value3[index2]))return false;return true}shrink(value3,context3){return tupleShrink(this.arbs,value3,context3)}};function tuple2(...arbs){return new TupleArbitrary(arbs)}var safeMathLog$3=Math.log;function runIdToFrequency(runId){return 2+~~(safeMathLog$3(runId+1)*0.4342944819032518)}var globalParameters={};function configureGlobal(parameters){globalParameters=parameters}function readConfigureGlobal(){return globalParameters}function resetConfigureGlobal(){globalParameters={}}var UndefinedContextPlaceholder=Symbol("UndefinedContextPlaceholder");function noUndefinedAsContext(value3){if(value3.context!==undefined)return value3;if(value3.hasToBeCloned)return new Value(value3.value_,UndefinedContextPlaceholder,()=>value3.value);return new Value(value3.value_,UndefinedContextPlaceholder)}var dummyHook$1=()=>{};var AsyncProperty=class{constructor(arb,predicate){this.arb=arb;this.predicate=predicate;const{asyncBeforeEach,asyncAfterEach,beforeEach,afterEach}=readConfigureGlobal()||{};if(asyncBeforeEach!==undefined&&beforeEach!==undefined)throw SError(`Global "asyncBeforeEach" and "beforeEach" parameters can't be set at the same time when running async properties`);if(asyncAfterEach!==undefined&&afterEach!==undefined)throw SError(`Global "asyncAfterEach" and "afterEach" parameters can't be set at the same time when running async properties`);this.beforeEachHook=asyncBeforeEach||beforeEach||dummyHook$1;this.afterEachHook=asyncAfterEach||afterEach||dummyHook$1}isAsync(){return true}generate(mrng,runId){return noUndefinedAsContext(this.arb.generate(mrng,runId!==undefined?runIdToFrequency(runId):undefined))}shrink(value3){if(value3.context===undefined&&!this.arb.canShrinkWithoutContext(value3.value_))return Stream.nil();const safeContext=value3.context!==UndefinedContextPlaceholder?value3.context:undefined;return this.arb.shrink(value3.value_,safeContext).map(noUndefinedAsContext)}async runBeforeEach(){await this.beforeEachHook()}async runAfterEach(){await this.afterEachHook()}async run(v){try{const output=await this.predicate(v);return output===undefined||output===true?null:{error:new SError("Property failed by returning false")}}catch(err){if(PreconditionFailure.isFailure(err))return err;return{error:err}}}beforeEach(hookFunction){const previousBeforeEachHook=this.beforeEachHook;this.beforeEachHook=()=>hookFunction(previousBeforeEachHook);return this}afterEach(hookFunction){const previousAfterEachHook=this.afterEachHook;this.afterEachHook=()=>hookFunction(previousAfterEachHook);return this}};var AlwaysShrinkableArbitrary=class extends Arbitrary{constructor(arb){super();this.arb=arb}generate(mrng,biasFactor){return noUndefinedAsContext(this.arb.generate(mrng,biasFactor))}canShrinkWithoutContext(_value){return true}shrink(value3,context3){if(context3===undefined&&!this.arb.canShrinkWithoutContext(value3))return Stream.nil();const safeContext=context3!==UndefinedContextPlaceholder?context3:undefined;return this.arb.shrink(value3,safeContext).map(noUndefinedAsContext)}};function asyncProperty(...args2){if(args2.length<2)throw new Error("asyncProperty expects at least two parameters");const arbs=safeSlice(args2,0,args2.length-1);const p=args2[args2.length-1];safeForEach(arbs,assertIsArbitrary);return new AsyncProperty(tuple2(...safeMap(arbs,(arb)=>new AlwaysShrinkableArbitrary(arb))),(t)=>p(...t))}var dummyHook=()=>{};var Property=class{constructor(arb,predicate){this.arb=arb;this.predicate=predicate;const{beforeEach=dummyHook,afterEach=dummyHook,asyncBeforeEach,asyncAfterEach}=readConfigureGlobal()||{};if(asyncBeforeEach!==undefined)throw SError(`"asyncBeforeEach" can't be set when running synchronous properties`);if(asyncAfterEach!==undefined)throw SError(`"asyncAfterEach" can't be set when running synchronous properties`);this.beforeEachHook=beforeEach;this.afterEachHook=afterEach}isAsync(){return false}generate(mrng,runId){return noUndefinedAsContext(this.arb.generate(mrng,runId!==undefined?runIdToFrequency(runId):undefined))}shrink(value3){if(value3.context===undefined&&!this.arb.canShrinkWithoutContext(value3.value_))return Stream.nil();const safeContext=value3.context!==UndefinedContextPlaceholder?value3.context:undefined;return this.arb.shrink(value3.value_,safeContext).map(noUndefinedAsContext)}runBeforeEach(){this.beforeEachHook()}runAfterEach(){this.afterEachHook()}run(v){try{const output=this.predicate(v);return output===undefined||output===true?null:{error:new SError("Property failed by returning false")}}catch(err){if(PreconditionFailure.isFailure(err))return err;return{error:err}}}beforeEach(hookFunction){const previousBeforeEachHook=this.beforeEachHook;this.beforeEachHook=()=>hookFunction(previousBeforeEachHook);return this}afterEach(hookFunction){const previousAfterEachHook=this.afterEachHook;this.afterEachHook=()=>hookFunction(previousAfterEachHook);return this}};function property(...args2){if(args2.length<2)throw new Error("property expects at least two parameters");const arbs=safeSlice(args2,0,args2.length-1);const p=args2[args2.length-1];safeForEach(arbs,assertIsArbitrary);return new Property(tuple2(...safeMap(arbs,(arb)=>new AlwaysShrinkableArbitrary(arb))),(t)=>p(...t))}var VerbosityLevel=function(VerbosityLevel2){VerbosityLevel2[VerbosityLevel2["None"]=0]="None";VerbosityLevel2[VerbosityLevel2["Verbose"]=1]="Verbose";VerbosityLevel2[VerbosityLevel2["VeryVerbose"]=2]="VeryVerbose";return VerbosityLevel2}({});function adaptRandomGeneratorTo8x(rng){if("unsafeNext"in rng){if(rng.unsafeJump===undefined)return{clone:()=>adaptRandomGeneratorTo8x(rng),next:()=>rng.unsafeNext(),getState:()=>rng.getState()};return{clone:()=>adaptRandomGeneratorTo8x(rng),next:()=>rng.unsafeNext(),jump:()=>rng.unsafeJump(),getState:()=>rng.getState()}}return rng}function adaptRandomGeneratorToInternal(rng){if("jump"in rng&&typeof rng.jump==="function")return rng;return{clone:()=>adaptRandomGeneratorToInternal(rng),next:()=>rng.next(),jump:()=>skipN(rng,42),getState:()=>rng.getState()}}function adaptRandomGenerator(rng){return adaptRandomGeneratorToInternal(adaptRandomGeneratorTo8x(rng))}var safeDateNow$1=Date.now;var safeMathMin$6=Math.min;var safeMathRandom=Math.random;var QualifiedParameters=class{constructor(op){const p=op||{};this.seed=readSeed(p);this.randomType=readRandomType(p);this.numRuns=readNumRuns(p);this.verbose=readVerbose(p);this.maxSkipsPerRun=p.maxSkipsPerRun!==undefined?p.maxSkipsPerRun:100;this.timeout=safeTimeout(p.timeout);this.skipAllAfterTimeLimit=safeTimeout(p.skipAllAfterTimeLimit);this.interruptAfterTimeLimit=safeTimeout(p.interruptAfterTimeLimit);this.markInterruptAsFailure=p.markInterruptAsFailure===true;this.skipEqualValues=p.skipEqualValues===true;this.ignoreEqualValues=p.ignoreEqualValues===true;this.logger=p.logger!==undefined?p.logger:(v)=>{console.log(v)};this.path=p.path!==undefined?p.path:"";this.unbiased=p.unbiased===true;this.examples=p.examples!==undefined?p.examples:[];this.endOnFailure=p.endOnFailure===true;this.reporter=p.reporter;this.asyncReporter=p.asyncReporter;this.includeErrorInReport=p.includeErrorInReport===true}toParameters(){return{seed:this.seed,randomType:this.randomType,numRuns:this.numRuns,maxSkipsPerRun:this.maxSkipsPerRun,timeout:this.timeout,skipAllAfterTimeLimit:this.skipAllAfterTimeLimit,interruptAfterTimeLimit:this.interruptAfterTimeLimit,markInterruptAsFailure:this.markInterruptAsFailure,skipEqualValues:this.skipEqualValues,ignoreEqualValues:this.ignoreEqualValues,path:this.path,logger:this.logger,unbiased:this.unbiased,verbose:this.verbose,examples:this.examples,endOnFailure:this.endOnFailure,reporter:this.reporter,asyncReporter:this.asyncReporter,includeErrorInReport:this.includeErrorInReport}}};function createQualifiedRandomGenerator(random2){return(seed)=>{return adaptRandomGenerator(random2(seed))}}function readSeed(p){if(p.seed===undefined)return safeDateNow$1()^safeMathRandom()*4294967296;const seed32=p.seed|0;if(p.seed===seed32)return seed32;return seed32^(p.seed-seed32)*4294967296}function readRandomType(p){if(p.randomType===undefined)return xorshift128plus;if(typeof p.randomType==="string")switch(p.randomType){case"mersenne":return createQualifiedRandomGenerator(mersenne);case"congruential":case"congruential32":return createQualifiedRandomGenerator(congruential32);case"xorshift128plus":return xorshift128plus;case"xoroshiro128plus":return xoroshiro128plus;default:throw new Error(`Invalid random specified: '${p.randomType}'`)}const mrng=p.randomType(0);if("min"in mrng&&mrng.min!==-2147483648)throw new Error(`Invalid random number generator: min must equal -0x80000000, got ${String(mrng.min)}`);if("max"in mrng&&mrng.max!==2147483647)throw new Error(`Invalid random number generator: max must equal 0x7fffffff, got ${String(mrng.max)}`);if(mrng===adaptRandomGenerator(mrng))return p.randomType;return createQualifiedRandomGenerator(p.randomType)}function readNumRuns(p){const defaultValue=100;if(p.numRuns!==undefined)return p.numRuns;if(p.num_runs!==undefined)return p.num_runs;return defaultValue}function readVerbose(p){if(p.verbose===undefined)return 0;if(typeof p.verbose==="boolean")return p.verbose===true?1:0;if(p.verbose<=0)return 0;if(p.verbose>=2)return 2;return p.verbose|0}function safeTimeout(value3){if(value3===undefined)return;return safeMathMin$6(value3,2147483647)}function read(op){return new QualifiedParameters(op)}function interruptAfter(timeMs,setTimeoutSafe,clearTimeoutSafe){let timeoutHandle=null;return{clear:()=>clearTimeoutSafe(timeoutHandle),promise:new Promise((resolve4)=>{timeoutHandle=setTimeoutSafe(()=>{resolve4(new PreconditionFailure(true))},timeMs)})}}var SkipAfterProperty=class{constructor(property2,getTime,timeLimit,interruptExecution,setTimeoutSafe,clearTimeoutSafe){this.property=property2;this.getTime=getTime;this.interruptExecution=interruptExecution;this.setTimeoutSafe=setTimeoutSafe;this.clearTimeoutSafe=clearTimeoutSafe;this.skipAfterTime=this.getTime()+timeLimit}isAsync(){return this.property.isAsync()}generate(mrng,runId){return this.property.generate(mrng,runId)}shrink(value3){return this.property.shrink(value3)}run(v){const remainingTime=this.skipAfterTime-this.getTime();if(remainingTime<=0){const preconditionFailure=new PreconditionFailure(this.interruptExecution);if(this.isAsync())return Promise.resolve(preconditionFailure);else return preconditionFailure}if(this.interruptExecution&&this.isAsync()){const t=interruptAfter(remainingTime,this.setTimeoutSafe,this.clearTimeoutSafe);const propRun=Promise.race([this.property.run(v),t.promise]);propRun.then(t.clear,t.clear);return propRun}return this.property.run(v)}runBeforeEach(){return this.property.runBeforeEach()}runAfterEach(){return this.property.runAfterEach()}};var timeoutAfter=(timeMs,setTimeoutSafe,clearTimeoutSafe)=>{let timeoutHandle=null;return{clear:()=>clearTimeoutSafe(timeoutHandle),promise:new Promise((resolve4)=>{timeoutHandle=setTimeoutSafe(()=>{resolve4({error:new SError(`Property timeout: exceeded limit of ${timeMs} milliseconds`)})},timeMs)})}};var TimeoutProperty=class{constructor(property2,timeMs,setTimeoutSafe,clearTimeoutSafe){this.property=property2;this.timeMs=timeMs;this.setTimeoutSafe=setTimeoutSafe;this.clearTimeoutSafe=clearTimeoutSafe}isAsync(){return true}generate(mrng,runId){return this.property.generate(mrng,runId)}shrink(value3){return this.property.shrink(value3)}async run(v){const t=timeoutAfter(this.timeMs,this.setTimeoutSafe,this.clearTimeoutSafe);const propRun=Promise.race([this.property.run(v),t.promise]);propRun.then(t.clear,t.clear);return propRun}runBeforeEach(){return Promise.resolve(this.property.runBeforeEach())}runAfterEach(){return Promise.resolve(this.property.runAfterEach())}};var UnbiasedProperty=class{constructor(property2){this.property=property2}isAsync(){return this.property.isAsync()}generate(mrng,_runId){return this.property.generate(mrng,undefined)}shrink(value3){return this.property.shrink(value3)}run(v){return this.property.run(v)}runBeforeEach(){return this.property.runBeforeEach()}runAfterEach(){return this.property.runAfterEach()}};var safeArrayFrom=Array.from;var safeBufferIsBuffer=typeof Buffer!=="undefined"?Buffer.isBuffer:undefined;var safeJsonStringify$1=JSON.stringify;var safeNumberIsNaN$5=Number.isNaN;var safeObjectKeys$5=Object.keys;var safeObjectGetOwnPropertySymbols$2=Object.getOwnPropertySymbols;var safeObjectGetOwnPropertyDescriptor$3=Object.getOwnPropertyDescriptor;var safeObjectGetPrototypeOf$2=Object.getPrototypeOf;var safeNegativeInfinity$7=Number.NEGATIVE_INFINITY;var safePositiveInfinity$8=Number.POSITIVE_INFINITY;var toStringMethod=Symbol.for("fast-check/toStringMethod");function hasToStringMethod(instance){return instance!==null&&(typeof instance==="object"||typeof instance==="function")&&toStringMethod in instance&&typeof instance[toStringMethod]==="function"}var asyncToStringMethod=Symbol.for("fast-check/asyncToStringMethod");function hasAsyncToStringMethod(instance){return instance!==null&&(typeof instance==="object"||typeof instance==="function")&&asyncToStringMethod in instance&&typeof instance[asyncToStringMethod]==="function"}var findSymbolNameRegex=/^Symbol\((.*)\)$/;function getSymbolDescription(s){if(s.description!==undefined)return s.description;const m=findSymbolNameRegex.exec(SString(s));return m&&m[1].length?m[1]:null}function stringifyNumber(numValue){switch(numValue){case 0:return 1/numValue===safeNegativeInfinity$7?"-0":"0";case safeNegativeInfinity$7:return"Number.NEGATIVE_INFINITY";case safePositiveInfinity$8:return"Number.POSITIVE_INFINITY";default:return numValue===numValue?SString(numValue):"Number.NaN"}}function isSparseArray(arr){let previousNumberedIndex=-1;for(const index2 in arr){const numberedIndex=Number(index2);if(numberedIndex!==previousNumberedIndex+1)return true;previousNumberedIndex=numberedIndex}return previousNumberedIndex+1!==arr.length}function stringifyInternal(value3,previousValues,getAsyncContent){const currentValues=[...previousValues,value3];if(typeof value3==="object"){if(safeIndexOf(previousValues,value3)!==-1)return"[cyclic]"}if(hasAsyncToStringMethod(value3)){const content=getAsyncContent(value3);if(content.state==="fulfilled")return content.value}if(hasToStringMethod(value3))try{return value3[toStringMethod]()}catch{}switch(safeToString2(value3)){case"[object Array]":{const arr=value3;if(arr.length>=50&&isSparseArray(arr)){const assignments=[];for(const index2 in arr)if(!safeNumberIsNaN$5(Number(index2)))safePush(assignments,`${index2}:${stringifyInternal(arr[index2],currentValues,getAsyncContent)}`);return assignments.length!==0?`Object.assign(Array(${arr.length}),{${safeJoin(assignments,",")}})`:`Array(${arr.length})`}const stringifiedArray=safeJoin(safeMap(arr,(v)=>stringifyInternal(v,currentValues,getAsyncContent)),",");return arr.length===0||arr.length-1 in arr?`[${stringifiedArray}]`:`[${stringifiedArray},]`}case"[object BigInt]":return`${value3}n`;case"[object Boolean]":{const unboxedToString=value3==true?"true":"false";return typeof value3==="boolean"?unboxedToString:`new Boolean(${unboxedToString})`}case"[object Date]":{const d=value3;return safeNumberIsNaN$5(safeGetTime(d))?`new Date(NaN)`:`new Date(${safeJsonStringify$1(safeToISOString(d))})`}case"[object Map]":return`new Map(${stringifyInternal(Array.from(value3),currentValues,getAsyncContent)})`;case"[object Null]":return`null`;case"[object Number]":return typeof value3==="number"?stringifyNumber(value3):`new Number(${stringifyNumber(Number(value3))})`;case"[object Object]":{try{const toStringAccessor=value3.toString;if(typeof toStringAccessor==="function"&&toStringAccessor!==Object.prototype.toString)return value3.toString()}catch{return"[object Object]"}const mapper=(k)=>`${k==="__proto__"?'["__proto__"]':typeof k==="symbol"?`[${stringifyInternal(k,currentValues,getAsyncContent)}]`:safeJsonStringify$1(k)}:${stringifyInternal(value3[k],currentValues,getAsyncContent)}`;return"{"+safeJoin([...safeObjectGetPrototypeOf$2(value3)===null?["__proto__:null"]:[],...safeMap(safeObjectKeys$5(value3),mapper),...safeMap(safeFilter(safeObjectGetOwnPropertySymbols$2(value3),(s)=>{const descriptor=safeObjectGetOwnPropertyDescriptor$3(value3,s);return descriptor&&descriptor.enumerable}),mapper)],",")+"}"}case"[object Set]":return`new Set(${stringifyInternal(Array.from(value3),currentValues,getAsyncContent)})`;case"[object String]":return typeof value3==="string"?safeJsonStringify$1(value3):`new String(${safeJsonStringify$1(value3)})`;case"[object Symbol]":{const s=value3;if(SSymbol.keyFor(s)!==undefined)return`Symbol.for(${safeJsonStringify$1(SSymbol.keyFor(s))})`;const desc=getSymbolDescription(s);if(desc===null)return"Symbol()";return s===(desc.startsWith("Symbol.")&&SSymbol[desc.substring(7)])?desc:`Symbol(${safeJsonStringify$1(desc)})`}case"[object Promise]":{const promiseContent=getAsyncContent(value3);switch(promiseContent.state){case"fulfilled":return`Promise.resolve(${stringifyInternal(promiseContent.value,currentValues,getAsyncContent)})`;case"rejected":return`Promise.reject(${stringifyInternal(promiseContent.value,currentValues,getAsyncContent)})`;case"pending":return`new Promise(() => {/*pending*/})`;default:return`new Promise(() => {/*unknown*/})`}}case"[object Error]":if(value3 instanceof Error)return`new Error(${stringifyInternal(value3.message,currentValues,getAsyncContent)})`;break;case"[object Undefined]":return`undefined`;case"[object Int8Array]":case"[object Uint8Array]":case"[object Uint8ClampedArray]":case"[object Int16Array]":case"[object Uint16Array]":case"[object Int32Array]":case"[object Uint32Array]":case"[object Float32Array]":case"[object Float64Array]":case"[object BigInt64Array]":case"[object BigUint64Array]":{if(typeof safeBufferIsBuffer==="function"&&safeBufferIsBuffer(value3))return`Buffer.from(${value3.buffer.detached?"/*detached ArrayBuffer*/":stringifyInternal(safeArrayFrom(value3.values()),currentValues,getAsyncContent)})`;const valuePrototype=safeObjectGetPrototypeOf$2(value3);const className=valuePrototype&&valuePrototype.constructor&&valuePrototype.constructor.name;if(typeof className==="string"){const typedArray=value3;if(typedArray.buffer.detached)return`${className}.from(/*detached ArrayBuffer*/)`;const valuesFromTypedArr=typedArray.values();return`${className}.from(${stringifyInternal(safeArrayFrom(valuesFromTypedArr),currentValues,getAsyncContent)})`}break}}try{return value3.toString()}catch{return safeToString2(value3)}}function stringify(value3){return stringifyInternal(value3,[],()=>({state:"unknown",value:undefined}))}function possiblyAsyncStringify(value3){const stillPendingMarker=SSymbol();const pendingPromisesForCache=[];const cache=new SMap$1;function createDelay0(){let handleId=null;const cancel=()=>{if(handleId!==null)clearTimeout(handleId)};return{delay:new Promise((resolve4)=>{handleId=setTimeout(()=>{handleId=null;resolve4(stillPendingMarker)},0)}),cancel}}const unknownState={state:"unknown",value:undefined};const getAsyncContent=function getAsyncContent(data){const cacheKey=data;if(cache.has(cacheKey))return cache.get(cacheKey);const delay0=createDelay0();const p=asyncToStringMethod in data?Promise.resolve().then(()=>data[asyncToStringMethod]()):data;p.catch(()=>{});pendingPromisesForCache.push(Promise.race([p,delay0.delay]).then((successValue)=>{if(successValue===stillPendingMarker)cache.set(cacheKey,{state:"pending",value:undefined});else cache.set(cacheKey,{state:"fulfilled",value:successValue});delay0.cancel()},(errorValue)=>{cache.set(cacheKey,{state:"rejected",value:errorValue});delay0.cancel()}));cache.set(cacheKey,unknownState);return unknownState};function loop(){const stringifiedValue=stringifyInternal(value3,[],getAsyncContent);if(pendingPromisesForCache.length===0)return stringifiedValue;return Promise.all(pendingPromisesForCache.splice(0)).then(loop)}return loop()}async function asyncStringify(value3){return Promise.resolve(possiblyAsyncStringify(value3))}function fromSyncCached(cachedValue){return cachedValue===null?new PreconditionFailure:cachedValue}function fromCached(...data){if(data[1])return data[0].then(fromSyncCached);return fromSyncCached(data[0])}function fromCachedUnsafe(cachedValue,isAsync){return fromCached(cachedValue,isAsync)}var IgnoreEqualValuesProperty=class{constructor(property2,skipRuns){this.property=property2;this.skipRuns=skipRuns;this.coveredCases=new Map}isAsync(){return this.property.isAsync()}generate(mrng,runId){return this.property.generate(mrng,runId)}shrink(value3){return this.property.shrink(value3)}run(v){const stringifiedValue=stringify(v);if(this.coveredCases.has(stringifiedValue)){const lastOutput=this.coveredCases.get(stringifiedValue);if(!this.skipRuns)return lastOutput;return fromCachedUnsafe(lastOutput,this.property.isAsync())}const out=this.property.run(v);this.coveredCases.set(stringifiedValue,out);return out}runBeforeEach(){return this.property.runBeforeEach()}runAfterEach(){return this.property.runAfterEach()}};var safeDateNow=Date.now;var safeSetTimeout=setTimeout;var safeClearTimeout=clearTimeout;function decorateProperty(rawProperty,qParams){let prop=rawProperty;if(rawProperty.isAsync()&&qParams.timeout!==undefined)prop=new TimeoutProperty(prop,qParams.timeout,safeSetTimeout,safeClearTimeout);if(qParams.unbiased)prop=new UnbiasedProperty(prop);if(qParams.skipAllAfterTimeLimit!==undefined)prop=new SkipAfterProperty(prop,safeDateNow,qParams.skipAllAfterTimeLimit,false,safeSetTimeout,safeClearTimeout);if(qParams.interruptAfterTimeLimit!==undefined)prop=new SkipAfterProperty(prop,safeDateNow,qParams.interruptAfterTimeLimit,true,safeSetTimeout,safeClearTimeout);if(qParams.skipEqualValues)prop=new IgnoreEqualValuesProperty(prop,true);if(qParams.ignoreEqualValues)prop=new IgnoreEqualValuesProperty(prop,false);return prop}var ExecutionStatus=function(ExecutionStatus2){ExecutionStatus2[ExecutionStatus2["Success"]=0]="Success";ExecutionStatus2[ExecutionStatus2["Skipped"]=-1]="Skipped";ExecutionStatus2[ExecutionStatus2["Failure"]=1]="Failure";return ExecutionStatus2}({});var RunExecution=class RunExecution2{constructor(verbosity,interruptedAsFailure){this.verbosity=verbosity;this.interruptedAsFailure=interruptedAsFailure;this.rootExecutionTrees=[];this.currentLevelExecutionTrees=this.rootExecutionTrees;this.failure=null;this.numSkips=0;this.numSuccesses=0;this.interrupted=false}appendExecutionTree(status,value3){const currentTree={status,value:value3,children:[]};this.currentLevelExecutionTrees.push(currentTree);return currentTree}fail(value3,id2,failure){if(this.verbosity>=1){const currentTree=this.appendExecutionTree(1,value3);this.currentLevelExecutionTrees=currentTree.children}if(this.pathToFailure===undefined)this.pathToFailure=`${id2}`;else this.pathToFailure+=`:${id2}`;this.value=value3;this.failure=failure}skip(value3){if(this.verbosity>=2)this.appendExecutionTree(-1,value3);if(this.pathToFailure===undefined)++this.numSkips}success(value3){if(this.verbosity>=2)this.appendExecutionTree(0,value3);if(this.pathToFailure===undefined)++this.numSuccesses}interrupt(){this.interrupted=true}isSuccess(){return this.pathToFailure===undefined}firstFailure(){return this.pathToFailure!==undefined?+safeSplit(this.pathToFailure,":")[0]:-1}numShrinks(){return this.pathToFailure!==undefined?safeSplit(this.pathToFailure,":").length-1:0}extractFailures(){if(this.isSuccess())return[];const failures=[];let cursor=this.rootExecutionTrees;while(cursor.length>0&&cursor[cursor.length-1].status===1){const failureTree=cursor[cursor.length-1];failures.push(failureTree.value);cursor=failureTree.children}return failures}static mergePaths(offsetPath,path){if(offsetPath.length===0)return path;const offsetItems=offsetPath.split(":");const remainingItems=path.split(":");const middle=+offsetItems[offsetItems.length-1]+ +remainingItems[0];return[...offsetItems.slice(0,offsetItems.length-1),`${middle}`,...remainingItems.slice(1)].join(":")}toRunDetails(seed,basePath,maxSkips,qParams){if(!this.isSuccess())return{failed:true,interrupted:this.interrupted,numRuns:this.firstFailure()+1-this.numSkips,numSkips:this.numSkips,numShrinks:this.numShrinks(),seed,counterexample:this.value,counterexamplePath:RunExecution2.mergePaths(basePath,this.pathToFailure),errorInstance:this.failure.error,failures:this.extractFailures(),executionSummary:this.rootExecutionTrees,verbose:this.verbosity,runConfiguration:qParams.toParameters()};const considerInterruptedAsFailure=this.interruptedAsFailure||this.numSuccesses===0;return{failed:this.numSkips>maxSkips||this.interrupted&&considerInterruptedAsFailure,interrupted:this.interrupted,numRuns:this.numSuccesses,numSkips:this.numSkips,numShrinks:0,seed,counterexample:null,counterexamplePath:null,error:null,errorInstance:null,failures:[],executionSummary:this.rootExecutionTrees,verbose:this.verbosity,runConfiguration:qParams.toParameters()}}};var RunnerIterator=class{constructor(sourceValues,shrink,verbose,interruptedAsFailure){this.sourceValues=sourceValues;this.shrink=shrink;this.runExecution=new RunExecution(verbose,interruptedAsFailure);this.currentIdx=-1;this.nextValues=sourceValues}[Symbol.iterator](){return this}next(){const nextValue=this.nextValues.next();if(nextValue.done||this.runExecution.interrupted)return{done:true,value:undefined};this.currentValue=nextValue.value;++this.currentIdx;return{done:false,value:nextValue.value.value_}}handleResult(result3){if(result3!==null&&typeof result3==="object"&&!PreconditionFailure.isFailure(result3)){this.runExecution.fail(this.currentValue.value_,this.currentIdx,result3);this.currentIdx=-1;this.nextValues=this.shrink(this.currentValue)}else if(result3!==null)if(!result3.interruptExecution){this.runExecution.skip(this.currentValue.value_);this.sourceValues.skippedOne()}else this.runExecution.interrupt();else this.runExecution.success(this.currentValue.value_)}};var SourceValuesIterator=class{constructor(initialValues,maxInitialIterations,remainingSkips){this.initialValues=initialValues;this.maxInitialIterations=maxInitialIterations;this.remainingSkips=remainingSkips}[Symbol.iterator](){return this}next(){if(--this.maxInitialIterations!==-1&&this.remainingSkips>=0){const n=this.initialValues.next();if(!n.done)return{value:n.value,done:false}}return{value:undefined,done:true}}skippedOne(){--this.remainingSkips;++this.maxInitialIterations}};var MIN_INT=-2147483648;var MAX_INT=2147483647;var DBL_FACTOR=Math.pow(2,27);var DBL_DIVISOR=Math.pow(2,-53);var Random=class Random2{constructor(sourceRng){this.internalRng=adaptRandomGenerator(sourceRng.clone())}clone(){return new Random2(this.internalRng)}next(bits){return uniformInt(this.internalRng,0,(1<<bits)-1)}nextBoolean(){return uniformInt(this.internalRng,0,1)===1}nextInt(min5,max5){return uniformInt(this.internalRng,min5===undefined?MIN_INT:min5,max5===undefined?MAX_INT:max5)}nextBigInt(min5,max5){return uniformBigInt(this.internalRng,min5,max5)}nextDouble(){const a=this.next(26);const b=this.next(27);return(a*DBL_FACTOR+b)*DBL_DIVISOR}getState(){if("getState"in this.internalRng&&typeof this.internalRng.getState==="function")return this.internalRng.getState()}};function tossNext(generator,rng,index2){rng.jump();return generator.generate(new Random(rng),index2)}function*toss(generator,seed,random2,examples){for(let idx=0;idx!==examples.length;++idx)yield new Value(examples[idx],undefined);for(let idx=0,rng=random2(seed);;++idx)yield tossNext(generator,rng,idx)}function lazyGenerate(generator,rng,idx){return()=>generator.generate(new Random(rng),idx)}function*lazyToss(generator,seed,random2,examples){yield*safeMap(examples,(e)=>()=>new Value(e,undefined));let idx=0;const rng=adaptRandomGenerator(random2(seed));for(;;){rng.jump();yield lazyGenerate(generator,rng,idx++)}}function produce(producer){return producer()}function pathWalk(path,initialProducers,shrink){const producers=initialProducers;const segments=path.split(":").map((text)=>+text);if(segments.length===0)return producers.map(produce);if(!segments.every((v)=>!Number.isNaN(v)))throw new Error(`Unable to replay, got invalid path=${path}`);let values3=producers.drop(segments[0]).map(produce);for(const s of segments.slice(1)){const valueToShrink=values3.getNthOrLast(0);if(valueToShrink===null)throw new Error(`Unable to replay, got wrong path=${path}`);values3=shrink(valueToShrink).drop(s)}return values3}var safeObjectAssign$6=Object.assign;function formatHints(hints){if(hints.length===1)return`Hint: ${hints[0]}`;return hints.map((h,idx)=>`Hint (${idx+1}): ${h}`).join(`
190
190
  `)}function formatFailures(failures,stringifyOne){return`Encountered failures were:
191
191
  - ${failures.map(stringifyOne).join(`
192
192
  - `)}`}function formatExecutionSummary(executionTrees,stringifyOne){const summaryLines=[];const remainingTreesAndDepth=[];for(let i=executionTrees.length-1;i>=0;--i)remainingTreesAndDepth.push({depth:1,tree:executionTrees[i]});while(remainingTreesAndDepth.length!==0){const currentTreeAndDepth=remainingTreesAndDepth.pop();const currentTree=currentTreeAndDepth.tree;const currentDepth=currentTreeAndDepth.depth;const statusIcon=currentTree.status===0?"\x1B[32m√\x1B[0m":currentTree.status===1?"\x1B[31m×\x1B[0m":"\x1B[33m!\x1B[0m";const leftPadding=currentDepth!==0?". ".repeat(currentDepth-1):"";summaryLines.push(`${leftPadding}${statusIcon} ${stringifyOne(currentTree.value)}`);for(let i=currentTree.children.length-1;i>=0;--i)remainingTreesAndDepth.push({depth:currentDepth+1,tree:currentTree.children[i]})}return`Execution summary:
@@ -218,7 +218,7 @@ ${formatHints(hints)}`;return errorMessage}function defaultReportMessage(out){re
218
218
  `)}`:""}
219
219
  const outs = ${stringifiedOuts};
220
220
  return outs[hash('${seed}' + stringify(args)) % outs.length];
221
- }`}return safeObjectDefineProperties$1(f,{toString:{value:()=>prettyPrint(stringify(outs))},[toStringMethod]:{value:()=>prettyPrint(stringify(outs))},[asyncToStringMethod]:{value:async()=>prettyPrint(await asyncStringify(outs))},[cloneMethod]:{value:producer,configurable:true}})};return producer()})}var safeMinSafeInteger=Number.MIN_SAFE_INTEGER;var safeMaxSafeInteger$1=Number.MAX_SAFE_INTEGER;function maxSafeInteger(){return new IntegerArbitrary(safeMinSafeInteger,safeMaxSafeInteger$1)}var safeMaxSafeInteger=Number.MAX_SAFE_INTEGER;function maxSafeNat(){return new IntegerArbitrary(0,safeMaxSafeInteger)}var safeNumberParseInt=Number.parseInt;function natToStringifiedNatMapper(options){const[style,v]=options;switch(style){case"oct":return`0${safeNumberToString(v,8)}`;case"hex":return`0x${safeNumberToString(v,16)}`;default:return`${v}`}}function tryParseStringifiedNat(stringValue,radix){const parsedNat=safeNumberParseInt(stringValue,radix);if(safeNumberToString(parsedNat,radix)!==stringValue)throw new Error("Invalid value");return parsedNat}function natToStringifiedNatUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");if(value3.length>=2&&value3[0]==="0"){if(value3[1]==="x")return["hex",tryParseStringifiedNat(safeSubstring(value3,2),16)];return["oct",tryParseStringifiedNat(safeSubstring(value3,1),8)]}return["dec",tryParseStringifiedNat(value3,10)]}function dotJoinerMapper$1(data){return safeJoin(data,".")}function dotJoinerUnmapper$1(value3){if(typeof value3!=="string")throw new Error("Invalid type");return safeMap(safeSplit(value3,"."),(v)=>tryParseStringifiedNat(v,10))}function ipV4(){return tuple2(nat(255),nat(255),nat(255),nat(255)).map(dotJoinerMapper$1,dotJoinerUnmapper$1)}function buildStringifiedNatArbitrary(maxValue){return tuple2(constantFrom("dec","oct","hex"),nat(maxValue)).map(natToStringifiedNatMapper,natToStringifiedNatUnmapper)}function dotJoinerMapper(data){return safeJoin(data,".")}function dotJoinerUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");return safeSplit(value3,".")}function ipV4Extended(){return oneof(tuple2(buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255)).map(dotJoinerMapper,dotJoinerUnmapper),tuple2(buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(65535)).map(dotJoinerMapper,dotJoinerUnmapper),tuple2(buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(16777215)).map(dotJoinerMapper,dotJoinerUnmapper),buildStringifiedNatArbitrary(4294967295))}function readBh(value3){if(value3.length===0)return[];else return safeSplit(value3,":")}function extractEhAndL(value3){const valueSplits=safeSplit(value3,":");if(valueSplits.length>=2&&valueSplits[valueSplits.length-1].length<=4)return[safeSlice(valueSplits,0,valueSplits.length-2),`${valueSplits[valueSplits.length-2]}:${valueSplits[valueSplits.length-1]}`];return[safeSlice(valueSplits,0,valueSplits.length-1),valueSplits[valueSplits.length-1]]}function fullySpecifiedMapper(data){return`${safeJoin(data[0],":")}:${data[1]}`}function fullySpecifiedUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");return extractEhAndL(value3)}function onlyTrailingMapper(data){return`::${safeJoin(data[0],":")}:${data[1]}`}function onlyTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");if(!safeStartsWith(value3,"::"))throw new Error("Invalid value");return extractEhAndL(safeSubstring(value3,2))}function multiTrailingMapper(data){return`${safeJoin(data[0],":")}::${safeJoin(data[1],":")}:${data[2]}`}function multiTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");const[bhString,trailingString]=safeSplit(value3,"::",2);const[eh,l]=extractEhAndL(trailingString);return[readBh(bhString),eh,l]}function multiTrailingMapperOne(data){return multiTrailingMapper([data[0],[data[1]],data[2]])}function multiTrailingUnmapperOne(value3){const out=multiTrailingUnmapper(value3);return[out[0],safeJoin(out[1],":"),out[2]]}function singleTrailingMapper(data){return`${safeJoin(data[0],":")}::${data[1]}`}function singleTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");const[bhString,trailing]=safeSplit(value3,"::",2);return[readBh(bhString),trailing]}function noTrailingMapper(data){return`${safeJoin(data[0],":")}::`}function noTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");if(!safeEndsWith(value3,"::"))throw new Error("Invalid value");return[readBh(safeSubstring(value3,0,value3.length-2))]}function h16sTol32Mapper([a,b]){return`${a}:${b}`}function h16sTol32Unmapper(value3){if(typeof value3!=="string")throw new SError("Invalid type");if(!value3.includes(":"))throw new SError("Invalid value");return value3.split(":",2)}var items="0123456789abcdef";var cachedHexa=undefined;function hexa(){if(cachedHexa===undefined)cachedHexa=integer({min:0,max:15}).map((n)=>items[n],(c)=>{if(typeof c!=="string")throw new SError("Not a string");if(c.length!==1)throw new SError("Invalid length");const code=safeCharCodeAt(c,0);if(code<=57)return code-48;if(code<97)throw new SError("Invalid character");return code-87});return cachedHexa}function ipV6(){const h16Arb=string3({unit:hexa(),minLength:1,maxLength:4,size:"max"});const ls32Arb=oneof(tuple2(h16Arb,h16Arb).map(h16sTol32Mapper,h16sTol32Unmapper),ipV4());return oneof(tuple2(array3(h16Arb,{minLength:6,maxLength:6,size:"max"}),ls32Arb).map(fullySpecifiedMapper,fullySpecifiedUnmapper),tuple2(array3(h16Arb,{minLength:5,maxLength:5,size:"max"}),ls32Arb).map(onlyTrailingMapper,onlyTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:1,size:"max"}),array3(h16Arb,{minLength:4,maxLength:4,size:"max"}),ls32Arb).map(multiTrailingMapper,multiTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:2,size:"max"}),array3(h16Arb,{minLength:3,maxLength:3,size:"max"}),ls32Arb).map(multiTrailingMapper,multiTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:3,size:"max"}),array3(h16Arb,{minLength:2,maxLength:2,size:"max"}),ls32Arb).map(multiTrailingMapper,multiTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:4,size:"max"}),h16Arb,ls32Arb).map(multiTrailingMapperOne,multiTrailingUnmapperOne),tuple2(array3(h16Arb,{minLength:0,maxLength:5,size:"max"}),ls32Arb).map(singleTrailingMapper,singleTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:6,size:"max"}),h16Arb).map(singleTrailingMapper,singleTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:7,size:"max"})).map(noTrailingMapper,noTrailingUnmapper))}var LazyArbitrary=class extends Arbitrary{constructor(name){super();this.name=name;this.underlying=null}generate(mrng,biasFactor){if(this.underlying===null)throw new Error(`Lazy arbitrary ${JSON.stringify(this.name)} not correctly initialized`);return this.underlying.generate(mrng,biasFactor)}canShrinkWithoutContext(value3){if(this.underlying===null)throw new Error(`Lazy arbitrary ${JSON.stringify(this.name)} not correctly initialized`);return this.underlying.canShrinkWithoutContext(value3)}shrink(value3,context4){if(this.underlying===null)throw new Error(`Lazy arbitrary ${JSON.stringify(this.name)} not correctly initialized`);return this.underlying.shrink(value3,context4)}};var safeGetOwnPropertyNames=Object.getOwnPropertyNames;function createLazyArbsPool(){const lazyArbsPool=new SMap$1;const getLazyFromPool=(key)=>{let lazyArb=safeMapGet(lazyArbsPool,key);if(lazyArb!==undefined)return lazyArb;lazyArb=new LazyArbitrary(String(key));safeMapSet(lazyArbsPool,key,lazyArb);return lazyArb};return getLazyFromPool}function letrec(builder){const getLazyFromPool=createLazyArbsPool();const strictArbs=builder(getLazyFromPool);const declaredArbitraryNames=safeGetOwnPropertyNames(strictArbs);for(const name of declaredArbitraryNames){const lazyArb=getLazyFromPool(name);lazyArb.underlying=strictArbs[name]}return strictArbs}function canHaveAtLeastOneItem(keys3,constraints){for(const key of keys3){const constraintsOnKey=constraints[key]||{};if(constraintsOnKey.maxLength===undefined||constraintsOnKey.maxLength>0)return true}return false}function initialPoolForEntityGraph(keys3,constraints){if(keys3.length===0)return constant2([]);if(!canHaveAtLeastOneItem(keys3,constraints))throw new SError("Contraints on pool must accept at least one entity, maxLength cannot sum to 0");return tuple2(...keys3.map((key)=>array3(constant2(key),constraints[key]))).map((values3)=>safeFlat(values3)).filter((names)=>names.length>0)}var safeObjectAssign$1=Object.assign;var safeObjectCreate$4=Object.create;var safeObjectDefineProperty$1=Object.defineProperty;var safeObjectGetPrototypeOf=Object.getPrototypeOf;var safeObjectPrototype=Object.prototype;function withTargetStringifiedValue(stringifiedValue){return safeObjectDefineProperty$1(safeObjectCreate$4(null),toStringMethod,{configurable:false,enumerable:false,writable:false,value:()=>stringifiedValue})}function withReferenceStringifiedValue(type,index2){return withTargetStringifiedValue(`<${SString(type)}#${index2}>`)}function unlinkedToLinkedEntitiesMapper(unlinkedEntities,producedLinks){const linkedEntities=safeObjectCreate$4(safeObjectPrototype);for(const name in unlinkedEntities){const unlinkedEntitiesForName=unlinkedEntities[name];const linkedEntitiesForName=[];for(const unlinkedEntity of unlinkedEntitiesForName){const linkedEntity=safeObjectAssign$1(safeObjectCreate$4(safeObjectGetPrototypeOf(unlinkedEntity)),unlinkedEntity);linkedEntitiesForName.push(linkedEntity)}linkedEntities[name]=linkedEntitiesForName}for(const name in producedLinks){const entityLinks=producedLinks[name];for(let entityIndex=0;entityIndex!==entityLinks.length;++entityIndex){const entityLinksForInstance=entityLinks[entityIndex];const linkedInstance=linkedEntities[name][entityIndex];for(const prop in entityLinksForInstance){const propValue=entityLinksForInstance[prop];linkedInstance[prop]=propValue.index===undefined?undefined:typeof propValue.index==="number"?linkedEntities[propValue.type][propValue.index]:safeMap(propValue.index,(index2)=>linkedEntities[propValue.type][index2])}safeObjectDefineProperty$1(linkedInstance,toStringMethod,{configurable:false,enumerable:false,writable:false,value:()=>{const unlinkedEntity=unlinkedEntities[name][entityIndex];const entity=safeObjectAssign$1(safeObjectCreate$4(safeObjectGetPrototypeOf(unlinkedEntity)),unlinkedEntity);for(const prop in entityLinksForInstance){const propValue=entityLinksForInstance[prop];entity[prop]=propValue.index===undefined?undefined:typeof propValue.index==="number"?withReferenceStringifiedValue(propValue.type,propValue.index):safeMap(propValue.index,(index2)=>withReferenceStringifiedValue(propValue.type,index2))}return stringify(entity)}})}}return linkedEntities}function buildInversedRelationsMapping(relations){let foundInversedRelations=0;const requestedInversedRelations=new SMap$1;for(const name in relations){const relationsForName=relations[name];for(const fieldName in relationsForName){const relation=relationsForName[fieldName];if(relation.arity!=="inverse")continue;let existingOnes=safeMapGet(requestedInversedRelations,relation.type);if(existingOnes===undefined){existingOnes=new SMap$1;safeMapSet(requestedInversedRelations,relation.type,existingOnes)}if(safeMapHas(existingOnes,relation.forwardRelationship))throw new SError(`Cannot declare multiple inverse relationships for the same forward relationship ${SString(relation.forwardRelationship)} on type ${SString(relation.type)}`);safeMapSet(existingOnes,relation.forwardRelationship,{type:name,property:fieldName});foundInversedRelations+=1}}const inversedRelations=new SMap$1;if(foundInversedRelations===0)return inversedRelations;for(const name in relations){const relationsForName=relations[name];const requestedInversedRelationsForName=safeMapGet(requestedInversedRelations,name);if(requestedInversedRelationsForName===undefined)continue;for(const fieldName in relationsForName){const relation=relationsForName[fieldName];if(relation.arity==="inverse")continue;const requestedIfAny=safeMapGet(requestedInversedRelationsForName,fieldName);if(requestedIfAny===undefined)continue;if(requestedIfAny.type!==relation.type)throw new SError(`Inverse relationship ${SString(requestedIfAny.property)} on type ${SString(requestedIfAny.type)} references forward relationship ${SString(fieldName)} but types do not match`);safeMapSet(inversedRelations,relation,requestedIfAny)}}if(inversedRelations.size!==foundInversedRelations)throw new SError(`Some inverse relationships could not be matched with their corresponding forward relationships`);return inversedRelations}var safeObjectAssign=Object.assign;var safeObjectCreate$3=Object.create;function produceLinkUnitaryIndexArbitrary(strategy,currentIndexIfSameType,countInTargetType){switch(strategy){case"exclusive":return constant2(countInTargetType);case"successor":return noBias(integer({min:currentIndexIfSameType!==undefined?currentIndexIfSameType+1:0,max:countInTargetType}));case"any":return noBias(integer({min:0,max:countInTargetType}))}}function buildLinkIndexArbitrary(arity,strategy,currentIndexIfSameType,countInTargetType,currentEntityDepth){const linkArbitrary=produceLinkUnitaryIndexArbitrary(strategy,currentIndexIfSameType,countInTargetType);switch(arity){case"0-1":return option3(linkArbitrary,{nil:undefined,depthIdentifier:currentEntityDepth});case"1":return linkArbitrary;case"many":{let randomUnicity=0;return option3(uniqueArray(linkArbitrary,{depthIdentifier:currentEntityDepth,selector:(v)=>v===countInTargetType?v+ ++randomUnicity:v,minLength:1}),{nil:[],depthIdentifier:currentEntityDepth}).map((values3)=>{let offset=0;return safeMap(values3,(v)=>v===countInTargetType?v+offset++:v)})}}}function createEmptyLinksInstanceFor(relations,targetType){const emptyLinksInstance=safeObjectCreate$3(null);const relationsForType=relations[targetType];for(const name in relationsForType){const relation=relationsForType[name];if(relation.arity==="inverse")emptyLinksInstance[name]={type:relation.type,index:[]}}return emptyLinksInstance}function assertAcceptableRelations(relations){const nonExclusiveEntities=new SSet;const exclusiveEntities=new SSet;for(const name in relations){const relationsForName=relations[name];for(const fieldName in relationsForName){const relation=relationsForName[fieldName];if(relation.arity==="inverse")continue;if(relation.strategy==="exclusive"){if(safeHas(nonExclusiveEntities,relation.type))throw new SError(`Cannot mix exclusive with other strategies for type ${SString(relation.type)}`);safeAdd(exclusiveEntities,relation.type)}else{if(safeHas(exclusiveEntities,relation.type))throw new SError(`Cannot mix exclusive with other strategies for type ${SString(relation.type)}`);safeAdd(nonExclusiveEntities,relation.type)}if(relation.strategy==="successor"&&relation.type!==name)throw new SError(`Cannot mix types for the strategy successor`);if(relation.strategy==="successor"&&relation.arity==="1")throw new SError(`Cannot use an arity of 1 for the strategy successor`)}}}function draftNextProductionState(state,offset){const{producedLinks,toBeProducedEntities}=state;const nextIndex=state.nextIndex+offset;const newProducedLinks=safeObjectAssign(safeObjectCreate$3(null),producedLinks);function getOrCreateProducedLinksFor(type){if(newProducedLinks[type]===producedLinks[type])newProducedLinks[type]=safeSlice(producedLinks[type]);return newProducedLinks[type]}function getOrCreateLinksFor(type,indexInType){const producedLinksForType=getOrCreateProducedLinksFor(type);if(producedLinksForType[indexInType]===producedLinks[type][indexInType])producedLinksForType[indexInType]=safeObjectAssign(safeObjectCreate$3(null),producedLinks[type][indexInType]);return producedLinksForType[indexInType]}function getOrCreateRelationFor(type,indexInType,property2){const links=getOrCreateLinksFor(type,indexInType);const originalEntity=producedLinks[type][indexInType];if(originalEntity!==undefined&&links[property2]===originalEntity[property2]){const sharedRelation=links[property2];links[property2]={type:sharedRelation.type,index:typeof sharedRelation.index==="object"?safeSlice(sharedRelation.index):sharedRelation.index}}return links[property2]}let newToBeProducedEntities=undefined;const toBeProduced=toBeProducedEntities[nextIndex];return{setOutboundLink:(name,value3)=>{const currentLinks=getOrCreateLinksFor(toBeProduced.type,toBeProduced.indexInType);currentLinks[name]=value3},enqueueNewEntity:(relations,targetType)=>{const producedLinksInTargetType=getOrCreateProducedLinksFor(targetType);const newEntityIndexInType=producedLinksInTargetType.length;if(newToBeProducedEntities===undefined)newToBeProducedEntities=safeSlice(toBeProducedEntities);safePush(newToBeProducedEntities,{type:targetType,indexInType:newEntityIndexInType,depth:toBeProduced.depth+1});safePush(producedLinksInTargetType,createEmptyLinksInstanceFor(relations,targetType));return newEntityIndexInType},appendBackReference:(targetType,indexInType,property2)=>{const knownInversedLinks=getOrCreateRelationFor(targetType,indexInType,property2).index;safePush(knownInversedLinks,toBeProduced.indexInType)},commit:()=>({producedLinks:newProducedLinks,toBeProducedEntities:newToBeProducedEntities!==undefined?newToBeProducedEntities:toBeProducedEntities,nextIndex:nextIndex+1})}}function buildInitialProductionState(relations,defaultEntities){const producedLinks=safeObjectCreate$3(null);for(const name in relations)producedLinks[name]=[];const toBeProducedEntities=[];for(const name of defaultEntities){safePush(toBeProducedEntities,{type:name,indexInType:producedLinks[name].length,depth:0});safePush(producedLinks[name],createEmptyLinksInstanceFor(relations,name))}return{producedLinks,toBeProducedEntities,nextIndex:0}}function buildEntityStepArbitrary(relations,inversedRelations,lastState,offset){const lastProducedLinks=lastState.producedLinks;const currentEntity=lastState.toBeProducedEntities[lastState.nextIndex+offset];const currentRelations=relations[currentEntity.type];const currentEntityDepth=createDepthIdentifier();currentEntityDepth.depth=currentEntity.depth;const subArbitraries=[];const linkContexts=[];for(const name in currentRelations){const relation=currentRelations[name];if(relation.arity==="inverse")continue;const targetType=relation.type;const countInTargetType=lastProducedLinks[targetType].length;safePush(subArbitraries,buildLinkIndexArbitrary(relation.arity,relation.strategy||"any",targetType===currentEntity.type?currentEntity.indexInType:undefined,countInTargetType,currentEntityDepth));safePush(linkContexts,{name,relation,sentinelLinkIndex:countInTargetType})}if(subArbitraries.length===0)return;return tuple2(...subArbitraries).map((results)=>{const state=draftNextProductionState(lastState,offset);for(let resultIndex=0;resultIndex!==results.length;++resultIndex){const linkOrLinks=results[resultIndex];const{name,relation,sentinelLinkIndex}=linkContexts[resultIndex];const effectiveLinks=[];const links=linkOrLinks===undefined?[]:typeof linkOrLinks==="number"?[linkOrLinks]:linkOrLinks;for(const link of links){let newEntityIndexInType;if(link>=sentinelLinkIndex)newEntityIndexInType=state.enqueueNewEntity(relations,relation.type);else newEntityIndexInType=link;safePush(effectiveLinks,newEntityIndexInType);const inversed=safeMapGet(inversedRelations,relation);if(inversed!==undefined)state.appendBackReference(relation.type,newEntityIndexInType,inversed.property)}state.setOutboundLink(name,{type:relation.type,index:linkOrLinks===undefined?undefined:typeof linkOrLinks==="number"?effectiveLinks[0]:effectiveLinks})}return state.commit()})}function onTheFlyLinksForEntityGraph(relations,defaultEntities){assertAcceptableRelations(relations);const inversedRelations=buildInversedRelationsMapping(relations);return chainUntil(constant2(buildInitialProductionState(relations,defaultEntities)),(state)=>{if(state.nextIndex>=state.toBeProducedEntities.length)return;let offset=0;let next=undefined;while(next===undefined&&state.nextIndex+offset<state.toBeProducedEntities.length){next=buildEntityStepArbitrary(relations,inversedRelations,state,offset);offset+=1}return next}).map((state)=>{return state.producedLinks})}var safeObjectKeys$1=Object.keys;var safeObjectGetOwnPropertySymbols$1=Object.getOwnPropertySymbols;var safeObjectGetOwnPropertyDescriptor$1=Object.getOwnPropertyDescriptor;function extractEnumerableKeys(instance){const keys3=safeObjectKeys$1(instance);const symbols=safeObjectGetOwnPropertySymbols$1(instance);for(let index2=0;index2!==symbols.length;++index2){const symbol4=symbols[index2];const descriptor=safeObjectGetOwnPropertyDescriptor$1(instance,symbol4);if(descriptor&&descriptor.enumerable)keys3.push(symbol4)}return keys3}var safeObjectCreate$2=Object.create;var safeObjectDefineProperty=Object.defineProperty;var safeObjectGetOwnPropertyDescriptor=Object.getOwnPropertyDescriptor;var safeObjectGetOwnPropertyNames=Object.getOwnPropertyNames;var safeObjectGetOwnPropertySymbols=Object.getOwnPropertySymbols;function buildValuesAndSeparateKeysToObjectMapper(keys3,noKeyValue){return function valuesAndSeparateKeysToObjectMapper(definition){const obj=definition[definition.length-1]?safeObjectCreate$2(null):{};for(let idx=0;idx!==keys3.length;++idx){const valueWrapper=definition[idx];if(valueWrapper!==noKeyValue){const key=keys3[idx];if(key==="__proto__")safeObjectDefineProperty(obj,key,{value:valueWrapper,configurable:true,enumerable:true,writable:true});else obj[key]=valueWrapper}}return obj}}function buildValuesAndSeparateKeysToObjectUnmapper(keys3,noKeyValue){return function valuesAndSeparateKeysToObjectUnmapper(value3){if(typeof value3!=="object"||value3===null)throw new Error("Incompatible instance received: should be a non-null object");const hasNullPrototype=Object.getPrototypeOf(value3)===null;const hasObjectPrototype="constructor"in value3&&value3.constructor===Object;if(!hasNullPrototype&&!hasObjectPrototype)throw new Error("Incompatible instance received: should be of exact type Object");let extractedPropertiesCount=0;const extractedValues=[];for(let idx=0;idx!==keys3.length;++idx){const descriptor=safeObjectGetOwnPropertyDescriptor(value3,keys3[idx]);if(descriptor!==undefined){if(!descriptor.configurable||!descriptor.enumerable||!descriptor.writable)throw new Error("Incompatible instance received: should contain only c/e/w properties");if(descriptor.get!==undefined||descriptor.set!==undefined)throw new Error("Incompatible instance received: should contain only no get/set properties");++extractedPropertiesCount;safePush(extractedValues,descriptor.value)}else safePush(extractedValues,noKeyValue)}const namePropertiesCount=safeObjectGetOwnPropertyNames(value3).length;const symbolPropertiesCount=safeObjectGetOwnPropertySymbols(value3).length;if(extractedPropertiesCount!==namePropertiesCount+symbolPropertiesCount)throw new Error("Incompatible instance received: should not contain extra properties");return[...extractedValues,hasNullPrototype]}}var noKeyValue=Symbol("no-key");function buildPartialRecordArbitrary(recordModel,requiredKeys,noNullPrototype){const keys3=extractEnumerableKeys(recordModel);const arbs=[];for(let index2=0;index2!==keys3.length;++index2){const k=keys3[index2];const requiredArbitrary=recordModel[k];if(requiredKeys===undefined||safeIndexOf(requiredKeys,k)!==-1)safePush(arbs,requiredArbitrary);else safePush(arbs,option3(requiredArbitrary,{nil:noKeyValue}))}return tuple2(...arbs,noNullPrototype?constant2(false):boolean2()).map(buildValuesAndSeparateKeysToObjectMapper(keys3,noKeyValue),buildValuesAndSeparateKeysToObjectUnmapper(keys3,noKeyValue))}function record2(recordModel,constraints){const noNullPrototype=constraints!==undefined&&!!constraints.noNullPrototype;if(constraints===undefined)return buildPartialRecordArbitrary(recordModel,undefined,noNullPrototype);if(!(("requiredKeys"in constraints)&&constraints.requiredKeys!==undefined))return buildPartialRecordArbitrary(recordModel,undefined,noNullPrototype);const requiredKeys=("requiredKeys"in constraints?constraints.requiredKeys:undefined)||[];for(let idx=0;idx!==requiredKeys.length;++idx){const descriptor=Object.getOwnPropertyDescriptor(recordModel,requiredKeys[idx]);if(descriptor===undefined)throw new Error(`requiredKeys cannot reference keys that have not been defined in recordModel`);if(!descriptor.enumerable)throw new Error(`requiredKeys cannot reference keys that are not enumerable in recordModel`)}return buildPartialRecordArbitrary(recordModel,requiredKeys,noNullPrototype)}var safeObjectCreate$1=Object.create;function unlinkedEntitiesForEntityGraph(arbitraries,countFor,unicityConstraintsFor,constraints){const recordModel=safeObjectCreate$1(null);for(const name in arbitraries){const entityRecordModel=arbitraries[name];const entityArbitrary=record2(entityRecordModel,constraints);const count=countFor(name);const unicityConstraints=unicityConstraintsFor(name);const arrayConstraints={minLength:count,maxLength:count};recordModel[name]=unicityConstraints!==undefined?uniqueArray(entityArbitrary,{...arrayConstraints,selector:unicityConstraints}):array3(entityArbitrary,arrayConstraints)}return record2(recordModel)}var safeObjectCreate=Object.create;var safeObjectKeys=Object.keys;function entityGraph(arbitraries,relations,constraints={}){const allKeys=safeObjectKeys(arbitraries);const initialPoolConstraints=constraints.initialPoolConstraints||safeObjectCreate(null);const unicityConstraints=constraints.unicityConstraints||safeObjectCreate(null);const unlinkedContraints={noNullPrototype:constraints.noNullPrototype};return initialPoolForEntityGraph(allKeys,initialPoolConstraints).chain((defaultEntities)=>onTheFlyLinksForEntityGraph(relations,defaultEntities).chain((producedLinks)=>unlinkedEntitiesForEntityGraph(arbitraries,(name)=>producedLinks[name].length,(name)=>unicityConstraints[name],unlinkedContraints).map((unlinkedEntities)=>unlinkedToLinkedEntitiesMapper(unlinkedEntities,producedLinks))))}function wordsToJoinedStringMapper(words){return safeJoin(safeMap(words,(w)=>w[w.length-1]===","?safeSubstring(w,0,w.length-1):w)," ")}function wordsToJoinedStringUnmapperFor(wordsArbitrary){return function wordsToJoinedStringUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");const words=[];for(const candidate of safeSplit(value3," "))if(wordsArbitrary.canShrinkWithoutContext(candidate))safePush(words,candidate);else if(wordsArbitrary.canShrinkWithoutContext(candidate+","))safePush(words,candidate+",");else throw new Error("Unsupported word");return words}}function wordsToSentenceMapper(words){let sentence=safeJoin(words," ");if(sentence[sentence.length-1]===",")sentence=safeSubstring(sentence,0,sentence.length-1);return safeToUpperCase(sentence[0])+safeSubstring(sentence,1)+"."}function wordsToSentenceUnmapperFor(wordsArbitrary){return function wordsToSentenceUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");if(value3.length<2||value3[value3.length-1]!=="."||value3[value3.length-2]===","||safeToUpperCase(safeToLowerCase(value3[0]))!==value3[0])throw new Error("Unsupported value");const adaptedValue=safeToLowerCase(value3[0])+safeSubstring(value3,1,value3.length-1);const words=[];const candidates=safeSplit(adaptedValue," ");for(let idx=0;idx!==candidates.length;++idx){const candidate=candidates[idx];if(wordsArbitrary.canShrinkWithoutContext(candidate))safePush(words,candidate);else if(idx===candidates.length-1&&wordsArbitrary.canShrinkWithoutContext(candidate+","))safePush(words,candidate+",");else throw new Error("Unsupported word")}return words}}function sentencesToParagraphMapper(sentences){return safeJoin(sentences," ")}function sentencesToParagraphUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");const sentences=safeSplit(value3,". ");for(let idx=0;idx<sentences.length-1;++idx)sentences[idx]+=".";return sentences}var h=(v,w)=>{return{arbitrary:constant2(v),weight:w}};function loremWord(){return oneof(h("non",6),h("adipiscing",5),h("ligula",5),h("enim",5),h("pellentesque",5),h("in",5),h("augue",5),h("et",5),h("nulla",5),h("lorem",4),h("sit",4),h("sed",4),h("diam",4),h("fermentum",4),h("ut",4),h("eu",4),h("aliquam",4),h("mauris",4),h("vitae",4),h("felis",4),h("ipsum",3),h("dolor",3),h("amet,",3),h("elit",3),h("euismod",3),h("mi",3),h("orci",3),h("erat",3),h("praesent",3),h("egestas",3),h("leo",3),h("vel",3),h("sapien",3),h("integer",3),h("curabitur",3),h("convallis",3),h("purus",3),h("risus",2),h("suspendisse",2),h("lectus",2),h("nec,",2),h("ultricies",2),h("sed,",2),h("cras",2),h("elementum",2),h("ultrices",2),h("maecenas",2),h("massa,",2),h("varius",2),h("a,",2),h("semper",2),h("proin",2),h("nec",2),h("nisl",2),h("amet",2),h("duis",2),h("congue",2),h("libero",2),h("vestibulum",2),h("pede",2),h("blandit",2),h("sodales",2),h("ante",2),h("nibh",2),h("ac",2),h("aenean",2),h("massa",2),h("suscipit",2),h("sollicitudin",2),h("fusce",2),h("tempus",2),h("aliquam,",2),h("nunc",2),h("ullamcorper",2),h("rhoncus",2),h("metus",2),h("faucibus,",2),h("justo",2),h("magna",2),h("at",2),h("tincidunt",2),h("consectetur",1),h("tortor,",1),h("dignissim",1),h("congue,",1),h("non,",1),h("porttitor,",1),h("nonummy",1),h("molestie,",1),h("est",1),h("eleifend",1),h("mi,",1),h("arcu",1),h("scelerisque",1),h("vitae,",1),h("consequat",1),h("in,",1),h("pretium",1),h("volutpat",1),h("pharetra",1),h("tempor",1),h("bibendum",1),h("odio",1),h("dui",1),h("primis",1),h("faucibus",1),h("luctus",1),h("posuere",1),h("cubilia",1),h("curae,",1),h("hendrerit",1),h("velit",1),h("mauris,",1),h("gravida",1),h("ornare",1),h("ut,",1),h("pulvinar",1),h("varius,",1),h("turpis",1),h("nibh,",1),h("eros",1),h("id",1),h("aliquet",1),h("quis",1),h("lobortis",1),h("consectetuer",1),h("morbi",1),h("vehicula",1),h("tortor",1),h("tellus,",1),h("id,",1),h("eu,",1),h("quam",1),h("feugiat,",1),h("posuere,",1),h("iaculis",1),h("lectus,",1),h("tristique",1),h("mollis,",1),h("nisl,",1),h("vulputate",1),h("sem",1),h("vivamus",1),h("placerat",1),h("imperdiet",1),h("cursus",1),h("rutrum",1),h("iaculis,",1),h("augue,",1),h("lacus",1))}function lorem(constraints={}){const{maxCount,mode="words",size:size6}=constraints;if(maxCount!==undefined&&maxCount<1)throw new Error(`lorem has to produce at least one word/sentence`);const wordArbitrary=loremWord();if(mode==="sentences")return array3(array3(wordArbitrary,{minLength:1,size:"small"}).map(wordsToSentenceMapper,wordsToSentenceUnmapperFor(wordArbitrary)),{minLength:1,maxLength:maxCount,size:size6}).map(sentencesToParagraphMapper,sentencesToParagraphUnmapper);else return array3(wordArbitrary,{minLength:1,maxLength:maxCount,size:size6}).map(wordsToJoinedStringMapper,wordsToJoinedStringUnmapperFor(wordArbitrary))}function arrayToMapMapper(data){return new Map(data)}function arrayToMapUnmapper(value3){if(typeof value3!=="object"||value3===null)throw new Error("Incompatible instance received: should be a non-null object");if(!("constructor"in value3)||value3.constructor!==Map)throw new Error("Incompatible instance received: should be of exact type Map");return Array.from(value3)}function mapKeyExtractor(entry){return entry[0]}function map13(keyArb,valueArb,constraints={}){return uniqueArray(tuple2(keyArb,valueArb),{minLength:constraints.minKeys,maxLength:constraints.maxKeys,size:constraints.size,selector:mapKeyExtractor,depthIdentifier:constraints.depthIdentifier,comparator:"SameValueZero"}).map(arrayToMapMapper,arrayToMapUnmapper)}var contextRemainingDepth=10;function memo(builder){const previous={};return(maxDepth)=>{const n=maxDepth!==undefined?maxDepth:contextRemainingDepth;if(!safeHasOwnProperty(previous,n)){const prev=contextRemainingDepth;contextRemainingDepth=n-1;previous[n]=builder(n);contextRemainingDepth=prev}return previous[n]}}function countToggledBits(n){let count=0;while(n>SBigInt2(0)){if(n&SBigInt2(1))++count;n>>=SBigInt2(1)}return count}function computeNextFlags(flags,nextSize){const allowedMask=(SBigInt2(1)<<SBigInt2(nextSize))-SBigInt2(1);const preservedFlags=flags&allowedMask;let numMissingFlags=countToggledBits(flags-preservedFlags);let nFlags=preservedFlags;for(let mask2=SBigInt2(1);mask2<=allowedMask&&numMissingFlags!==0;mask2<<=SBigInt2(1))if(!(nFlags&mask2)){nFlags|=mask2;--numMissingFlags}return nFlags}function computeTogglePositions(chars,toggleCase){const positions=[];for(let idx=chars.length-1;idx!==-1;--idx)if(toggleCase(chars[idx])!==chars[idx])safePush(positions,idx);return positions}function computeFlagsFromChars(untoggledChars,toggledChars,togglePositions){let flags=SBigInt2(0);for(let idx=0,mask2=SBigInt2(1);idx!==togglePositions.length;++idx,mask2<<=SBigInt2(1))if(untoggledChars[togglePositions[idx]]!==toggledChars[togglePositions[idx]])flags|=mask2;return flags}function applyFlagsOnChars(chars,flags,togglePositions,toggleCase){for(let idx=0,mask2=SBigInt2(1);idx!==togglePositions.length;++idx,mask2<<=SBigInt2(1))if(flags&mask2)chars[togglePositions[idx]]=toggleCase(chars[togglePositions[idx]])}var MixedCaseArbitrary=class extends Arbitrary{constructor(stringArb,toggleCase,untoggleAll){super();this.stringArb=stringArb;this.toggleCase=toggleCase;this.untoggleAll=untoggleAll}buildContextFor(rawStringValue,flagsValue){return{rawString:rawStringValue.value,rawStringContext:rawStringValue.context,flags:flagsValue.value,flagsContext:flagsValue.context}}generate(mrng,biasFactor){const rawStringValue=this.stringArb.generate(mrng,biasFactor);const chars=[...rawStringValue.value];const togglePositions=computeTogglePositions(chars,this.toggleCase);const flagsValue=bigInt2(SBigInt2(0),(SBigInt2(1)<<SBigInt2(togglePositions.length))-SBigInt2(1)).generate(mrng,undefined);applyFlagsOnChars(chars,flagsValue.value,togglePositions,this.toggleCase);return new Value(safeJoin(chars,""),this.buildContextFor(rawStringValue,flagsValue))}canShrinkWithoutContext(value3){if(typeof value3!=="string")return false;return this.untoggleAll!==undefined?this.stringArb.canShrinkWithoutContext(this.untoggleAll(value3)):this.stringArb.canShrinkWithoutContext(value3)}shrink(value3,context4){let contextSafe;if(context4!==undefined)contextSafe=context4;else if(this.untoggleAll!==undefined){const untoggledValue=this.untoggleAll(value3);const valueChars=[...value3];const untoggledValueChars=[...untoggledValue];contextSafe={rawString:untoggledValue,rawStringContext:undefined,flags:computeFlagsFromChars(untoggledValueChars,valueChars,computeTogglePositions(untoggledValueChars,this.toggleCase)),flagsContext:undefined}}else contextSafe={rawString:value3,rawStringContext:undefined,flags:SBigInt2(0),flagsContext:undefined};const rawString=contextSafe.rawString;const flags=contextSafe.flags;return this.stringArb.shrink(rawString,contextSafe.rawStringContext).map((nRawStringValue)=>{const nChars=[...nRawStringValue.value];const nTogglePositions=computeTogglePositions(nChars,this.toggleCase);const nFlags=computeNextFlags(flags,nTogglePositions.length);applyFlagsOnChars(nChars,nFlags,nTogglePositions,this.toggleCase);return new Value(safeJoin(nChars,""),this.buildContextFor(nRawStringValue,new Value(nFlags,undefined)))}).join(makeLazy2(()=>{const chars=[...rawString];const togglePositions=computeTogglePositions(chars,this.toggleCase);return bigInt2(SBigInt2(0),(SBigInt2(1)<<SBigInt2(togglePositions.length))-SBigInt2(1)).shrink(flags,contextSafe.flagsContext).map((nFlagsValue)=>{const nChars=safeSlice(chars);applyFlagsOnChars(nChars,nFlagsValue.value,togglePositions,this.toggleCase);return new Value(safeJoin(nChars,""),this.buildContextFor(new Value(rawString,contextSafe.rawStringContext),nFlagsValue))})}))}};function defaultToggleCase(rawChar){const upper=safeToUpperCase(rawChar);if(upper!==rawChar)return upper;return safeToLowerCase(rawChar)}function mixedCase(stringArb,constraints){return new MixedCaseArbitrary(stringArb,constraints&&constraints.toggleCase||defaultToggleCase,constraints&&constraints.untoggleAll)}function toTypedMapper$1(data){return SFloat32Array.from(data)}function fromTypedUnmapper$1(value3){if(!(value3 instanceof SFloat32Array))throw new Error("Unexpected type");return[...value3]}function float32Array(constraints={}){return array3(float(constraints),constraints).map(toTypedMapper$1,fromTypedUnmapper$1)}function toTypedMapper(data){return SFloat64Array.from(data)}function fromTypedUnmapper(value3){if(!(value3 instanceof SFloat64Array))throw new Error("Unexpected type");return[...value3]}function float64Array(constraints={}){return array3(double(constraints),constraints).map(toTypedMapper,fromTypedUnmapper)}function typedIntArrayArbitraryArbitraryBuilder(constraints,defaultMin,defaultMax,TypedArrayClass,arbitraryBuilder){const generatorName=TypedArrayClass.name;const{min:min5=defaultMin,max:max5=defaultMax,...arrayConstraints}=constraints;if(min5>max5)throw new Error(`Invalid range passed to ${generatorName}: min must be lower than or equal to max`);if(min5<defaultMin)throw new Error(`Invalid min value passed to ${generatorName}: min must be greater than or equal to ${defaultMin}`);if(max5>defaultMax)throw new Error(`Invalid max value passed to ${generatorName}: max must be lower than or equal to ${defaultMax}`);return array3(arbitraryBuilder({min:min5,max:max5}),arrayConstraints).map((data)=>TypedArrayClass.from(data),(value3)=>{if(!(value3 instanceof TypedArrayClass))throw new Error("Invalid type");return[...value3]})}function int16Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,-32768,32767,SInt16Array,integer)}function int32Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,-2147483648,2147483647,SInt32Array,integer)}function int8Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,-128,127,SInt8Array,integer)}function uint16Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,65535,SUint16Array,integer)}function uint32Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,4294967295,SUint32Array,integer)}function uint8Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,255,SUint8Array,integer)}function uint8ClampedArray(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,255,SUint8ClampedArray,integer)}function isSafeContext(context4){return context4!==undefined}function toGeneratorValue(value3){if(value3.hasToBeCloned)return new Value(value3.value_,{generatorContext:value3.context},()=>value3.value);return new Value(value3.value_,{generatorContext:value3.context})}function toShrinkerValue(value3){if(value3.hasToBeCloned)return new Value(value3.value_,{shrinkerContext:value3.context},()=>value3.value);return new Value(value3.value_,{shrinkerContext:value3.context})}var WithShrinkFromOtherArbitrary=class extends Arbitrary{constructor(generatorArbitrary,shrinkerArbitrary){super();this.generatorArbitrary=generatorArbitrary;this.shrinkerArbitrary=shrinkerArbitrary}generate(mrng,biasFactor){return toGeneratorValue(this.generatorArbitrary.generate(mrng,biasFactor))}canShrinkWithoutContext(value3){return this.shrinkerArbitrary.canShrinkWithoutContext(value3)}shrink(value3,context4){if(!isSafeContext(context4))return this.shrinkerArbitrary.shrink(value3,undefined).map(toShrinkerValue);if("generatorContext"in context4)return this.generatorArbitrary.shrink(value3,context4.generatorContext).map(toGeneratorValue);return this.shrinkerArbitrary.shrink(value3,context4.shrinkerContext).map(toShrinkerValue)}};function restrictedIntegerArbitraryBuilder(min5,maxGenerated,max5){const generatorArbitrary=integer({min:min5,max:maxGenerated});if(maxGenerated===max5)return generatorArbitrary;return new WithShrinkFromOtherArbitrary(generatorArbitrary,integer({min:min5,max:max5}))}var safeMathMin$1=Math.min;var safeMathMax=Math.max;var safeArrayIsArray$1=SArray.isArray;var safeObjectEntries=Object.entries;function extractMaxIndex(indexesAndValues){let maxIndex=-1;for(let index2=0;index2!==indexesAndValues.length;++index2)maxIndex=safeMathMax(maxIndex,indexesAndValues[index2][0]);return maxIndex}function arrayFromItems(length,indexesAndValues){const array4=SArray(length);for(let index2=0;index2!==indexesAndValues.length;++index2){const it=indexesAndValues[index2];if(it[0]<length)array4[it[0]]=it[1]}return array4}function sparseArray(arb,constraints={}){const{size:size6,minNumElements=0,maxLength=MaxLengthUpperBound,maxNumElements=maxLength,noTrailingHole,depthIdentifier}=constraints;const maxGeneratedLength=maxGeneratedLengthFromSizeForArbitrary(size6,maxGeneratedLengthFromSizeForArbitrary(size6,minNumElements,maxNumElements,constraints.maxNumElements!==undefined),maxLength,constraints.maxLength!==undefined);if(minNumElements>maxLength)throw new Error(`The minimal number of non-hole elements cannot be higher than the maximal length of the array`);if(minNumElements>maxNumElements)throw new Error(`The minimal number of non-hole elements cannot be higher than the maximal number of non-holes`);const resultedMaxNumElements=safeMathMin$1(maxNumElements,maxLength);const resultedSizeMaxNumElements=constraints.maxNumElements!==undefined||size6!==undefined?size6:"=";const sparseArrayNoTrailingHole=uniqueArray(tuple2(restrictedIntegerArbitraryBuilder(0,safeMathMax(maxGeneratedLength-1,0),safeMathMax(maxLength-1,0)),arb),{size:resultedSizeMaxNumElements,minLength:minNumElements,maxLength:resultedMaxNumElements,selector:(item)=>item[0],depthIdentifier}).map((items2)=>{return arrayFromItems(extractMaxIndex(items2)+1,items2)},(value3)=>{if(!safeArrayIsArray$1(value3))throw new Error("Not supported entry type");if(noTrailingHole&&value3.length!==0&&!(value3.length-1 in value3))throw new Error("No trailing hole");return safeMap(safeObjectEntries(value3),(entry)=>[Number(entry[0]),entry[1]])});if(noTrailingHole||maxLength===minNumElements)return sparseArrayNoTrailingHole;return tuple2(sparseArrayNoTrailingHole,restrictedIntegerArbitraryBuilder(minNumElements,maxGeneratedLength,maxLength)).map((data)=>{const sparse=data[0];const targetLength=data[1];if(sparse.length>=targetLength)return sparse;const longerSparse=safeSlice(sparse);longerSparse.length=targetLength;return longerSparse},(value3)=>{if(!safeArrayIsArray$1(value3))throw new Error("Not supported entry type");return[value3,value3.length]})}function arrayToSetMapper(data){return new Set(data)}function arrayToSetUnmapper(value3){if(typeof value3!=="object"||value3===null)throw new Error("Incompatible instance received: should be a non-null object");if(!("constructor"in value3)||value3.constructor!==Set)throw new Error("Incompatible instance received: should be of exact type Set");return Array.from(value3)}function set3(arb,constraints={}){return uniqueArray(arb,{minLength:constraints.minLength,maxLength:constraints.maxLength,size:constraints.size,depthIdentifier:constraints.depthIdentifier,comparator:"SameValueZero"}).map(arrayToSetMapper,arrayToSetUnmapper)}function dictOf(ka,va,maxKeys,size6,depthIdentifier,withNullPrototype){return dictionary(ka,va,{maxKeys,noNullPrototype:!withNullPrototype,size:size6,depthIdentifier})}function typedArray(constraints){return oneof(int8Array(constraints),uint8Array(constraints),uint8ClampedArray(constraints),int16Array(constraints),uint16Array(constraints),int32Array(constraints),uint32Array(constraints),float32Array(constraints),float64Array(constraints))}function anyArbitraryBuilder(constraints){const arbitrariesForBase=constraints.values;const depthSize=constraints.depthSize;const depthIdentifier=createDepthIdentifier();const maxDepth=constraints.maxDepth;const maxKeys=constraints.maxKeys;const size6=constraints.size;const baseArb=oneof(...arbitrariesForBase,...constraints.withBigInt?[bigInt2()]:[],...constraints.withDate?[date()]:[]);return letrec((tie)=>({anything:oneof({maxDepth,depthSize,depthIdentifier},baseArb,tie("array"),tie("object"),...constraints.withMap?[tie("map")]:[],...constraints.withSet?[tie("set")]:[],...constraints.withObjectString?[tie("anything").map((o)=>stringify(o))]:[],...constraints.withTypedArray?[typedArray({maxLength:maxKeys,size:size6})]:[],...constraints.withSparseArray?[sparseArray(tie("anything"),{maxNumElements:maxKeys,size:size6,depthIdentifier})]:[]),keys:constraints.withObjectString?oneof({arbitrary:constraints.key,weight:10},{arbitrary:tie("anything").map((o)=>stringify(o)),weight:1}):constraints.key,array:array3(tie("anything"),{maxLength:maxKeys,size:size6,depthIdentifier}),set:set3(tie("anything"),{maxLength:maxKeys,size:size6,depthIdentifier}),map:oneof(map13(tie("keys"),tie("anything"),{maxKeys,size:size6,depthIdentifier}),map13(tie("anything"),tie("anything"),{maxKeys,size:size6,depthIdentifier})),object:dictOf(tie("keys"),tie("anything"),maxKeys,size6,depthIdentifier,constraints.withNullPrototype)})).anything}function unboxedToBoxedMapper(value3){switch(typeof value3){case"boolean":return new SBoolean(value3);case"number":return new SNumber(value3);case"string":return new SString(value3);default:return value3}}function unboxedToBoxedUnmapper(value3){if(typeof value3!=="object"||value3===null||!("constructor"in value3))return value3;return value3.constructor===SBoolean||value3.constructor===SNumber||value3.constructor===SString?value3.valueOf():value3}function boxedArbitraryBuilder(arb){return arb.map(unboxedToBoxedMapper,unboxedToBoxedUnmapper)}function defaultValues(constraints,stringArbitrary){return[boolean2(),maxSafeInteger(),double(),stringArbitrary(constraints),oneof(stringArbitrary(constraints),constant2(null),constant2(undefined))]}function boxArbitraries(arbs){return arbs.map((arb)=>boxedArbitraryBuilder(arb))}function boxArbitrariesIfNeeded(arbs,boxEnabled){return boxEnabled?boxArbitraries(arbs).concat(arbs):arbs}function toQualifiedObjectConstraints(settings={}){const valueConstraints={size:settings.size,unit:"stringUnit"in settings?settings.stringUnit:settings.withUnicodeString?"binary":undefined};return{key:settings.key!==undefined?settings.key:string3(valueConstraints),values:boxArbitrariesIfNeeded(settings.values!==undefined?settings.values:defaultValues(valueConstraints,string3),settings.withBoxedValues===true),depthSize:settings.depthSize,maxDepth:settings.maxDepth,maxKeys:settings.maxKeys,size:settings.size,withSet:settings.withSet===true,withMap:settings.withMap===true,withObjectString:settings.withObjectString===true,withNullPrototype:settings.withNullPrototype===true,withBigInt:settings.withBigInt===true,withDate:settings.withDate===true,withTypedArray:settings.withTypedArray===true,withSparseArray:settings.withSparseArray===true}}function objectInternal(constraints){return dictionary(constraints.key,anyArbitraryBuilder(constraints),{maxKeys:constraints.maxKeys,noNullPrototype:!constraints.withNullPrototype,size:constraints.size})}function object(constraints){return objectInternal(toQualifiedObjectConstraints(constraints))}function jsonConstraintsBuilder(stringArbitrary,constraints){const{depthSize,maxDepth}=constraints;return{key:stringArbitrary,values:[boolean2(),double({noDefaultInfinity:true,noNaN:true}),stringArbitrary,constant2(null)],depthSize,maxDepth}}function anything(constraints){return anyArbitraryBuilder(toQualifiedObjectConstraints(constraints))}function jsonValue(constraints={}){const noUnicodeString=constraints.noUnicodeString===undefined||constraints.noUnicodeString===true;return anything(jsonConstraintsBuilder("stringUnit"in constraints?string3({unit:constraints.stringUnit}):noUnicodeString?string3():string3({unit:"binary"}),constraints))}var safeJsonStringify=JSON.stringify;var safeJsonParse=JSON.parse;function jsonStringUnmapper(value3){if(typeof value3!=="string")throw new SError("Cannot unmap the passed value");return safeJsonParse(value3)}function json(constraints={}){return jsonValue(constraints).map(safeJsonStringify,jsonStringUnmapper)}var safeObjectDefineProperties=Object.defineProperties;function prettyPrint(numSeen,seenValuesStrings){return`Stream(${seenValuesStrings!==undefined?`${safeJoin(seenValuesStrings,",")}…`:`${numSeen} emitted`})`}var StreamArbitrary=class extends Arbitrary{constructor(arb,history){super();this.arb=arb;this.history=history}generate(mrng,biasFactor){const appliedBiasFactor=biasFactor!==undefined&&mrng.nextInt(1,biasFactor)===1?biasFactor:undefined;const enrichedProducer=()=>{const seenValues=this.history?[]:null;let numSeenValues=0;const g=function*(arb,clonedMrng){while(true){const value3=arb.generate(clonedMrng,appliedBiasFactor).value;numSeenValues++;if(seenValues!==null)safePush(seenValues,value3);yield value3}};const s=new Stream(g(this.arb,mrng.clone()));return safeObjectDefineProperties(s,{toString:{value:()=>prettyPrint(numSeenValues,seenValues!==null?seenValues.map(stringify):undefined)},[toStringMethod]:{value:()=>prettyPrint(numSeenValues,seenValues!==null?seenValues.map(stringify):undefined)},[asyncToStringMethod]:{value:async()=>prettyPrint(numSeenValues,seenValues!==null?await Promise.all(seenValues.map(asyncStringify)):undefined)},[cloneMethod]:{value:enrichedProducer,enumerable:true}})};return new Value(enrichedProducer(),undefined)}canShrinkWithoutContext(_value){return false}shrink(_value,_context){return Stream.nil()}};function infiniteStream(arb,constraints){return new StreamArbitrary(arb,constraints!==undefined&&typeof constraints==="object"&&"noHistory"in constraints?!constraints.noHistory:true)}function codePointsToStringMapper(tab){return safeJoin(tab,"")}function codePointsToStringUnmapper(value3){if(typeof value3!=="string")throw new Error("Cannot unmap the passed value");return[...value3]}function stringToBase64Mapper(s){switch(s.length%4){case 0:return s;case 3:return`${s}=`;case 2:return`${s}==`;default:return safeSubstring(s,1)}}function stringToBase64Unmapper(value3){if(typeof value3!=="string"||value3.length%4!==0)throw new Error("Invalid string received");const lastTrailingIndex=value3.indexOf("=");if(lastTrailingIndex===-1)return value3;if(value3.length-lastTrailingIndex>2)throw new Error("Cannot unmap the passed value");return safeSubstring(value3,0,lastTrailingIndex)}var safeStringFromCharCode=String.fromCharCode;function base64Mapper(v){if(v<26)return safeStringFromCharCode(v+65);if(v<52)return safeStringFromCharCode(v+97-26);if(v<62)return safeStringFromCharCode(v+48-52);return v===62?"+":"/"}function base64Unmapper(s){if(typeof s!=="string"||s.length!==1)throw new SError("Invalid entry");const v=safeCharCodeAt(s,0);if(v>=65&&v<=90)return v-65;if(v>=97&&v<=122)return v-97+26;if(v>=48&&v<=57)return v-48+52;return v===43?62:v===47?63:-1}function base64(){return integer({min:0,max:63}).map(base64Mapper,base64Unmapper)}function base64String(constraints={}){const{minLength:unscaledMinLength=0,maxLength:unscaledMaxLength=MaxLengthUpperBound,size:size6}=constraints;const minLength=unscaledMinLength+3-(unscaledMinLength+3)%4;const maxLength=unscaledMaxLength-unscaledMaxLength%4;const requestedSize=constraints.maxLength===undefined&&size6===undefined?"=":size6;if(minLength>maxLength)throw new SError("Minimal length should be inferior or equal to maximal length");if(minLength%4!==0)throw new SError("Minimal length of base64 strings must be a multiple of 4");if(maxLength%4!==0)throw new SError("Maximal length of base64 strings must be a multiple of 4");const charArbitrary=base64();return array3(charArbitrary,{minLength,maxLength,size:requestedSize,experimentalCustomSlices:createSlicesForStringLegacy(charArbitrary,codePointsToStringUnmapper)}).map(codePointsToStringMapper,codePointsToStringUnmapper).map(stringToBase64Mapper,stringToBase64Unmapper)}var safeObjectIs=Object.is;function isSubarrayOf(source,small){const countMap=new SMap$1;let countMinusZero=0;for(const sourceEntry of source)if(safeObjectIs(sourceEntry,-0))++countMinusZero;else safeMapSet(countMap,sourceEntry,(safeMapGet(countMap,sourceEntry)||0)+1);for(let index2=0;index2!==small.length;++index2){if(!(index2 in small))return false;const smallEntry=small[index2];if(safeObjectIs(smallEntry,-0)){if(countMinusZero===0)return false;--countMinusZero}else{const oldCount=safeMapGet(countMap,smallEntry)||0;if(oldCount===0)return false;safeMapSet(countMap,smallEntry,oldCount-1)}}return true}var safeMathFloor$1=Math.floor;var safeMathLog=Math.log;var safeArrayIsArray=Array.isArray;var SubarrayArbitrary=class extends Arbitrary{constructor(originalArray,isOrdered,minLength,maxLength){super();this.originalArray=originalArray;this.isOrdered=isOrdered;this.minLength=minLength;this.maxLength=maxLength;if(minLength<0||minLength>originalArray.length)throw new Error("fc.*{s|S}ubarrayOf expects the minimal length to be between 0 and the size of the original array");if(maxLength<0||maxLength>originalArray.length)throw new Error("fc.*{s|S}ubarrayOf expects the maximal length to be between 0 and the size of the original array");if(minLength>maxLength)throw new Error("fc.*{s|S}ubarrayOf expects the minimal length to be inferior or equal to the maximal length");this.lengthArb=new IntegerArbitrary(minLength,maxLength);this.biasedLengthArb=minLength!==maxLength?new IntegerArbitrary(minLength,minLength+safeMathFloor$1(safeMathLog(maxLength-minLength)/safeMathLog(2))):this.lengthArb}generate(mrng,biasFactor){const size6=(biasFactor!==undefined&&mrng.nextInt(1,biasFactor)===1?this.biasedLengthArb:this.lengthArb).generate(mrng,undefined);const sizeValue=size6.value;const remainingElements=safeMap(this.originalArray,(_v,idx)=>idx);const ids=[];for(let index2=0;index2!==sizeValue;++index2){const selectedIdIndex=mrng.nextInt(0,remainingElements.length-1);safePush(ids,remainingElements[selectedIdIndex]);safeSplice(remainingElements,selectedIdIndex,1)}if(this.isOrdered)safeSort(ids,(a,b)=>a-b);return new Value(safeMap(ids,(i)=>this.originalArray[i]),size6.context)}canShrinkWithoutContext(value3){if(!safeArrayIsArray(value3))return false;if(!this.lengthArb.canShrinkWithoutContext(value3.length))return false;return isSubarrayOf(this.originalArray,value3)}shrink(value3,context4){if(value3.length===0)return Stream.nil();return this.lengthArb.shrink(value3.length,context4).map((newSize)=>{return new Value(safeSlice(value3,value3.length-newSize.value),newSize.context)}).join(value3.length>this.minLength?makeLazy2(()=>this.shrink(safeSlice(value3,1),undefined).filter((newValue)=>this.minLength<=newValue.value.length+1).map((newValue)=>new Value([value3[0],...newValue.value],undefined))):Stream.nil())}};function subarray(originalArray,constraints={}){const{minLength=0,maxLength=originalArray.length}=constraints;return new SubarrayArbitrary(originalArray,true,minLength,maxLength)}function shuffledSubarray(originalArray,constraints={}){const{minLength=0,maxLength=originalArray.length}=constraints;return new SubarrayArbitrary(originalArray,false,minLength,maxLength)}var encodeSymbolLookupTable={10:"A",11:"B",12:"C",13:"D",14:"E",15:"F",16:"G",17:"H",18:"J",19:"K",20:"M",21:"N",22:"P",23:"Q",24:"R",25:"S",26:"T",27:"V",28:"W",29:"X",30:"Y",31:"Z"};var decodeSymbolLookupTable={"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,A:10,B:11,C:12,D:13,E:14,F:15,G:16,H:17,J:18,K:19,M:20,N:21,P:22,Q:23,R:24,S:25,T:26,V:27,W:28,X:29,Y:30,Z:31};function encodeSymbol(symbol4){return symbol4<10?SString(symbol4):encodeSymbolLookupTable[symbol4]}function pad(value3,paddingLength){let extraPadding="";while(value3.length+extraPadding.length<paddingLength)extraPadding+="0";return extraPadding+value3}function smallUintToBase32StringMapper(num){let base32Str="";for(let remaining=num;remaining!==0;){const next=remaining>>5;base32Str=encodeSymbol(remaining-(next<<5))+base32Str;remaining=next}return base32Str}function uintToBase32StringMapper(num,paddingLength){const head=~~(num/1073741824);const tail=num&1073741823;return pad(smallUintToBase32StringMapper(head),paddingLength-6)+pad(smallUintToBase32StringMapper(tail),6)}function paddedUintToBase32StringMapper(paddingLength){return function padded(num){return uintToBase32StringMapper(num,paddingLength)}}function uintToBase32StringUnmapper(value3){if(typeof value3!=="string")throw new SError("Unsupported type");let accumulated=0;let power=1;for(let index2=value3.length-1;index2>=0;--index2){const char=value3[index2];const numericForChar=decodeSymbolLookupTable[char];if(numericForChar===undefined)throw new SError("Unsupported type");accumulated+=numericForChar*power;power*=32}return accumulated}var padded10Mapper=paddedUintToBase32StringMapper(10);var padded8Mapper=paddedUintToBase32StringMapper(8);function ulidMapper(parts){return padded10Mapper(parts[0])+padded8Mapper(parts[1])+padded8Mapper(parts[2])}function ulidUnmapper(value3){if(typeof value3!=="string"||value3.length!==26)throw new Error("Unsupported type");return[uintToBase32StringUnmapper(value3.slice(0,10)),uintToBase32StringUnmapper(value3.slice(10,18)),uintToBase32StringUnmapper(value3.slice(18))]}function ulid(){return tuple2(integer({min:0,max:281474976710655}),integer({min:0,max:1099511627775}),integer({min:0,max:1099511627775})).map(ulidMapper,ulidUnmapper)}function numberToPaddedEightMapper(n){return safePadStart(safeNumberToString(n,16),8,"0")}function numberToPaddedEightUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");if(value3.length!==8)throw new Error("Unsupported value: invalid length");const n=parseInt(value3,16);if(value3!==numberToPaddedEightMapper(n))throw new Error("Unsupported value: invalid content");return n}function buildPaddedNumberArbitrary(min5,max5){return integer({min:min5,max:max5}).map(numberToPaddedEightMapper,numberToPaddedEightUnmapper)}function paddedEightsToUuidMapper(t){return`${t[0]}-${safeSubstring(t[1],4)}-${safeSubstring(t[1],0,4)}-${safeSubstring(t[2],0,4)}-${safeSubstring(t[2],4)}${t[3]}`}var UuidRegex=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/;function paddedEightsToUuidUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");const m=UuidRegex.exec(value3);if(m===null)throw new Error("Unsupported type");return[m[1],m[3]+m[2],m[4]+safeSubstring(m[5],0,4),safeSubstring(m[5],4)]}var quickNumberToHexaString="0123456789abcdef";function buildVersionsAppliersForUuid(versions){const mapping={};const reversedMapping={};for(let index2=0;index2!==versions.length;++index2){const from=quickNumberToHexaString[index2];const to=quickNumberToHexaString[versions[index2]];mapping[from]=to;reversedMapping[to]=from}function versionsApplierMapper(value3){return mapping[value3[0]]+safeSubstring(value3,1)}function versionsApplierUnmapper(value3){if(typeof value3!=="string")throw new SError("Cannot produce non-string values");const rev=reversedMapping[value3[0]];if(rev===undefined)throw new SError("Cannot produce strings not starting by the version in hexa code");return rev+safeSubstring(value3,1)}return{versionsApplierMapper,versionsApplierUnmapper}}function assertValidVersions(versions){const found={};for(const version2 of versions){if(found[version2])throw new SError(`Version ${version2} has been requested at least twice for uuid`);found[version2]=true;if(version2<1||version2>15)throw new SError(`Version must be a value in [1-15] for uuid, but received ${version2}`);if(~~version2!==version2)throw new SError(`Version must be an integer value for uuid, but received ${version2}`)}if(versions.length===0)throw new SError(`Must provide at least one version for uuid`)}function uuid(constraints={}){const padded=buildPaddedNumberArbitrary(0,4294967295);const version2=constraints.version!==undefined?typeof constraints.version==="number"?[constraints.version]:constraints.version:[1,2,3,4,5,6,7,8];assertValidVersions(version2);const{versionsApplierMapper,versionsApplierUnmapper}=buildVersionsAppliersForUuid(version2);return tuple2(padded,buildPaddedNumberArbitrary(0,268435456*version2.length-1).map(versionsApplierMapper,versionsApplierUnmapper),buildPaddedNumberArbitrary(2147483648,3221225471),padded).map(paddedEightsToUuidMapper,paddedEightsToUuidUnmapper)}function hostUserInfo(size6){return string3({unit:getOrCreateAlphaNumericPercentArbitrary("-._~!$&'()*+,;=:"),size:size6})}function userHostPortMapper([u,h2,p]){return(u===null?"":`${u}@`)+h2+(p===null?"":`:${p}`)}function userHostPortUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported");const atPosition=value3.indexOf("@");const user=atPosition!==-1?value3.substring(0,atPosition):null;const m=/:(\d+)$/.exec(value3);const port=m!==null?Number(m[1]):null;return[user,m!==null?value3.substring(atPosition+1,value3.length-m[1].length-1):value3.substring(atPosition+1),port]}function bracketedMapper(s){return`[${s}]`}function bracketedUnmapper(value3){if(typeof value3!=="string"||value3[0]!=="["||value3[value3.length-1]!=="]")throw new Error("Unsupported");return value3.substring(1,value3.length-1)}function webAuthority(constraints){const c=constraints||{};const size6=c.size;const hostnameArbs=[domain({size:size6}),...c.withIPv4===true?[ipV4()]:[],...c.withIPv6===true?[ipV6().map(bracketedMapper,bracketedUnmapper)]:[],...c.withIPv4Extended===true?[ipV4Extended()]:[]];return tuple2(c.withUserInfo===true?option3(hostUserInfo(size6)):constant2(null),oneof(...hostnameArbs),c.withPort===true?option3(nat(65535)):constant2(null)).map(userHostPortMapper,userHostPortUnmapper)}function buildUriQueryOrFragmentArbitrary(size6){return string3({unit:getOrCreateAlphaNumericPercentArbitrary("-._~!$&'()*+,;=:@/?"),size:size6})}function webFragments(constraints={}){return buildUriQueryOrFragmentArbitrary(constraints.size)}function webSegment(constraints={}){return string3({unit:getOrCreateAlphaNumericPercentArbitrary("-._~!$&'()*+,;=:@"),size:constraints.size})}function segmentsToPathMapper(segments){let path="";for(let index2=0;index2!==segments.length;++index2)path+="/"+segments[index2];return path}function segmentsToPathUnmapper(value3){if(typeof value3!=="string")throw new Error("Incompatible value received: type");if(value3.length!==0&&value3[0]!=="/")throw new Error("Incompatible value received: start");return safeSplice(safeSplit(value3,"/"),1)}function sqrtSize(size6){switch(size6){case"xsmall":return["xsmall","xsmall"];case"small":return["small","xsmall"];case"medium":return["small","small"];case"large":return["medium","small"];case"xlarge":return["medium","medium"]}}function buildUriPathArbitraryInternal(segmentSize,numSegmentSize){return array3(webSegment({size:segmentSize}),{size:numSegmentSize}).map(segmentsToPathMapper,segmentsToPathUnmapper)}function buildUriPathArbitrary(resolvedSize){const[segmentSize,numSegmentSize]=sqrtSize(resolvedSize);if(segmentSize===numSegmentSize)return buildUriPathArbitraryInternal(segmentSize,numSegmentSize);return oneof(buildUriPathArbitraryInternal(segmentSize,numSegmentSize),buildUriPathArbitraryInternal(numSegmentSize,segmentSize))}function webPath(constraints){return buildUriPathArbitrary(resolveSize((constraints||{}).size))}function webQueryParameters(constraints={}){return buildUriQueryOrFragmentArbitrary(constraints.size)}function partsToUrlMapper(data){const[scheme,authority,path]=data;return`${scheme}://${authority}${path}${data[3]===null?"":`?${data[3]}`}${data[4]===null?"":`#${data[4]}`}`}var UrlSplitRegex=/^([[A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)([^?#]*)(\?[A-Za-z0-9\-._~!$&'()*+,;=:@/?%]*)?(#[A-Za-z0-9\-._~!$&'()*+,;=:@/?%]*)?$/;function partsToUrlUnmapper(value3){if(typeof value3!=="string")throw new Error("Incompatible value received: type");const m=UrlSplitRegex.exec(value3);if(m===null)throw new Error("Incompatible value received");const scheme=m[1];const authority=m[2];const path=m[3];const query=m[4];const fragments=m[5];return[scheme,authority,path,query!==undefined?query.substring(1):null,fragments!==undefined?fragments.substring(1):null]}function webUrl(constraints){const c=constraints||{};const resolvedSize=resolveSize(c.size);const resolvedAuthoritySettingsSize=c.authoritySettings!==undefined&&c.authoritySettings.size!==undefined?relativeSizeToSize(c.authoritySettings.size,resolvedSize):resolvedSize;const resolvedAuthoritySettings={...c.authoritySettings,size:resolvedAuthoritySettingsSize};return tuple2(constantFrom(...c.validSchemes||["http","https"]),webAuthority(resolvedAuthoritySettings),webPath({size:resolvedSize}),c.withQueryParameters===true?option3(webQueryParameters({size:resolvedSize})):constant2(null),c.withFragments===true?option3(webFragments({size:resolvedSize})):constant2(null)).map(partsToUrlMapper,partsToUrlUnmapper)}var CommandsIterable=class CommandsIterable2{constructor(commands,metadataForReplay){this.commands=commands;this.metadataForReplay=metadataForReplay;this[cloneMethod]=function(){return new CommandsIterable2(this.commands.map((c)=>c.clone()),this.metadataForReplay)}}[Symbol.iterator](){return this.commands[Symbol.iterator]()}toString(){const serializedCommands=this.commands.filter((c)=>c.hasRan).map((c)=>c.toString()).join(",");const metadata=this.metadataForReplay();return metadata.length!==0?`${serializedCommands} /*${metadata}*/`:serializedCommands}};var CommandWrapper=class CommandWrapper2{constructor(cmd){this.cmd=cmd;this.hasRan=false;if(hasToStringMethod(cmd)){const method=cmd[toStringMethod];this[toStringMethod]=function toStringMethod2(){return method.call(cmd)}}if(hasAsyncToStringMethod(cmd)){const method=cmd[asyncToStringMethod];this[asyncToStringMethod]=function asyncToStringMethod2(){return method.call(cmd)}}}check(m){return this.cmd.check(m)}run(m,r){this.hasRan=true;return this.cmd.run(m,r)}clone(){if(hasCloneMethod(this.cmd))return new CommandWrapper2(this.cmd[cloneMethod]());return new CommandWrapper2(this.cmd)}toString(){return this.cmd.toString()}};var ReplayPath=class{static parse(replayPathStr){const[serializedCount,serializedChanges]=replayPathStr.split(":");const counts=this.parseCounts(serializedCount);const changes=this.parseChanges(serializedChanges);return this.parseOccurences(counts,changes)}static stringify(replayPath){const occurences=this.countOccurences(replayPath);return`${this.stringifyCounts(occurences)}:${this.stringifyChanges(occurences)}`}static intToB64(n){if(n<26)return String.fromCharCode(n+65);if(n<52)return String.fromCharCode(n+97-26);if(n<62)return String.fromCharCode(n+48-52);return String.fromCharCode(n===62?43:47)}static b64ToInt(c){if(c>="a")return c.charCodeAt(0)-97+26;if(c>="A")return c.charCodeAt(0)-65;if(c>="0")return c.charCodeAt(0)-48+52;return c==="+"?62:63}static countOccurences(replayPath){return replayPath.reduce((counts,cur)=>{if(counts.length===0||counts[counts.length-1].count===64||counts[counts.length-1].value!==cur)counts.push({value:cur,count:1});else counts[counts.length-1].count+=1;return counts},[])}static parseOccurences(counts,changes){const replayPath=[];for(let idx=0;idx!==counts.length;++idx){const count=counts[idx];const value3=changes[idx];for(let num=0;num!==count;++num)replayPath.push(value3)}return replayPath}static stringifyChanges(occurences){let serializedChanges="";for(let idx=0;idx<occurences.length;idx+=6){const changesInt=occurences.slice(idx,idx+6).reduceRight((prev,cur)=>(prev<<1)+(cur.value?1:0),0);serializedChanges+=this.intToB64(changesInt)}return serializedChanges}static parseChanges(serializedChanges){const changesInt=serializedChanges.split("").map((c)=>this.b64ToInt(c));const changes=[];for(let idx=0;idx!==changesInt.length;++idx){let current=changesInt[idx];for(let n=0;n!==6;++n,current>>=1)changes.push(current%2===1)}return changes}static stringifyCounts(occurences){return occurences.map(({count})=>this.intToB64(count-1)).join("")}static parseCounts(serializedCount){return serializedCount.split("").map((c)=>this.b64ToInt(c)+1)}};var CommandsArbitrary=class extends Arbitrary{constructor(commandArbs,maxGeneratedCommands,maxCommands,sourceReplayPath,disableReplayLog){super();this.sourceReplayPath=sourceReplayPath;this.disableReplayLog=disableReplayLog;this.oneCommandArb=oneof(...commandArbs).map((c)=>new CommandWrapper(c));this.lengthArb=restrictedIntegerArbitraryBuilder(0,maxGeneratedCommands,maxCommands);this.replayPath=[];this.replayPathPosition=0}metadataForReplay(){return this.disableReplayLog?"":`replayPath=${JSON.stringify(ReplayPath.stringify(this.replayPath))}`}buildValueFor(items2,shrunkOnce){const commands=items2.map((item)=>item.value_);const context4={shrunkOnce,items:items2};return new Value(new CommandsIterable(commands,()=>this.metadataForReplay()),context4)}generate(mrng){const sizeValue=this.lengthArb.generate(mrng,undefined).value;const items2=Array(sizeValue);for(let idx=0;idx!==sizeValue;++idx)items2[idx]=this.oneCommandArb.generate(mrng,undefined);this.replayPathPosition=0;return this.buildValueFor(items2,false)}canShrinkWithoutContext(_value){return false}filterOnExecution(itemsRaw){const items2=[];for(const c of itemsRaw)if(c.value_.hasRan){this.replayPath.push(true);items2.push(c)}else this.replayPath.push(false);return items2}filterOnReplay(itemsRaw){return itemsRaw.filter((c,idx)=>{const state=this.replayPath[this.replayPathPosition+idx];if(state===undefined)throw new Error(`Too short replayPath`);if(!state&&c.value_.hasRan)throw new Error(`Mismatch between replayPath and real execution`);return state})}filterForShrinkImpl(itemsRaw){if(this.replayPathPosition===0)this.replayPath=this.sourceReplayPath!==null?ReplayPath.parse(this.sourceReplayPath):[];const items2=this.replayPathPosition<this.replayPath.length?this.filterOnReplay(itemsRaw):this.filterOnExecution(itemsRaw);this.replayPathPosition+=itemsRaw.length;return items2}shrink(_value,context4){if(context4===undefined)return Stream.nil();const safeContext=context4;const shrunkOnce=safeContext.shrunkOnce;const itemsRaw=safeContext.items;const items2=this.filterForShrinkImpl(itemsRaw);if(items2.length===0)return Stream.nil();const rootShrink=shrunkOnce?Stream.nil():new Stream([[]][Symbol.iterator]());const nextShrinks=[];for(let numToKeep=0;numToKeep!==items2.length;++numToKeep)nextShrinks.push(makeLazy2(()=>{const fixedStart=items2.slice(0,numToKeep);return this.lengthArb.shrink(items2.length-1-numToKeep,undefined).map((l)=>fixedStart.concat(items2.slice(items2.length-(l.value+1))))}));for(let itemAt=0;itemAt!==items2.length;++itemAt)nextShrinks.push(makeLazy2(()=>this.oneCommandArb.shrink(items2[itemAt].value_,items2[itemAt].context).map((v)=>items2.slice(0,itemAt).concat([v],items2.slice(itemAt+1)))));return rootShrink.join(...nextShrinks).map((shrinkables)=>{return this.buildValueFor(shrinkables.map((c)=>new Value(c.value_.clone(),c.context)),true)})}};function commands(commandArbs,constraints={}){const{size:size6,maxCommands=MaxLengthUpperBound,disableReplayLog=false,replayPath=null}=constraints;return new CommandsArbitrary(commandArbs,maxGeneratedLengthFromSizeForArbitrary(size6,0,maxCommands,constraints.maxCommands!==undefined),maxCommands,replayPath,disableReplayLog)}var ScheduledCommand=class{constructor(s,cmd){this.s=s;this.cmd=cmd}async check(m){let error=null;let checkPassed=false;if((await this.s.scheduleSequence([{label:`check@${this.cmd.toString()}`,builder:async()=>{try{checkPassed=await Promise.resolve(this.cmd.check(m))}catch(err){error=err;throw err}}}]).task).faulty)throw error;return checkPassed}async run(m,r){let error=null;if((await this.s.scheduleSequence([{label:`run@${this.cmd.toString()}`,builder:async()=>{try{await this.cmd.run(m,r)}catch(err){error=err;throw err}}}]).task).faulty)throw error}};var scheduleCommands=function*(s,cmds){for(const cmd of cmds)yield new ScheduledCommand(s,cmd)};var genericModelRun=(s,cmds,initialValue,runCmd,then)=>{return s.then((o)=>{const{model,real}=o;let state=initialValue;for(const c of cmds)state=then(state,()=>{return runCmd(c,model,real)});return state})};var internalModelRun=(s,cmds)=>{const then=(_p,c)=>c();const setupProducer={then:(fun)=>{fun(s())}};const runSync3=(cmd,m,r)=>{if(cmd.check(m))cmd.run(m,r)};return genericModelRun(setupProducer,cmds,undefined,runSync3,then)};var isAsyncSetup=(s)=>{return typeof s.then==="function"};var internalAsyncModelRun=async(s,cmds,defaultPromise=Promise.resolve())=>{const then=(p,c)=>p.then(c);const setupProducer={then:(fun)=>{const out=s();if(isAsyncSetup(out))return out.then(fun);else return fun(out)}};const runAsync=async(cmd,m,r)=>{if(await cmd.check(m))await cmd.run(m,r)};return await genericModelRun(setupProducer,cmds,defaultPromise,runAsync,then)};function modelRun(s,cmds){internalModelRun(s,cmds)}async function asyncModelRun(s,cmds){await internalAsyncModelRun(s,cmds)}async function scheduledModelRun(scheduler,s,cmds){const scheduledCommands=scheduleCommands(scheduler,cmds);const out=internalAsyncModelRun(s,scheduledCommands,scheduler.schedule(Promise.resolve(),"startModel"));await scheduler.waitFor(out);await scheduler.waitAll()}var defaultSchedulerAct=(f)=>f();var SchedulerImplem=class SchedulerImplem2{constructor(act,taskSelector){this.act=act;this.taskSelector=taskSelector;this.lastTaskId=0;this.sourceTaskSelector=taskSelector.clone();this.scheduledTasks=[];this.triggeredTasks=[];this.scheduledWatchers=[];this[cloneMethod]=function(){return new SchedulerImplem2(this.act,this.sourceTaskSelector)}}static buildLog(reportItem){return`[task\${${reportItem.taskId}}] ${reportItem.label.length!==0?`${reportItem.schedulingType}::${reportItem.label}`:reportItem.schedulingType} ${reportItem.status}${reportItem.outputValue!==undefined?` with value ${escapeForTemplateString(reportItem.outputValue)}`:""}`}log(schedulingType,taskId,label,metadata,status,data){this.triggeredTasks.push({status,schedulingType,taskId,label,metadata,outputValue:data!==undefined?stringify(data):undefined})}scheduleInternal(schedulingType,label,task,metadata,customAct,thenTaskToBeAwaited){const taskId=++this.lastTaskId;let trigger=undefined;const scheduledPromise=new Promise((resolve4,reject)=>{trigger=()=>{const promise3=Promise.resolve(thenTaskToBeAwaited!==undefined?task.then(()=>thenTaskToBeAwaited()):task);promise3.then((data)=>{this.log(schedulingType,taskId,label,metadata,"resolved",data);resolve4(data)},(err)=>{this.log(schedulingType,taskId,label,metadata,"rejected",err);reject(err)});return promise3}});this.scheduledTasks.push({original:task,trigger,schedulingType,taskId,label,metadata,customAct});if(this.scheduledWatchers.length!==0)this.scheduledWatchers[0]();return scheduledPromise}schedule(task,label,metadata,customAct){return this.scheduleInternal("promise",label||"",task,metadata,customAct||defaultSchedulerAct)}scheduleFunction(asyncFunction,customAct){return(...args2)=>this.scheduleInternal("function",`${asyncFunction.name}(${args2.map(stringify).join(",")})`,asyncFunction(...args2),undefined,customAct||defaultSchedulerAct)}scheduleSequence(sequenceBuilders,customAct){const status={done:false,faulty:false};const dummyResolvedPromise={then:(f)=>f()};let resolveSequenceTask=()=>{};const sequenceTask=new Promise((resolve4)=>{resolveSequenceTask=()=>resolve4({done:status.done,faulty:status.faulty})});const onFaultyItemNoThrow=()=>{status.faulty=true;resolveSequenceTask()};const onDone=()=>{status.done=true;resolveSequenceTask()};const registerNextBuilder=(index2,previous)=>{if(index2>=sequenceBuilders.length){previous.then(onDone,onFaultyItemNoThrow);return}previous.then(()=>{const item=sequenceBuilders[index2];const[builder,label,metadata]=typeof item==="function"?[item,item.name,undefined]:[item.builder,item.label,item.metadata];const scheduled=this.scheduleInternal("sequence",label,dummyResolvedPromise,metadata,customAct||defaultSchedulerAct,()=>builder());registerNextBuilder(index2+1,scheduled)},onFaultyItemNoThrow)};registerNextBuilder(0,dummyResolvedPromise);return Object.assign(status,{task:sequenceTask})}count(){return this.scheduledTasks.length}internalWaitOne(){if(this.scheduledTasks.length===0)throw new Error("No task scheduled");const taskIndex=this.taskSelector.nextTaskIndex(this.scheduledTasks);const[scheduledTask]=this.scheduledTasks.splice(taskIndex,1);return scheduledTask.customAct(()=>{return scheduledTask.trigger().catch((_err)=>{})})}waitOne(customAct){const waitAct=customAct||defaultSchedulerAct;return this.act(()=>waitAct(()=>this.internalWaitOne()))}async waitAll(customAct){while(this.scheduledTasks.length>0)await this.waitOne(customAct)}async internalWaitFor(unscheduledTask,options){let taskResolved=false;const customAct=options.customAct;const onWaitStart=options.onWaitStart;const onWaitIdle=options.onWaitIdle;const launchAwaiterOnInit=options.launchAwaiterOnInit;let resolveFinal=undefined;let rejectFinal=undefined;let awaiterTicks=0;let awaiterPromise=null;let awaiterScheduledTaskPromise=null;const awaiter=async()=>{awaiterTicks=50;for(awaiterTicks=50;!taskResolved&&awaiterTicks>0;--awaiterTicks)await Promise.resolve();if(!taskResolved&&this.scheduledTasks.length>0){if(onWaitStart!==undefined)onWaitStart();awaiterScheduledTaskPromise=this.waitOne(customAct);return awaiterScheduledTaskPromise.then(()=>{awaiterScheduledTaskPromise=null;return awaiter()},(err)=>{awaiterScheduledTaskPromise=null;taskResolved=true;rejectFinal(err);throw err})}if(!taskResolved&&onWaitIdle!==undefined)onWaitIdle();awaiterPromise=null};const handleNotified=()=>{if(awaiterPromise!==null){awaiterTicks=51;return}awaiterPromise=awaiter().catch(()=>{})};const clearAndReplaceWatcher=()=>{const handleNotifiedIndex=this.scheduledWatchers.indexOf(handleNotified);if(handleNotifiedIndex!==-1)this.scheduledWatchers.splice(handleNotifiedIndex,1);if(handleNotifiedIndex===0&&this.scheduledWatchers.length!==0)this.scheduledWatchers[0]()};const finalTask=new Promise((resolve4,reject)=>{resolveFinal=(value3)=>{clearAndReplaceWatcher();resolve4(value3)};rejectFinal=(error)=>{clearAndReplaceWatcher();reject(error)}});unscheduledTask.then((ret)=>{taskResolved=true;if(awaiterScheduledTaskPromise===null)resolveFinal(ret);else awaiterScheduledTaskPromise.then(()=>resolveFinal(ret),(error)=>rejectFinal(error))},(err)=>{taskResolved=true;if(awaiterScheduledTaskPromise===null)rejectFinal(err);else awaiterScheduledTaskPromise.then(()=>rejectFinal(err),()=>rejectFinal(err))});if((this.scheduledTasks.length>0||launchAwaiterOnInit)&&this.scheduledWatchers.length===0)handleNotified();this.scheduledWatchers.push(handleNotified);return finalTask}waitNext(count,customAct){let resolver=undefined;let remaining=count;const awaited=remaining<=0?Promise.resolve():new Promise((r)=>{resolver=()=>{if(--remaining<=0)r()}});return this.internalWaitFor(awaited,{customAct,onWaitStart:resolver,onWaitIdle:undefined,launchAwaiterOnInit:false})}waitIdle(customAct){let resolver=undefined;const awaited=new Promise((r)=>resolver=r);return this.internalWaitFor(awaited,{customAct,onWaitStart:undefined,onWaitIdle:resolver,launchAwaiterOnInit:true})}waitFor(unscheduledTask,customAct){return this.internalWaitFor(unscheduledTask,{customAct,onWaitStart:undefined,onWaitIdle:undefined,launchAwaiterOnInit:false})}report(){return[...this.triggeredTasks,...this.scheduledTasks.map((t)=>({status:"pending",schedulingType:t.schedulingType,taskId:t.taskId,label:t.label,metadata:t.metadata}))]}toString(){return"schedulerFor()`\n"+this.report().map(SchedulerImplem2.buildLog).map((log2)=>`-> ${log2}`).join(`
221
+ }`}return safeObjectDefineProperties$1(f,{toString:{value:()=>prettyPrint(stringify(outs))},[toStringMethod]:{value:()=>prettyPrint(stringify(outs))},[asyncToStringMethod]:{value:async()=>prettyPrint(await asyncStringify(outs))},[cloneMethod]:{value:producer,configurable:true}})};return producer()})}var safeMinSafeInteger=Number.MIN_SAFE_INTEGER;var safeMaxSafeInteger$1=Number.MAX_SAFE_INTEGER;function maxSafeInteger(){return new IntegerArbitrary(safeMinSafeInteger,safeMaxSafeInteger$1)}var safeMaxSafeInteger=Number.MAX_SAFE_INTEGER;function maxSafeNat(){return new IntegerArbitrary(0,safeMaxSafeInteger)}var safeNumberParseInt=Number.parseInt;function natToStringifiedNatMapper(options){const[style,v]=options;switch(style){case"oct":return`0${safeNumberToString(v,8)}`;case"hex":return`0x${safeNumberToString(v,16)}`;default:return`${v}`}}function tryParseStringifiedNat(stringValue,radix){const parsedNat=safeNumberParseInt(stringValue,radix);if(safeNumberToString(parsedNat,radix)!==stringValue)throw new Error("Invalid value");return parsedNat}function natToStringifiedNatUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");if(value3.length>=2&&value3[0]==="0"){if(value3[1]==="x")return["hex",tryParseStringifiedNat(safeSubstring(value3,2),16)];return["oct",tryParseStringifiedNat(safeSubstring(value3,1),8)]}return["dec",tryParseStringifiedNat(value3,10)]}function dotJoinerMapper$1(data){return safeJoin(data,".")}function dotJoinerUnmapper$1(value3){if(typeof value3!=="string")throw new Error("Invalid type");return safeMap(safeSplit(value3,"."),(v)=>tryParseStringifiedNat(v,10))}function ipV4(){return tuple2(nat(255),nat(255),nat(255),nat(255)).map(dotJoinerMapper$1,dotJoinerUnmapper$1)}function buildStringifiedNatArbitrary(maxValue){return tuple2(constantFrom("dec","oct","hex"),nat(maxValue)).map(natToStringifiedNatMapper,natToStringifiedNatUnmapper)}function dotJoinerMapper(data){return safeJoin(data,".")}function dotJoinerUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");return safeSplit(value3,".")}function ipV4Extended(){return oneof(tuple2(buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255)).map(dotJoinerMapper,dotJoinerUnmapper),tuple2(buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(65535)).map(dotJoinerMapper,dotJoinerUnmapper),tuple2(buildStringifiedNatArbitrary(255),buildStringifiedNatArbitrary(16777215)).map(dotJoinerMapper,dotJoinerUnmapper),buildStringifiedNatArbitrary(4294967295))}function readBh(value3){if(value3.length===0)return[];else return safeSplit(value3,":")}function extractEhAndL(value3){const valueSplits=safeSplit(value3,":");if(valueSplits.length>=2&&valueSplits[valueSplits.length-1].length<=4)return[safeSlice(valueSplits,0,valueSplits.length-2),`${valueSplits[valueSplits.length-2]}:${valueSplits[valueSplits.length-1]}`];return[safeSlice(valueSplits,0,valueSplits.length-1),valueSplits[valueSplits.length-1]]}function fullySpecifiedMapper(data){return`${safeJoin(data[0],":")}:${data[1]}`}function fullySpecifiedUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");return extractEhAndL(value3)}function onlyTrailingMapper(data){return`::${safeJoin(data[0],":")}:${data[1]}`}function onlyTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");if(!safeStartsWith(value3,"::"))throw new Error("Invalid value");return extractEhAndL(safeSubstring(value3,2))}function multiTrailingMapper(data){return`${safeJoin(data[0],":")}::${safeJoin(data[1],":")}:${data[2]}`}function multiTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");const[bhString,trailingString]=safeSplit(value3,"::",2);const[eh,l]=extractEhAndL(trailingString);return[readBh(bhString),eh,l]}function multiTrailingMapperOne(data){return multiTrailingMapper([data[0],[data[1]],data[2]])}function multiTrailingUnmapperOne(value3){const out=multiTrailingUnmapper(value3);return[out[0],safeJoin(out[1],":"),out[2]]}function singleTrailingMapper(data){return`${safeJoin(data[0],":")}::${data[1]}`}function singleTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");const[bhString,trailing]=safeSplit(value3,"::",2);return[readBh(bhString),trailing]}function noTrailingMapper(data){return`${safeJoin(data[0],":")}::`}function noTrailingUnmapper(value3){if(typeof value3!=="string")throw new Error("Invalid type");if(!safeEndsWith(value3,"::"))throw new Error("Invalid value");return[readBh(safeSubstring(value3,0,value3.length-2))]}function h16sTol32Mapper([a,b]){return`${a}:${b}`}function h16sTol32Unmapper(value3){if(typeof value3!=="string")throw new SError("Invalid type");if(!value3.includes(":"))throw new SError("Invalid value");return value3.split(":",2)}var items="0123456789abcdef";var cachedHexa=undefined;function hexa(){if(cachedHexa===undefined)cachedHexa=integer({min:0,max:15}).map((n)=>items[n],(c)=>{if(typeof c!=="string")throw new SError("Not a string");if(c.length!==1)throw new SError("Invalid length");const code=safeCharCodeAt(c,0);if(code<=57)return code-48;if(code<97)throw new SError("Invalid character");return code-87});return cachedHexa}function ipV6(){const h16Arb=string3({unit:hexa(),minLength:1,maxLength:4,size:"max"});const ls32Arb=oneof(tuple2(h16Arb,h16Arb).map(h16sTol32Mapper,h16sTol32Unmapper),ipV4());return oneof(tuple2(array3(h16Arb,{minLength:6,maxLength:6,size:"max"}),ls32Arb).map(fullySpecifiedMapper,fullySpecifiedUnmapper),tuple2(array3(h16Arb,{minLength:5,maxLength:5,size:"max"}),ls32Arb).map(onlyTrailingMapper,onlyTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:1,size:"max"}),array3(h16Arb,{minLength:4,maxLength:4,size:"max"}),ls32Arb).map(multiTrailingMapper,multiTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:2,size:"max"}),array3(h16Arb,{minLength:3,maxLength:3,size:"max"}),ls32Arb).map(multiTrailingMapper,multiTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:3,size:"max"}),array3(h16Arb,{minLength:2,maxLength:2,size:"max"}),ls32Arb).map(multiTrailingMapper,multiTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:4,size:"max"}),h16Arb,ls32Arb).map(multiTrailingMapperOne,multiTrailingUnmapperOne),tuple2(array3(h16Arb,{minLength:0,maxLength:5,size:"max"}),ls32Arb).map(singleTrailingMapper,singleTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:6,size:"max"}),h16Arb).map(singleTrailingMapper,singleTrailingUnmapper),tuple2(array3(h16Arb,{minLength:0,maxLength:7,size:"max"})).map(noTrailingMapper,noTrailingUnmapper))}var LazyArbitrary=class extends Arbitrary{constructor(name){super();this.name=name;this.underlying=null}generate(mrng,biasFactor){if(this.underlying===null)throw new Error(`Lazy arbitrary ${JSON.stringify(this.name)} not correctly initialized`);return this.underlying.generate(mrng,biasFactor)}canShrinkWithoutContext(value3){if(this.underlying===null)throw new Error(`Lazy arbitrary ${JSON.stringify(this.name)} not correctly initialized`);return this.underlying.canShrinkWithoutContext(value3)}shrink(value3,context4){if(this.underlying===null)throw new Error(`Lazy arbitrary ${JSON.stringify(this.name)} not correctly initialized`);return this.underlying.shrink(value3,context4)}};var safeGetOwnPropertyNames=Object.getOwnPropertyNames;function createLazyArbsPool(){const lazyArbsPool=new SMap$1;const getLazyFromPool=(key)=>{let lazyArb=safeMapGet(lazyArbsPool,key);if(lazyArb!==undefined)return lazyArb;lazyArb=new LazyArbitrary(String(key));safeMapSet(lazyArbsPool,key,lazyArb);return lazyArb};return getLazyFromPool}function letrec(builder){const getLazyFromPool=createLazyArbsPool();const strictArbs=builder(getLazyFromPool);const declaredArbitraryNames=safeGetOwnPropertyNames(strictArbs);for(const name of declaredArbitraryNames){const lazyArb=getLazyFromPool(name);lazyArb.underlying=strictArbs[name]}return strictArbs}function canHaveAtLeastOneItem(keys3,constraints){for(const key of keys3){const constraintsOnKey=constraints[key]||{};if(constraintsOnKey.maxLength===undefined||constraintsOnKey.maxLength>0)return true}return false}function initialPoolForEntityGraph(keys3,constraints){if(keys3.length===0)return constant2([]);if(!canHaveAtLeastOneItem(keys3,constraints))throw new SError("Contraints on pool must accept at least one entity, maxLength cannot sum to 0");return tuple2(...keys3.map((key)=>array3(constant2(key),constraints[key]))).map((values3)=>safeFlat(values3)).filter((names)=>names.length>0)}var safeObjectAssign$1=Object.assign;var safeObjectCreate$4=Object.create;var safeObjectDefineProperty$1=Object.defineProperty;var safeObjectGetPrototypeOf=Object.getPrototypeOf;var safeObjectPrototype=Object.prototype;function withTargetStringifiedValue(stringifiedValue){return safeObjectDefineProperty$1(safeObjectCreate$4(null),toStringMethod,{configurable:false,enumerable:false,writable:false,value:()=>stringifiedValue})}function withReferenceStringifiedValue(type,index2){return withTargetStringifiedValue(`<${SString(type)}#${index2}>`)}function unlinkedToLinkedEntitiesMapper(unlinkedEntities,producedLinks){const linkedEntities=safeObjectCreate$4(safeObjectPrototype);for(const name in unlinkedEntities){const unlinkedEntitiesForName=unlinkedEntities[name];const linkedEntitiesForName=[];for(const unlinkedEntity of unlinkedEntitiesForName){const linkedEntity=safeObjectAssign$1(safeObjectCreate$4(safeObjectGetPrototypeOf(unlinkedEntity)),unlinkedEntity);linkedEntitiesForName.push(linkedEntity)}linkedEntities[name]=linkedEntitiesForName}for(const name in producedLinks){const entityLinks=producedLinks[name];for(let entityIndex=0;entityIndex!==entityLinks.length;++entityIndex){const entityLinksForInstance=entityLinks[entityIndex];const linkedInstance=linkedEntities[name][entityIndex];for(const prop in entityLinksForInstance){const propValue=entityLinksForInstance[prop];linkedInstance[prop]=propValue.index===undefined?undefined:typeof propValue.index==="number"?linkedEntities[propValue.type][propValue.index]:safeMap(propValue.index,(index2)=>linkedEntities[propValue.type][index2])}safeObjectDefineProperty$1(linkedInstance,toStringMethod,{configurable:false,enumerable:false,writable:false,value:()=>{const unlinkedEntity=unlinkedEntities[name][entityIndex];const entity=safeObjectAssign$1(safeObjectCreate$4(safeObjectGetPrototypeOf(unlinkedEntity)),unlinkedEntity);for(const prop in entityLinksForInstance){const propValue=entityLinksForInstance[prop];entity[prop]=propValue.index===undefined?undefined:typeof propValue.index==="number"?withReferenceStringifiedValue(propValue.type,propValue.index):safeMap(propValue.index,(index2)=>withReferenceStringifiedValue(propValue.type,index2))}return stringify(entity)}})}}return linkedEntities}function buildInversedRelationsMapping(relations){let foundInversedRelations=0;const requestedInversedRelations=new SMap$1;for(const name in relations){const relationsForName=relations[name];for(const fieldName in relationsForName){const relation=relationsForName[fieldName];if(relation.arity!=="inverse")continue;let existingOnes=safeMapGet(requestedInversedRelations,relation.type);if(existingOnes===undefined){existingOnes=new SMap$1;safeMapSet(requestedInversedRelations,relation.type,existingOnes)}if(safeMapHas(existingOnes,relation.forwardRelationship))throw new SError(`Cannot declare multiple inverse relationships for the same forward relationship ${SString(relation.forwardRelationship)} on type ${SString(relation.type)}`);safeMapSet(existingOnes,relation.forwardRelationship,{type:name,property:fieldName});foundInversedRelations+=1}}const inversedRelations=new SMap$1;if(foundInversedRelations===0)return inversedRelations;for(const name in relations){const relationsForName=relations[name];const requestedInversedRelationsForName=safeMapGet(requestedInversedRelations,name);if(requestedInversedRelationsForName===undefined)continue;for(const fieldName in relationsForName){const relation=relationsForName[fieldName];if(relation.arity==="inverse")continue;const requestedIfAny=safeMapGet(requestedInversedRelationsForName,fieldName);if(requestedIfAny===undefined)continue;if(requestedIfAny.type!==relation.type)throw new SError(`Inverse relationship ${SString(requestedIfAny.property)} on type ${SString(requestedIfAny.type)} references forward relationship ${SString(fieldName)} but types do not match`);safeMapSet(inversedRelations,relation,requestedIfAny)}}if(inversedRelations.size!==foundInversedRelations)throw new SError(`Some inverse relationships could not be matched with their corresponding forward relationships`);return inversedRelations}var safeObjectAssign=Object.assign;var safeObjectCreate$3=Object.create;function produceLinkUnitaryIndexArbitrary(strategy,currentIndexIfSameType,countInTargetType){switch(strategy){case"exclusive":return constant2(countInTargetType);case"successor":return noBias(integer({min:currentIndexIfSameType!==undefined?currentIndexIfSameType+1:0,max:countInTargetType}));case"any":return noBias(integer({min:0,max:countInTargetType}))}}function buildLinkIndexArbitrary(arity,strategy,currentIndexIfSameType,countInTargetType,currentEntityDepth){const linkArbitrary=produceLinkUnitaryIndexArbitrary(strategy,currentIndexIfSameType,countInTargetType);switch(arity){case"0-1":return option3(linkArbitrary,{nil:undefined,depthIdentifier:currentEntityDepth});case"1":return linkArbitrary;case"many":{let randomUnicity=0;return option3(uniqueArray(linkArbitrary,{depthIdentifier:currentEntityDepth,selector:(v)=>v===countInTargetType?v+ ++randomUnicity:v,minLength:1}),{nil:[],depthIdentifier:currentEntityDepth}).map((values3)=>{let offset=0;return safeMap(values3,(v)=>v===countInTargetType?v+offset++:v)})}}}function createEmptyLinksInstanceFor(relations,targetType){const emptyLinksInstance=safeObjectCreate$3(null);const relationsForType=relations[targetType];for(const name in relationsForType){const relation=relationsForType[name];if(relation.arity==="inverse")emptyLinksInstance[name]={type:relation.type,index:[]}}return emptyLinksInstance}function assertAcceptableRelations(relations){const nonExclusiveEntities=new SSet;const exclusiveEntities=new SSet;for(const name in relations){const relationsForName=relations[name];for(const fieldName in relationsForName){const relation=relationsForName[fieldName];if(relation.arity==="inverse")continue;if(relation.strategy==="exclusive"){if(safeHas(nonExclusiveEntities,relation.type))throw new SError(`Cannot mix exclusive with other strategies for type ${SString(relation.type)}`);safeAdd(exclusiveEntities,relation.type)}else{if(safeHas(exclusiveEntities,relation.type))throw new SError(`Cannot mix exclusive with other strategies for type ${SString(relation.type)}`);safeAdd(nonExclusiveEntities,relation.type)}if(relation.strategy==="successor"&&relation.type!==name)throw new SError(`Cannot mix types for the strategy successor`);if(relation.strategy==="successor"&&relation.arity==="1")throw new SError(`Cannot use an arity of 1 for the strategy successor`)}}}function draftNextProductionState(state,offset){const{producedLinks,toBeProducedEntities}=state;const nextIndex=state.nextIndex+offset;const newProducedLinks=safeObjectAssign(safeObjectCreate$3(null),producedLinks);function getOrCreateProducedLinksFor(type){if(newProducedLinks[type]===producedLinks[type])newProducedLinks[type]=safeSlice(producedLinks[type]);return newProducedLinks[type]}function getOrCreateLinksFor(type,indexInType){const producedLinksForType=getOrCreateProducedLinksFor(type);if(producedLinksForType[indexInType]===producedLinks[type][indexInType])producedLinksForType[indexInType]=safeObjectAssign(safeObjectCreate$3(null),producedLinks[type][indexInType]);return producedLinksForType[indexInType]}function getOrCreateRelationFor(type,indexInType,property2){const links=getOrCreateLinksFor(type,indexInType);const originalEntity=producedLinks[type][indexInType];if(originalEntity!==undefined&&links[property2]===originalEntity[property2]){const sharedRelation=links[property2];links[property2]={type:sharedRelation.type,index:typeof sharedRelation.index==="object"?safeSlice(sharedRelation.index):sharedRelation.index}}return links[property2]}let newToBeProducedEntities=undefined;const toBeProduced=toBeProducedEntities[nextIndex];return{setOutboundLink:(name,value3)=>{const currentLinks=getOrCreateLinksFor(toBeProduced.type,toBeProduced.indexInType);currentLinks[name]=value3},enqueueNewEntity:(relations,targetType)=>{const producedLinksInTargetType=getOrCreateProducedLinksFor(targetType);const newEntityIndexInType=producedLinksInTargetType.length;if(newToBeProducedEntities===undefined)newToBeProducedEntities=safeSlice(toBeProducedEntities);safePush(newToBeProducedEntities,{type:targetType,indexInType:newEntityIndexInType,depth:toBeProduced.depth+1});safePush(producedLinksInTargetType,createEmptyLinksInstanceFor(relations,targetType));return newEntityIndexInType},appendBackReference:(targetType,indexInType,property2)=>{const knownInversedLinks=getOrCreateRelationFor(targetType,indexInType,property2).index;safePush(knownInversedLinks,toBeProduced.indexInType)},commit:()=>({producedLinks:newProducedLinks,toBeProducedEntities:newToBeProducedEntities!==undefined?newToBeProducedEntities:toBeProducedEntities,nextIndex:nextIndex+1})}}function buildInitialProductionState(relations,defaultEntities){const producedLinks=safeObjectCreate$3(null);for(const name in relations)producedLinks[name]=[];const toBeProducedEntities=[];for(const name of defaultEntities){safePush(toBeProducedEntities,{type:name,indexInType:producedLinks[name].length,depth:0});safePush(producedLinks[name],createEmptyLinksInstanceFor(relations,name))}return{producedLinks,toBeProducedEntities,nextIndex:0}}function buildEntityStepArbitrary(relations,inversedRelations,lastState,offset){const lastProducedLinks=lastState.producedLinks;const currentEntity=lastState.toBeProducedEntities[lastState.nextIndex+offset];const currentRelations=relations[currentEntity.type];const currentEntityDepth=createDepthIdentifier();currentEntityDepth.depth=currentEntity.depth;const subArbitraries=[];const linkContexts=[];for(const name in currentRelations){const relation=currentRelations[name];if(relation.arity==="inverse")continue;const targetType=relation.type;const countInTargetType=lastProducedLinks[targetType].length;safePush(subArbitraries,buildLinkIndexArbitrary(relation.arity,relation.strategy||"any",targetType===currentEntity.type?currentEntity.indexInType:undefined,countInTargetType,currentEntityDepth));safePush(linkContexts,{name,relation,sentinelLinkIndex:countInTargetType})}if(subArbitraries.length===0)return;return tuple2(...subArbitraries).map((results)=>{const state=draftNextProductionState(lastState,offset);for(let resultIndex=0;resultIndex!==results.length;++resultIndex){const linkOrLinks=results[resultIndex];const{name,relation,sentinelLinkIndex}=linkContexts[resultIndex];const effectiveLinks=[];const links=linkOrLinks===undefined?[]:typeof linkOrLinks==="number"?[linkOrLinks]:linkOrLinks;for(const link of links){let newEntityIndexInType;if(link>=sentinelLinkIndex)newEntityIndexInType=state.enqueueNewEntity(relations,relation.type);else newEntityIndexInType=link;safePush(effectiveLinks,newEntityIndexInType);const inversed=safeMapGet(inversedRelations,relation);if(inversed!==undefined)state.appendBackReference(relation.type,newEntityIndexInType,inversed.property)}state.setOutboundLink(name,{type:relation.type,index:linkOrLinks===undefined?undefined:typeof linkOrLinks==="number"?effectiveLinks[0]:effectiveLinks})}return state.commit()})}function onTheFlyLinksForEntityGraph(relations,defaultEntities){assertAcceptableRelations(relations);const inversedRelations=buildInversedRelationsMapping(relations);return chainUntil(constant2(buildInitialProductionState(relations,defaultEntities)),(state)=>{if(state.nextIndex>=state.toBeProducedEntities.length)return;let offset=0;let next=undefined;while(next===undefined&&state.nextIndex+offset<state.toBeProducedEntities.length){next=buildEntityStepArbitrary(relations,inversedRelations,state,offset);offset+=1}return next}).map((state)=>{return state.producedLinks})}var safeObjectKeys$1=Object.keys;var safeObjectGetOwnPropertySymbols$1=Object.getOwnPropertySymbols;var safeObjectGetOwnPropertyDescriptor$1=Object.getOwnPropertyDescriptor;function extractEnumerableKeys(instance){const keys3=safeObjectKeys$1(instance);const symbols=safeObjectGetOwnPropertySymbols$1(instance);for(let index2=0;index2!==symbols.length;++index2){const symbol4=symbols[index2];const descriptor=safeObjectGetOwnPropertyDescriptor$1(instance,symbol4);if(descriptor&&descriptor.enumerable)keys3.push(symbol4)}return keys3}var safeObjectCreate$2=Object.create;var safeObjectDefineProperty=Object.defineProperty;var safeObjectGetOwnPropertyDescriptor=Object.getOwnPropertyDescriptor;var safeObjectGetOwnPropertyNames=Object.getOwnPropertyNames;var safeObjectGetOwnPropertySymbols=Object.getOwnPropertySymbols;function buildValuesAndSeparateKeysToObjectMapper(keys3,noKeyValue){return function valuesAndSeparateKeysToObjectMapper(definition){const obj=definition[definition.length-1]?safeObjectCreate$2(null):{};for(let idx=0;idx!==keys3.length;++idx){const valueWrapper=definition[idx];if(valueWrapper!==noKeyValue){const key=keys3[idx];if(key==="__proto__")safeObjectDefineProperty(obj,key,{value:valueWrapper,configurable:true,enumerable:true,writable:true});else obj[key]=valueWrapper}}return obj}}function buildValuesAndSeparateKeysToObjectUnmapper(keys3,noKeyValue){return function valuesAndSeparateKeysToObjectUnmapper(value3){if(typeof value3!=="object"||value3===null)throw new Error("Incompatible instance received: should be a non-null object");const hasNullPrototype=Object.getPrototypeOf(value3)===null;const hasObjectPrototype="constructor"in value3&&value3.constructor===Object;if(!hasNullPrototype&&!hasObjectPrototype)throw new Error("Incompatible instance received: should be of exact type Object");let extractedPropertiesCount=0;const extractedValues=[];for(let idx=0;idx!==keys3.length;++idx){const descriptor=safeObjectGetOwnPropertyDescriptor(value3,keys3[idx]);if(descriptor!==undefined){if(!descriptor.configurable||!descriptor.enumerable||!descriptor.writable)throw new Error("Incompatible instance received: should contain only c/e/w properties");if(descriptor.get!==undefined||descriptor.set!==undefined)throw new Error("Incompatible instance received: should contain only no get/set properties");++extractedPropertiesCount;safePush(extractedValues,descriptor.value)}else safePush(extractedValues,noKeyValue)}const namePropertiesCount=safeObjectGetOwnPropertyNames(value3).length;const symbolPropertiesCount=safeObjectGetOwnPropertySymbols(value3).length;if(extractedPropertiesCount!==namePropertiesCount+symbolPropertiesCount)throw new Error("Incompatible instance received: should not contain extra properties");return[...extractedValues,hasNullPrototype]}}var noKeyValue=Symbol("no-key");function buildPartialRecordArbitrary(recordModel,requiredKeys,noNullPrototype){const keys3=extractEnumerableKeys(recordModel);const arbs=[];for(let index2=0;index2!==keys3.length;++index2){const k=keys3[index2];const requiredArbitrary=recordModel[k];if(requiredKeys===undefined||safeIndexOf(requiredKeys,k)!==-1)safePush(arbs,requiredArbitrary);else safePush(arbs,option3(requiredArbitrary,{nil:noKeyValue}))}return tuple2(...arbs,noNullPrototype?constant2(false):boolean2()).map(buildValuesAndSeparateKeysToObjectMapper(keys3,noKeyValue),buildValuesAndSeparateKeysToObjectUnmapper(keys3,noKeyValue))}function record2(recordModel,constraints){const noNullPrototype=constraints!==undefined&&!!constraints.noNullPrototype;if(constraints===undefined)return buildPartialRecordArbitrary(recordModel,undefined,noNullPrototype);if(!(("requiredKeys"in constraints)&&constraints.requiredKeys!==undefined))return buildPartialRecordArbitrary(recordModel,undefined,noNullPrototype);const requiredKeys=("requiredKeys"in constraints?constraints.requiredKeys:undefined)||[];for(let idx=0;idx!==requiredKeys.length;++idx){const descriptor=Object.getOwnPropertyDescriptor(recordModel,requiredKeys[idx]);if(descriptor===undefined)throw new Error(`requiredKeys cannot reference keys that have not been defined in recordModel`);if(!descriptor.enumerable)throw new Error(`requiredKeys cannot reference keys that are not enumerable in recordModel`)}return buildPartialRecordArbitrary(recordModel,requiredKeys,noNullPrototype)}var safeObjectCreate$1=Object.create;function unlinkedEntitiesForEntityGraph(arbitraries,countFor,unicityConstraintsFor,constraints){const recordModel=safeObjectCreate$1(null);for(const name in arbitraries){const entityRecordModel=arbitraries[name];const entityArbitrary=record2(entityRecordModel,constraints);const count=countFor(name);const unicityConstraints=unicityConstraintsFor(name);const arrayConstraints={minLength:count,maxLength:count};recordModel[name]=unicityConstraints!==undefined?uniqueArray(entityArbitrary,{...arrayConstraints,selector:unicityConstraints}):array3(entityArbitrary,arrayConstraints)}return record2(recordModel)}var safeObjectCreate=Object.create;var safeObjectKeys=Object.keys;function entityGraph(arbitraries,relations,constraints={}){const allKeys=safeObjectKeys(arbitraries);const initialPoolConstraints=constraints.initialPoolConstraints||safeObjectCreate(null);const unicityConstraints=constraints.unicityConstraints||safeObjectCreate(null);const unlinkedContraints={noNullPrototype:constraints.noNullPrototype};return initialPoolForEntityGraph(allKeys,initialPoolConstraints).chain((defaultEntities)=>onTheFlyLinksForEntityGraph(relations,defaultEntities).chain((producedLinks)=>unlinkedEntitiesForEntityGraph(arbitraries,(name)=>producedLinks[name].length,(name)=>unicityConstraints[name],unlinkedContraints).map((unlinkedEntities)=>unlinkedToLinkedEntitiesMapper(unlinkedEntities,producedLinks))))}function wordsToJoinedStringMapper(words){return safeJoin(safeMap(words,(w)=>w[w.length-1]===","?safeSubstring(w,0,w.length-1):w)," ")}function wordsToJoinedStringUnmapperFor(wordsArbitrary){return function wordsToJoinedStringUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");const words=[];for(const candidate of safeSplit(value3," "))if(wordsArbitrary.canShrinkWithoutContext(candidate))safePush(words,candidate);else if(wordsArbitrary.canShrinkWithoutContext(candidate+","))safePush(words,candidate+",");else throw new Error("Unsupported word");return words}}function wordsToSentenceMapper(words){let sentence=safeJoin(words," ");if(sentence[sentence.length-1]===",")sentence=safeSubstring(sentence,0,sentence.length-1);return safeToUpperCase(sentence[0])+safeSubstring(sentence,1)+"."}function wordsToSentenceUnmapperFor(wordsArbitrary){return function wordsToSentenceUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");if(value3.length<2||value3[value3.length-1]!=="."||value3[value3.length-2]===","||safeToUpperCase(safeToLowerCase(value3[0]))!==value3[0])throw new Error("Unsupported value");const adaptedValue=safeToLowerCase(value3[0])+safeSubstring(value3,1,value3.length-1);const words=[];const candidates=safeSplit(adaptedValue," ");for(let idx=0;idx!==candidates.length;++idx){const candidate=candidates[idx];if(wordsArbitrary.canShrinkWithoutContext(candidate))safePush(words,candidate);else if(idx===candidates.length-1&&wordsArbitrary.canShrinkWithoutContext(candidate+","))safePush(words,candidate+",");else throw new Error("Unsupported word")}return words}}function sentencesToParagraphMapper(sentences){return safeJoin(sentences," ")}function sentencesToParagraphUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");const sentences=safeSplit(value3,". ");for(let idx=0;idx<sentences.length-1;++idx)sentences[idx]+=".";return sentences}var h=(v,w)=>{return{arbitrary:constant2(v),weight:w}};function loremWord(){return oneof(h("non",6),h("adipiscing",5),h("ligula",5),h("enim",5),h("pellentesque",5),h("in",5),h("augue",5),h("et",5),h("nulla",5),h("lorem",4),h("sit",4),h("sed",4),h("diam",4),h("fermentum",4),h("ut",4),h("eu",4),h("aliquam",4),h("mauris",4),h("vitae",4),h("felis",4),h("ipsum",3),h("dolor",3),h("amet,",3),h("elit",3),h("euismod",3),h("mi",3),h("orci",3),h("erat",3),h("praesent",3),h("egestas",3),h("leo",3),h("vel",3),h("sapien",3),h("integer",3),h("curabitur",3),h("convallis",3),h("purus",3),h("risus",2),h("suspendisse",2),h("lectus",2),h("nec,",2),h("ultricies",2),h("sed,",2),h("cras",2),h("elementum",2),h("ultrices",2),h("maecenas",2),h("massa,",2),h("varius",2),h("a,",2),h("semper",2),h("proin",2),h("nec",2),h("nisl",2),h("amet",2),h("duis",2),h("congue",2),h("libero",2),h("vestibulum",2),h("pede",2),h("blandit",2),h("sodales",2),h("ante",2),h("nibh",2),h("ac",2),h("aenean",2),h("massa",2),h("suscipit",2),h("sollicitudin",2),h("fusce",2),h("tempus",2),h("aliquam,",2),h("nunc",2),h("ullamcorper",2),h("rhoncus",2),h("metus",2),h("faucibus,",2),h("justo",2),h("magna",2),h("at",2),h("tincidunt",2),h("consectetur",1),h("tortor,",1),h("dignissim",1),h("congue,",1),h("non,",1),h("porttitor,",1),h("nonummy",1),h("molestie,",1),h("est",1),h("eleifend",1),h("mi,",1),h("arcu",1),h("scelerisque",1),h("vitae,",1),h("consequat",1),h("in,",1),h("pretium",1),h("volutpat",1),h("pharetra",1),h("tempor",1),h("bibendum",1),h("odio",1),h("dui",1),h("primis",1),h("faucibus",1),h("luctus",1),h("posuere",1),h("cubilia",1),h("curae,",1),h("hendrerit",1),h("velit",1),h("mauris,",1),h("gravida",1),h("ornare",1),h("ut,",1),h("pulvinar",1),h("varius,",1),h("turpis",1),h("nibh,",1),h("eros",1),h("id",1),h("aliquet",1),h("quis",1),h("lobortis",1),h("consectetuer",1),h("morbi",1),h("vehicula",1),h("tortor",1),h("tellus,",1),h("id,",1),h("eu,",1),h("quam",1),h("feugiat,",1),h("posuere,",1),h("iaculis",1),h("lectus,",1),h("tristique",1),h("mollis,",1),h("nisl,",1),h("vulputate",1),h("sem",1),h("vivamus",1),h("placerat",1),h("imperdiet",1),h("cursus",1),h("rutrum",1),h("iaculis,",1),h("augue,",1),h("lacus",1))}function lorem(constraints={}){const{maxCount,mode="words",size:size6}=constraints;if(maxCount!==undefined&&maxCount<1)throw new Error(`lorem has to produce at least one word/sentence`);const wordArbitrary=loremWord();if(mode==="sentences")return array3(array3(wordArbitrary,{minLength:1,size:"small"}).map(wordsToSentenceMapper,wordsToSentenceUnmapperFor(wordArbitrary)),{minLength:1,maxLength:maxCount,size:size6}).map(sentencesToParagraphMapper,sentencesToParagraphUnmapper);else return array3(wordArbitrary,{minLength:1,maxLength:maxCount,size:size6}).map(wordsToJoinedStringMapper,wordsToJoinedStringUnmapperFor(wordArbitrary))}function arrayToMapMapper(data){return new Map(data)}function arrayToMapUnmapper(value3){if(typeof value3!=="object"||value3===null)throw new Error("Incompatible instance received: should be a non-null object");if(!("constructor"in value3)||value3.constructor!==Map)throw new Error("Incompatible instance received: should be of exact type Map");return Array.from(value3)}function mapKeyExtractor(entry){return entry[0]}function map13(keyArb,valueArb,constraints={}){return uniqueArray(tuple2(keyArb,valueArb),{minLength:constraints.minKeys,maxLength:constraints.maxKeys,size:constraints.size,selector:mapKeyExtractor,depthIdentifier:constraints.depthIdentifier,comparator:"SameValueZero"}).map(arrayToMapMapper,arrayToMapUnmapper)}var contextRemainingDepth=10;function memo(builder){const previous={};return(maxDepth)=>{const n=maxDepth!==undefined?maxDepth:contextRemainingDepth;if(!safeHasOwnProperty(previous,n)){const prev=contextRemainingDepth;contextRemainingDepth=n-1;previous[n]=builder(n);contextRemainingDepth=prev}return previous[n]}}function countToggledBits(n){let count=0;while(n>SBigInt2(0)){if(n&SBigInt2(1))++count;n>>=SBigInt2(1)}return count}function computeNextFlags(flags,nextSize){const allowedMask=(SBigInt2(1)<<SBigInt2(nextSize))-SBigInt2(1);const preservedFlags=flags&allowedMask;let numMissingFlags=countToggledBits(flags-preservedFlags);let nFlags=preservedFlags;for(let mask2=SBigInt2(1);mask2<=allowedMask&&numMissingFlags!==0;mask2<<=SBigInt2(1))if(!(nFlags&mask2)){nFlags|=mask2;--numMissingFlags}return nFlags}function computeTogglePositions(chars,toggleCase){const positions=[];for(let idx=chars.length-1;idx!==-1;--idx)if(toggleCase(chars[idx])!==chars[idx])safePush(positions,idx);return positions}function computeFlagsFromChars(untoggledChars,toggledChars,togglePositions){let flags=SBigInt2(0);for(let idx=0,mask2=SBigInt2(1);idx!==togglePositions.length;++idx,mask2<<=SBigInt2(1))if(untoggledChars[togglePositions[idx]]!==toggledChars[togglePositions[idx]])flags|=mask2;return flags}function applyFlagsOnChars(chars,flags,togglePositions,toggleCase){for(let idx=0,mask2=SBigInt2(1);idx!==togglePositions.length;++idx,mask2<<=SBigInt2(1))if(flags&mask2)chars[togglePositions[idx]]=toggleCase(chars[togglePositions[idx]])}var MixedCaseArbitrary=class extends Arbitrary{constructor(stringArb,toggleCase,untoggleAll){super();this.stringArb=stringArb;this.toggleCase=toggleCase;this.untoggleAll=untoggleAll}buildContextFor(rawStringValue,flagsValue){return{rawString:rawStringValue.value,rawStringContext:rawStringValue.context,flags:flagsValue.value,flagsContext:flagsValue.context}}generate(mrng,biasFactor){const rawStringValue=this.stringArb.generate(mrng,biasFactor);const chars=[...rawStringValue.value];const togglePositions=computeTogglePositions(chars,this.toggleCase);const flagsValue=bigInt2(SBigInt2(0),(SBigInt2(1)<<SBigInt2(togglePositions.length))-SBigInt2(1)).generate(mrng,undefined);applyFlagsOnChars(chars,flagsValue.value,togglePositions,this.toggleCase);return new Value(safeJoin(chars,""),this.buildContextFor(rawStringValue,flagsValue))}canShrinkWithoutContext(value3){if(typeof value3!=="string")return false;return this.untoggleAll!==undefined?this.stringArb.canShrinkWithoutContext(this.untoggleAll(value3)):this.stringArb.canShrinkWithoutContext(value3)}shrink(value3,context4){let contextSafe;if(context4!==undefined)contextSafe=context4;else if(this.untoggleAll!==undefined){const untoggledValue=this.untoggleAll(value3);const valueChars=[...value3];const untoggledValueChars=[...untoggledValue];contextSafe={rawString:untoggledValue,rawStringContext:undefined,flags:computeFlagsFromChars(untoggledValueChars,valueChars,computeTogglePositions(untoggledValueChars,this.toggleCase)),flagsContext:undefined}}else contextSafe={rawString:value3,rawStringContext:undefined,flags:SBigInt2(0),flagsContext:undefined};const rawString=contextSafe.rawString;const flags=contextSafe.flags;return this.stringArb.shrink(rawString,contextSafe.rawStringContext).map((nRawStringValue)=>{const nChars=[...nRawStringValue.value];const nTogglePositions=computeTogglePositions(nChars,this.toggleCase);const nFlags=computeNextFlags(flags,nTogglePositions.length);applyFlagsOnChars(nChars,nFlags,nTogglePositions,this.toggleCase);return new Value(safeJoin(nChars,""),this.buildContextFor(nRawStringValue,new Value(nFlags,undefined)))}).join(makeLazy2(()=>{const chars=[...rawString];const togglePositions=computeTogglePositions(chars,this.toggleCase);return bigInt2(SBigInt2(0),(SBigInt2(1)<<SBigInt2(togglePositions.length))-SBigInt2(1)).shrink(flags,contextSafe.flagsContext).map((nFlagsValue)=>{const nChars=safeSlice(chars);applyFlagsOnChars(nChars,nFlagsValue.value,togglePositions,this.toggleCase);return new Value(safeJoin(nChars,""),this.buildContextFor(new Value(rawString,contextSafe.rawStringContext),nFlagsValue))})}))}};function defaultToggleCase(rawChar){const upper=safeToUpperCase(rawChar);if(upper!==rawChar)return upper;return safeToLowerCase(rawChar)}function mixedCase(stringArb,constraints){return new MixedCaseArbitrary(stringArb,constraints&&constraints.toggleCase||defaultToggleCase,constraints&&constraints.untoggleAll)}function toTypedMapper$1(data){return SFloat32Array.from(data)}function fromTypedUnmapper$1(value3){if(!(value3 instanceof SFloat32Array))throw new Error("Unexpected type");return[...value3]}function float32Array(constraints={}){return array3(float(constraints),constraints).map(toTypedMapper$1,fromTypedUnmapper$1)}function toTypedMapper(data){return SFloat64Array.from(data)}function fromTypedUnmapper(value3){if(!(value3 instanceof SFloat64Array))throw new Error("Unexpected type");return[...value3]}function float64Array(constraints={}){return array3(double(constraints),constraints).map(toTypedMapper,fromTypedUnmapper)}function typedIntArrayArbitraryArbitraryBuilder(constraints,defaultMin,defaultMax,TypedArrayClass,arbitraryBuilder){const generatorName=TypedArrayClass.name;const{min:min5=defaultMin,max:max5=defaultMax,...arrayConstraints}=constraints;if(min5>max5)throw new Error(`Invalid range passed to ${generatorName}: min must be lower than or equal to max`);if(min5<defaultMin)throw new Error(`Invalid min value passed to ${generatorName}: min must be greater than or equal to ${defaultMin}`);if(max5>defaultMax)throw new Error(`Invalid max value passed to ${generatorName}: max must be lower than or equal to ${defaultMax}`);return array3(arbitraryBuilder({min:min5,max:max5}),arrayConstraints).map((data)=>TypedArrayClass.from(data),(value3)=>{if(!(value3 instanceof TypedArrayClass))throw new Error("Invalid type");return[...value3]})}function int16Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,-32768,32767,SInt16Array,integer)}function int32Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,-2147483648,2147483647,SInt32Array,integer)}function int8Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,-128,127,SInt8Array,integer)}function uint16Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,65535,SUint16Array,integer)}function uint32Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,4294967295,SUint32Array,integer)}function uint8Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,255,SUint8Array,integer)}function uint8ClampedArray(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,0,255,SUint8ClampedArray,integer)}function isSafeContext(context4){return context4!==undefined}function toGeneratorValue(value3){if(value3.hasToBeCloned)return new Value(value3.value_,{generatorContext:value3.context},()=>value3.value);return new Value(value3.value_,{generatorContext:value3.context})}function toShrinkerValue(value3){if(value3.hasToBeCloned)return new Value(value3.value_,{shrinkerContext:value3.context},()=>value3.value);return new Value(value3.value_,{shrinkerContext:value3.context})}var WithShrinkFromOtherArbitrary=class extends Arbitrary{constructor(generatorArbitrary,shrinkerArbitrary){super();this.generatorArbitrary=generatorArbitrary;this.shrinkerArbitrary=shrinkerArbitrary}generate(mrng,biasFactor){return toGeneratorValue(this.generatorArbitrary.generate(mrng,biasFactor))}canShrinkWithoutContext(value3){return this.shrinkerArbitrary.canShrinkWithoutContext(value3)}shrink(value3,context4){if(!isSafeContext(context4))return this.shrinkerArbitrary.shrink(value3,undefined).map(toShrinkerValue);if("generatorContext"in context4)return this.generatorArbitrary.shrink(value3,context4.generatorContext).map(toGeneratorValue);return this.shrinkerArbitrary.shrink(value3,context4.shrinkerContext).map(toShrinkerValue)}};function restrictedIntegerArbitraryBuilder(min5,maxGenerated,max5){const generatorArbitrary=integer({min:min5,max:maxGenerated});if(maxGenerated===max5)return generatorArbitrary;return new WithShrinkFromOtherArbitrary(generatorArbitrary,integer({min:min5,max:max5}))}var safeMathMin$1=Math.min;var safeMathMax=Math.max;var safeArrayIsArray$1=SArray.isArray;var safeObjectEntries=Object.entries;function extractMaxIndex(indexesAndValues){let maxIndex=-1;for(let index2=0;index2!==indexesAndValues.length;++index2)maxIndex=safeMathMax(maxIndex,indexesAndValues[index2][0]);return maxIndex}function arrayFromItems(length,indexesAndValues){const array4=SArray(length);for(let index2=0;index2!==indexesAndValues.length;++index2){const it=indexesAndValues[index2];if(it[0]<length)array4[it[0]]=it[1]}return array4}function sparseArray(arb,constraints={}){const{size:size6,minNumElements=0,maxLength=MaxLengthUpperBound,maxNumElements=maxLength,noTrailingHole,depthIdentifier}=constraints;const maxGeneratedLength=maxGeneratedLengthFromSizeForArbitrary(size6,maxGeneratedLengthFromSizeForArbitrary(size6,minNumElements,maxNumElements,constraints.maxNumElements!==undefined),maxLength,constraints.maxLength!==undefined);if(minNumElements>maxLength)throw new Error(`The minimal number of non-hole elements cannot be higher than the maximal length of the array`);if(minNumElements>maxNumElements)throw new Error(`The minimal number of non-hole elements cannot be higher than the maximal number of non-holes`);const resultedMaxNumElements=safeMathMin$1(maxNumElements,maxLength);const resultedSizeMaxNumElements=constraints.maxNumElements!==undefined||size6!==undefined?size6:"=";const sparseArrayNoTrailingHole=uniqueArray(tuple2(restrictedIntegerArbitraryBuilder(0,safeMathMax(maxGeneratedLength-1,0),safeMathMax(maxLength-1,0)),arb),{size:resultedSizeMaxNumElements,minLength:minNumElements,maxLength:resultedMaxNumElements,selector:(item)=>item[0],depthIdentifier}).map((items2)=>{return arrayFromItems(extractMaxIndex(items2)+1,items2)},(value3)=>{if(!safeArrayIsArray$1(value3))throw new Error("Not supported entry type");if(noTrailingHole&&value3.length!==0&&!(value3.length-1 in value3))throw new Error("No trailing hole");return safeMap(safeObjectEntries(value3),(entry)=>[Number(entry[0]),entry[1]])});if(noTrailingHole||maxLength===minNumElements)return sparseArrayNoTrailingHole;return tuple2(sparseArrayNoTrailingHole,restrictedIntegerArbitraryBuilder(minNumElements,maxGeneratedLength,maxLength)).map((data)=>{const sparse=data[0];const targetLength=data[1];if(sparse.length>=targetLength)return sparse;const longerSparse=safeSlice(sparse);longerSparse.length=targetLength;return longerSparse},(value3)=>{if(!safeArrayIsArray$1(value3))throw new Error("Not supported entry type");return[value3,value3.length]})}function arrayToSetMapper(data){return new Set(data)}function arrayToSetUnmapper(value3){if(typeof value3!=="object"||value3===null)throw new Error("Incompatible instance received: should be a non-null object");if(!("constructor"in value3)||value3.constructor!==Set)throw new Error("Incompatible instance received: should be of exact type Set");return Array.from(value3)}function set3(arb,constraints={}){return uniqueArray(arb,{minLength:constraints.minLength,maxLength:constraints.maxLength,size:constraints.size,depthIdentifier:constraints.depthIdentifier,comparator:"SameValueZero"}).map(arrayToSetMapper,arrayToSetUnmapper)}function dictOf(ka,va,maxKeys,size6,depthIdentifier,withNullPrototype){return dictionary(ka,va,{maxKeys,noNullPrototype:!withNullPrototype,size:size6,depthIdentifier})}function typedArray(constraints){return oneof(int8Array(constraints),uint8Array(constraints),uint8ClampedArray(constraints),int16Array(constraints),uint16Array(constraints),int32Array(constraints),uint32Array(constraints),float32Array(constraints),float64Array(constraints))}function anyArbitraryBuilder(constraints){const arbitrariesForBase=constraints.values;const depthSize=constraints.depthSize;const depthIdentifier=createDepthIdentifier();const maxDepth=constraints.maxDepth;const maxKeys=constraints.maxKeys;const size6=constraints.size;const baseArb=oneof(...arbitrariesForBase,...constraints.withBigInt?[bigInt2()]:[],...constraints.withDate?[date()]:[]);return letrec((tie)=>({anything:oneof({maxDepth,depthSize,depthIdentifier},baseArb,tie("array"),tie("object"),...constraints.withMap?[tie("map")]:[],...constraints.withSet?[tie("set")]:[],...constraints.withObjectString?[tie("anything").map((o)=>stringify(o))]:[],...constraints.withTypedArray?[typedArray({maxLength:maxKeys,size:size6})]:[],...constraints.withSparseArray?[sparseArray(tie("anything"),{maxNumElements:maxKeys,size:size6,depthIdentifier})]:[]),keys:constraints.withObjectString?oneof({arbitrary:constraints.key,weight:10},{arbitrary:tie("anything").map((o)=>stringify(o)),weight:1}):constraints.key,array:array3(tie("anything"),{maxLength:maxKeys,size:size6,depthIdentifier}),set:set3(tie("anything"),{maxLength:maxKeys,size:size6,depthIdentifier}),map:oneof(map13(tie("keys"),tie("anything"),{maxKeys,size:size6,depthIdentifier}),map13(tie("anything"),tie("anything"),{maxKeys,size:size6,depthIdentifier})),object:dictOf(tie("keys"),tie("anything"),maxKeys,size6,depthIdentifier,constraints.withNullPrototype)})).anything}function unboxedToBoxedMapper(value3){switch(typeof value3){case"boolean":return new SBoolean(value3);case"number":return new SNumber(value3);case"string":return new SString(value3);default:return value3}}function unboxedToBoxedUnmapper(value3){if(typeof value3!=="object"||value3===null||!("constructor"in value3))return value3;return value3.constructor===SBoolean||value3.constructor===SNumber||value3.constructor===SString?value3.valueOf():value3}function boxedArbitraryBuilder(arb){return arb.map(unboxedToBoxedMapper,unboxedToBoxedUnmapper)}function defaultValues(constraints,stringArbitrary){return[boolean2(),maxSafeInteger(),double(),stringArbitrary(constraints),oneof(stringArbitrary(constraints),constant2(null),constant2(undefined))]}function boxArbitraries(arbs){return arbs.map((arb)=>boxedArbitraryBuilder(arb))}function boxArbitrariesIfNeeded(arbs,boxEnabled){return boxEnabled?boxArbitraries(arbs).concat(arbs):arbs}function toQualifiedObjectConstraints(settings={}){const valueConstraints={size:settings.size,unit:"stringUnit"in settings?settings.stringUnit:settings.withUnicodeString?"binary":undefined};return{key:settings.key!==undefined?settings.key:string3(valueConstraints),values:boxArbitrariesIfNeeded(settings.values!==undefined?settings.values:defaultValues(valueConstraints,string3),settings.withBoxedValues===true),depthSize:settings.depthSize,maxDepth:settings.maxDepth,maxKeys:settings.maxKeys,size:settings.size,withSet:settings.withSet===true,withMap:settings.withMap===true,withObjectString:settings.withObjectString===true,withNullPrototype:settings.withNullPrototype===true,withBigInt:settings.withBigInt===true,withDate:settings.withDate===true,withTypedArray:settings.withTypedArray===true,withSparseArray:settings.withSparseArray===true}}function objectInternal(constraints){return dictionary(constraints.key,anyArbitraryBuilder(constraints),{maxKeys:constraints.maxKeys,noNullPrototype:!constraints.withNullPrototype,size:constraints.size})}function object(constraints){return objectInternal(toQualifiedObjectConstraints(constraints))}function jsonConstraintsBuilder(stringArbitrary,constraints){const{depthSize,maxDepth}=constraints;return{key:stringArbitrary,values:[boolean2(),double({noDefaultInfinity:true,noNaN:true}),stringArbitrary,constant2(null)],depthSize,maxDepth}}function anything(constraints){return anyArbitraryBuilder(toQualifiedObjectConstraints(constraints))}function jsonValue(constraints={}){const noUnicodeString=constraints.noUnicodeString===undefined||constraints.noUnicodeString===true;return anything(jsonConstraintsBuilder("stringUnit"in constraints?string3({unit:constraints.stringUnit}):noUnicodeString?string3():string3({unit:"binary"}),constraints))}var safeJsonStringify=JSON.stringify;var safeJsonParse=JSON.parse;function jsonStringUnmapper(value3){if(typeof value3!=="string")throw new SError("Cannot unmap the passed value");return safeJsonParse(value3)}function json(constraints={}){return jsonValue(constraints).map(safeJsonStringify,jsonStringUnmapper)}var safeObjectDefineProperties=Object.defineProperties;function prettyPrint(numSeen,seenValuesStrings){return`Stream(${seenValuesStrings!==undefined?`${safeJoin(seenValuesStrings,",")}…`:`${numSeen} emitted`})`}var StreamArbitrary=class extends Arbitrary{constructor(arb,history){super();this.arb=arb;this.history=history}generate(mrng,biasFactor){const appliedBiasFactor=biasFactor!==undefined&&mrng.nextInt(1,biasFactor)===1?biasFactor:undefined;const enrichedProducer=()=>{const seenValues=this.history?[]:null;let numSeenValues=0;const g=function*(arb,clonedMrng){while(true){const value3=arb.generate(clonedMrng,appliedBiasFactor).value;numSeenValues++;if(seenValues!==null)safePush(seenValues,value3);yield value3}};const s=new Stream(g(this.arb,mrng.clone()));return safeObjectDefineProperties(s,{toString:{value:()=>prettyPrint(numSeenValues,seenValues!==null?seenValues.map(stringify):undefined)},[toStringMethod]:{value:()=>prettyPrint(numSeenValues,seenValues!==null?seenValues.map(stringify):undefined)},[asyncToStringMethod]:{value:async()=>prettyPrint(numSeenValues,seenValues!==null?await Promise.all(seenValues.map(asyncStringify)):undefined)},[cloneMethod]:{value:enrichedProducer,enumerable:true}})};return new Value(enrichedProducer(),undefined)}canShrinkWithoutContext(_value){return false}shrink(_value,_context){return Stream.nil()}};function infiniteStream(arb,constraints){return new StreamArbitrary(arb,constraints!==undefined&&typeof constraints==="object"&&"noHistory"in constraints?!constraints.noHistory:true)}function codePointsToStringMapper(tab){return safeJoin(tab,"")}function codePointsToStringUnmapper(value3){if(typeof value3!=="string")throw new Error("Cannot unmap the passed value");return[...value3]}function stringToBase64Mapper(s){switch(s.length%4){case 0:return s;case 3:return`${s}=`;case 2:return`${s}==`;default:return safeSubstring(s,1)}}function stringToBase64Unmapper(value3){if(typeof value3!=="string"||value3.length%4!==0)throw new Error("Invalid string received");const lastTrailingIndex=value3.indexOf("=");if(lastTrailingIndex===-1)return value3;if(value3.length-lastTrailingIndex>2)throw new Error("Cannot unmap the passed value");return safeSubstring(value3,0,lastTrailingIndex)}var safeStringFromCharCode=String.fromCharCode;function base64Mapper(v){if(v<26)return safeStringFromCharCode(v+65);if(v<52)return safeStringFromCharCode(v+97-26);if(v<62)return safeStringFromCharCode(v+48-52);return v===62?"+":"/"}function base64Unmapper(s){if(typeof s!=="string"||s.length!==1)throw new SError("Invalid entry");const v=safeCharCodeAt(s,0);if(v>=65&&v<=90)return v-65;if(v>=97&&v<=122)return v-97+26;if(v>=48&&v<=57)return v-48+52;return v===43?62:v===47?63:-1}function base64(){return integer({min:0,max:63}).map(base64Mapper,base64Unmapper)}function base64String(constraints={}){const{minLength:unscaledMinLength=0,maxLength:unscaledMaxLength=MaxLengthUpperBound,size:size6}=constraints;const minLength=unscaledMinLength+3-(unscaledMinLength+3)%4;const maxLength=unscaledMaxLength-unscaledMaxLength%4;const requestedSize=constraints.maxLength===undefined&&size6===undefined?"=":size6;if(minLength>maxLength)throw new SError("Minimal length should be inferior or equal to maximal length");if(minLength%4!==0)throw new SError("Minimal length of base64 strings must be a multiple of 4");if(maxLength%4!==0)throw new SError("Maximal length of base64 strings must be a multiple of 4");const charArbitrary=base64();return array3(charArbitrary,{minLength,maxLength,size:requestedSize,experimentalCustomSlices:createSlicesForStringLegacy(charArbitrary,codePointsToStringUnmapper)}).map(codePointsToStringMapper,codePointsToStringUnmapper).map(stringToBase64Mapper,stringToBase64Unmapper)}var safeObjectIs=Object.is;function isSubarrayOf(source,small){const countMap=new SMap$1;let countMinusZero=0;for(const sourceEntry of source)if(safeObjectIs(sourceEntry,-0))++countMinusZero;else safeMapSet(countMap,sourceEntry,(safeMapGet(countMap,sourceEntry)||0)+1);for(let index2=0;index2!==small.length;++index2){if(!(index2 in small))return false;const smallEntry=small[index2];if(safeObjectIs(smallEntry,-0)){if(countMinusZero===0)return false;--countMinusZero}else{const oldCount=safeMapGet(countMap,smallEntry)||0;if(oldCount===0)return false;safeMapSet(countMap,smallEntry,oldCount-1)}}return true}var safeMathFloor$1=Math.floor;var safeMathLog=Math.log;var safeArrayIsArray=Array.isArray;var SubarrayArbitrary=class extends Arbitrary{constructor(originalArray,isOrdered,minLength,maxLength){super();this.originalArray=originalArray;this.isOrdered=isOrdered;this.minLength=minLength;this.maxLength=maxLength;if(minLength<0||minLength>originalArray.length)throw new Error("fc.*{s|S}ubarrayOf expects the minimal length to be between 0 and the size of the original array");if(maxLength<0||maxLength>originalArray.length)throw new Error("fc.*{s|S}ubarrayOf expects the maximal length to be between 0 and the size of the original array");if(minLength>maxLength)throw new Error("fc.*{s|S}ubarrayOf expects the minimal length to be inferior or equal to the maximal length");this.lengthArb=new IntegerArbitrary(minLength,maxLength);this.biasedLengthArb=minLength!==maxLength?new IntegerArbitrary(minLength,minLength+safeMathFloor$1(safeMathLog(maxLength-minLength)/safeMathLog(2))):this.lengthArb}generate(mrng,biasFactor){const size6=(biasFactor!==undefined&&mrng.nextInt(1,biasFactor)===1?this.biasedLengthArb:this.lengthArb).generate(mrng,undefined);const sizeValue=size6.value;const remainingElements=safeMap(this.originalArray,(_v,idx)=>idx);const ids=[];for(let index2=0;index2!==sizeValue;++index2){const selectedIdIndex=mrng.nextInt(0,remainingElements.length-1);safePush(ids,remainingElements[selectedIdIndex]);safeSplice(remainingElements,selectedIdIndex,1)}if(this.isOrdered)safeSort(ids,(a,b)=>a-b);return new Value(safeMap(ids,(i)=>this.originalArray[i]),size6.context)}canShrinkWithoutContext(value3){if(!safeArrayIsArray(value3))return false;if(!this.lengthArb.canShrinkWithoutContext(value3.length))return false;return isSubarrayOf(this.originalArray,value3)}shrink(value3,context4){if(value3.length===0)return Stream.nil();return this.lengthArb.shrink(value3.length,context4).map((newSize)=>{return new Value(safeSlice(value3,value3.length-newSize.value),newSize.context)}).join(value3.length>this.minLength?makeLazy2(()=>this.shrink(safeSlice(value3,1),undefined).filter((newValue)=>this.minLength<=newValue.value.length+1).map((newValue)=>new Value([value3[0],...newValue.value],undefined))):Stream.nil())}};function subarray(originalArray,constraints={}){const{minLength=0,maxLength=originalArray.length}=constraints;return new SubarrayArbitrary(originalArray,true,minLength,maxLength)}function shuffledSubarray(originalArray,constraints={}){const{minLength=0,maxLength=originalArray.length}=constraints;return new SubarrayArbitrary(originalArray,false,minLength,maxLength)}var encodeSymbolLookupTable={10:"A",11:"B",12:"C",13:"D",14:"E",15:"F",16:"G",17:"H",18:"J",19:"K",20:"M",21:"N",22:"P",23:"Q",24:"R",25:"S",26:"T",27:"V",28:"W",29:"X",30:"Y",31:"Z"};var decodeSymbolLookupTable={"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,A:10,B:11,C:12,D:13,E:14,F:15,G:16,H:17,J:18,K:19,M:20,N:21,P:22,Q:23,R:24,S:25,T:26,V:27,W:28,X:29,Y:30,Z:31};function encodeSymbol(symbol4){return symbol4<10?SString(symbol4):encodeSymbolLookupTable[symbol4]}function pad(value3,paddingLength){let extraPadding="";while(value3.length+extraPadding.length<paddingLength)extraPadding+="0";return extraPadding+value3}function smallUintToBase32StringMapper(num){let base32Str="";for(let remaining=num;remaining!==0;){const next=remaining>>5;base32Str=encodeSymbol(remaining-(next<<5))+base32Str;remaining=next}return base32Str}function uintToBase32StringMapper(num,paddingLength){const head=~~(num/1073741824);const tail=num&1073741823;return pad(smallUintToBase32StringMapper(head),paddingLength-6)+pad(smallUintToBase32StringMapper(tail),6)}function paddedUintToBase32StringMapper(paddingLength){return function padded(num){return uintToBase32StringMapper(num,paddingLength)}}function uintToBase32StringUnmapper(value3){if(typeof value3!=="string")throw new SError("Unsupported type");let accumulated=0;let power=1;for(let index2=value3.length-1;index2>=0;--index2){const char=value3[index2];const numericForChar=decodeSymbolLookupTable[char];if(numericForChar===undefined)throw new SError("Unsupported type");accumulated+=numericForChar*power;power*=32}return accumulated}var padded10Mapper=paddedUintToBase32StringMapper(10);var padded8Mapper=paddedUintToBase32StringMapper(8);function ulidMapper(parts){return padded10Mapper(parts[0])+padded8Mapper(parts[1])+padded8Mapper(parts[2])}function ulidUnmapper(value3){if(typeof value3!=="string"||value3.length!==26)throw new Error("Unsupported type");return[uintToBase32StringUnmapper(value3.slice(0,10)),uintToBase32StringUnmapper(value3.slice(10,18)),uintToBase32StringUnmapper(value3.slice(18))]}function ulid(){return tuple2(integer({min:0,max:281474976710655}),integer({min:0,max:1099511627775}),integer({min:0,max:1099511627775})).map(ulidMapper,ulidUnmapper)}function numberToPaddedEightMapper(n){return safePadStart(safeNumberToString(n,16),8,"0")}function numberToPaddedEightUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");if(value3.length!==8)throw new Error("Unsupported value: invalid length");const n=parseInt(value3,16);if(value3!==numberToPaddedEightMapper(n))throw new Error("Unsupported value: invalid content");return n}function buildPaddedNumberArbitrary(min5,max5){return integer({min:min5,max:max5}).map(numberToPaddedEightMapper,numberToPaddedEightUnmapper)}function paddedEightsToUuidMapper(t){return`${t[0]}-${safeSubstring(t[1],4)}-${safeSubstring(t[1],0,4)}-${safeSubstring(t[2],0,4)}-${safeSubstring(t[2],4)}${t[3]}`}var UuidRegex=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/;function paddedEightsToUuidUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported type");const m=UuidRegex.exec(value3);if(m===null)throw new Error("Unsupported type");return[m[1],m[3]+m[2],m[4]+safeSubstring(m[5],0,4),safeSubstring(m[5],4)]}var quickNumberToHexaString="0123456789abcdef";function buildVersionsAppliersForUuid(versions){const mapping={};const reversedMapping={};for(let index2=0;index2!==versions.length;++index2){const from=quickNumberToHexaString[index2];const to=quickNumberToHexaString[versions[index2]];mapping[from]=to;reversedMapping[to]=from}function versionsApplierMapper(value3){return mapping[value3[0]]+safeSubstring(value3,1)}function versionsApplierUnmapper(value3){if(typeof value3!=="string")throw new SError("Cannot produce non-string values");const rev=reversedMapping[value3[0]];if(rev===undefined)throw new SError("Cannot produce strings not starting by the version in hexa code");return rev+safeSubstring(value3,1)}return{versionsApplierMapper,versionsApplierUnmapper}}function assertValidVersions(versions){const found={};for(const version2 of versions){if(found[version2])throw new SError(`Version ${version2} has been requested at least twice for uuid`);found[version2]=true;if(version2<1||version2>15)throw new SError(`Version must be a value in [1-15] for uuid, but received ${version2}`);if(~~version2!==version2)throw new SError(`Version must be an integer value for uuid, but received ${version2}`)}if(versions.length===0)throw new SError(`Must provide at least one version for uuid`)}function uuid(constraints={}){const padded=buildPaddedNumberArbitrary(0,4294967295);const version2=constraints.version!==undefined?typeof constraints.version==="number"?[constraints.version]:constraints.version:[1,2,3,4,5,6,7,8];assertValidVersions(version2);const{versionsApplierMapper,versionsApplierUnmapper}=buildVersionsAppliersForUuid(version2);return tuple2(padded,buildPaddedNumberArbitrary(0,268435456*version2.length-1).map(versionsApplierMapper,versionsApplierUnmapper),buildPaddedNumberArbitrary(2147483648,3221225471),padded).map(paddedEightsToUuidMapper,paddedEightsToUuidUnmapper)}function hostUserInfo(size6){return string3({unit:getOrCreateAlphaNumericPercentArbitrary("-._~!$&'()*+,;=:"),size:size6})}function userHostPortMapper([u,h2,p]){return(u===null?"":`${u}@`)+h2+(p===null?"":`:${p}`)}function userHostPortUnmapper(value3){if(typeof value3!=="string")throw new Error("Unsupported");const atPosition=value3.indexOf("@");const user=atPosition!==-1?value3.substring(0,atPosition):null;const m=/:(\d+)$/.exec(value3);const port=m!==null?Number(m[1]):null;return[user,m!==null?value3.substring(atPosition+1,value3.length-m[1].length-1):value3.substring(atPosition+1),port]}function bracketedMapper(s){return`[${s}]`}function bracketedUnmapper(value3){if(typeof value3!=="string"||value3[0]!=="["||value3[value3.length-1]!=="]")throw new Error("Unsupported");return value3.substring(1,value3.length-1)}function webAuthority(constraints){const c=constraints||{};const size6=c.size;const hostnameArbs=[domain({size:size6}),...c.withIPv4===true?[ipV4()]:[],...c.withIPv6===true?[ipV6().map(bracketedMapper,bracketedUnmapper)]:[],...c.withIPv4Extended===true?[ipV4Extended()]:[]];return tuple2(c.withUserInfo===true?option3(hostUserInfo(size6)):constant2(null),oneof(...hostnameArbs),c.withPort===true?option3(nat(65535)):constant2(null)).map(userHostPortMapper,userHostPortUnmapper)}function buildUriQueryOrFragmentArbitrary(size6){return string3({unit:getOrCreateAlphaNumericPercentArbitrary("-._~!$&'()*+,;=:@/?"),size:size6})}function webFragments(constraints={}){return buildUriQueryOrFragmentArbitrary(constraints.size)}function webSegment(constraints={}){return string3({unit:getOrCreateAlphaNumericPercentArbitrary("-._~!$&'()*+,;=:@"),size:constraints.size})}function segmentsToPathMapper(segments){let path="";for(let index2=0;index2!==segments.length;++index2)path+="/"+segments[index2];return path}function segmentsToPathUnmapper(value3){if(typeof value3!=="string")throw new Error("Incompatible value received: type");if(value3.length!==0&&value3[0]!=="/")throw new Error("Incompatible value received: start");return safeSplice(safeSplit(value3,"/"),1)}function sqrtSize(size6){switch(size6){case"xsmall":return["xsmall","xsmall"];case"small":return["small","xsmall"];case"medium":return["small","small"];case"large":return["medium","small"];case"xlarge":return["medium","medium"]}}function buildUriPathArbitraryInternal(segmentSize,numSegmentSize){return array3(webSegment({size:segmentSize}),{size:numSegmentSize}).map(segmentsToPathMapper,segmentsToPathUnmapper)}function buildUriPathArbitrary(resolvedSize){const[segmentSize,numSegmentSize]=sqrtSize(resolvedSize);if(segmentSize===numSegmentSize)return buildUriPathArbitraryInternal(segmentSize,numSegmentSize);return oneof(buildUriPathArbitraryInternal(segmentSize,numSegmentSize),buildUriPathArbitraryInternal(numSegmentSize,segmentSize))}function webPath(constraints){return buildUriPathArbitrary(resolveSize((constraints||{}).size))}function webQueryParameters(constraints={}){return buildUriQueryOrFragmentArbitrary(constraints.size)}function partsToUrlMapper(data){const[scheme,authority,path]=data;return`${scheme}://${authority}${path}${data[3]===null?"":`?${data[3]}`}${data[4]===null?"":`#${data[4]}`}`}var UrlSplitRegex=/^([[A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)([^?#]*)(\?[A-Za-z0-9\-._~!$&'()*+,;=:@/?%]*)?(#[A-Za-z0-9\-._~!$&'()*+,;=:@/?%]*)?$/;function partsToUrlUnmapper(value3){if(typeof value3!=="string")throw new Error("Incompatible value received: type");const m=UrlSplitRegex.exec(value3);if(m===null)throw new Error("Incompatible value received");const scheme=m[1];const authority=m[2];const path=m[3];const query=m[4];const fragments=m[5];return[scheme,authority,path,query!==undefined?query.substring(1):null,fragments!==undefined?fragments.substring(1):null]}function webUrl(constraints){const c=constraints||{};const resolvedSize=resolveSize(c.size);const resolvedAuthoritySettingsSize=c.authoritySettings!==undefined&&c.authoritySettings.size!==undefined?relativeSizeToSize(c.authoritySettings.size,resolvedSize):resolvedSize;const resolvedAuthoritySettings={...c.authoritySettings,size:resolvedAuthoritySettingsSize};return tuple2(constantFrom(...c.validSchemes||["http","https"]),webAuthority(resolvedAuthoritySettings),webPath({size:resolvedSize}),c.withQueryParameters===true?option3(webQueryParameters({size:resolvedSize})):constant2(null),c.withFragments===true?option3(webFragments({size:resolvedSize})):constant2(null)).map(partsToUrlMapper,partsToUrlUnmapper)}var CommandsIterable=class CommandsIterable2{constructor(commands,metadataForReplay){this.commands=commands;this.metadataForReplay=metadataForReplay;this[cloneMethod]=function(){return new CommandsIterable2(this.commands.map((c)=>c.clone()),this.metadataForReplay)}}[Symbol.iterator](){return this.commands[Symbol.iterator]()}toString(){const serializedCommands=this.commands.filter((c)=>c.hasRan).map((c)=>c.toString()).join(",");const metadata=this.metadataForReplay();return metadata.length!==0?`${serializedCommands} /*${metadata}*/`:serializedCommands}};var CommandWrapper=class CommandWrapper2{constructor(cmd){this.cmd=cmd;this.hasRan=false;if(hasToStringMethod(cmd)){const method=cmd[toStringMethod];this[toStringMethod]=function toStringMethod(){return method.call(cmd)}}if(hasAsyncToStringMethod(cmd)){const method=cmd[asyncToStringMethod];this[asyncToStringMethod]=function asyncToStringMethod(){return method.call(cmd)}}}check(m){return this.cmd.check(m)}run(m,r){this.hasRan=true;return this.cmd.run(m,r)}clone(){if(hasCloneMethod(this.cmd))return new CommandWrapper2(this.cmd[cloneMethod]());return new CommandWrapper2(this.cmd)}toString(){return this.cmd.toString()}};var ReplayPath=class{static parse(replayPathStr){const[serializedCount,serializedChanges]=replayPathStr.split(":");const counts=this.parseCounts(serializedCount);const changes=this.parseChanges(serializedChanges);return this.parseOccurences(counts,changes)}static stringify(replayPath){const occurences=this.countOccurences(replayPath);return`${this.stringifyCounts(occurences)}:${this.stringifyChanges(occurences)}`}static intToB64(n){if(n<26)return String.fromCharCode(n+65);if(n<52)return String.fromCharCode(n+97-26);if(n<62)return String.fromCharCode(n+48-52);return String.fromCharCode(n===62?43:47)}static b64ToInt(c){if(c>="a")return c.charCodeAt(0)-97+26;if(c>="A")return c.charCodeAt(0)-65;if(c>="0")return c.charCodeAt(0)-48+52;return c==="+"?62:63}static countOccurences(replayPath){return replayPath.reduce((counts,cur)=>{if(counts.length===0||counts[counts.length-1].count===64||counts[counts.length-1].value!==cur)counts.push({value:cur,count:1});else counts[counts.length-1].count+=1;return counts},[])}static parseOccurences(counts,changes){const replayPath=[];for(let idx=0;idx!==counts.length;++idx){const count=counts[idx];const value3=changes[idx];for(let num=0;num!==count;++num)replayPath.push(value3)}return replayPath}static stringifyChanges(occurences){let serializedChanges="";for(let idx=0;idx<occurences.length;idx+=6){const changesInt=occurences.slice(idx,idx+6).reduceRight((prev,cur)=>(prev<<1)+(cur.value?1:0),0);serializedChanges+=this.intToB64(changesInt)}return serializedChanges}static parseChanges(serializedChanges){const changesInt=serializedChanges.split("").map((c)=>this.b64ToInt(c));const changes=[];for(let idx=0;idx!==changesInt.length;++idx){let current=changesInt[idx];for(let n=0;n!==6;++n,current>>=1)changes.push(current%2===1)}return changes}static stringifyCounts(occurences){return occurences.map(({count})=>this.intToB64(count-1)).join("")}static parseCounts(serializedCount){return serializedCount.split("").map((c)=>this.b64ToInt(c)+1)}};var CommandsArbitrary=class extends Arbitrary{constructor(commandArbs,maxGeneratedCommands,maxCommands,sourceReplayPath,disableReplayLog){super();this.sourceReplayPath=sourceReplayPath;this.disableReplayLog=disableReplayLog;this.oneCommandArb=oneof(...commandArbs).map((c)=>new CommandWrapper(c));this.lengthArb=restrictedIntegerArbitraryBuilder(0,maxGeneratedCommands,maxCommands);this.replayPath=[];this.replayPathPosition=0}metadataForReplay(){return this.disableReplayLog?"":`replayPath=${JSON.stringify(ReplayPath.stringify(this.replayPath))}`}buildValueFor(items2,shrunkOnce){const commands=items2.map((item)=>item.value_);const context4={shrunkOnce,items:items2};return new Value(new CommandsIterable(commands,()=>this.metadataForReplay()),context4)}generate(mrng){const sizeValue=this.lengthArb.generate(mrng,undefined).value;const items2=Array(sizeValue);for(let idx=0;idx!==sizeValue;++idx)items2[idx]=this.oneCommandArb.generate(mrng,undefined);this.replayPathPosition=0;return this.buildValueFor(items2,false)}canShrinkWithoutContext(_value){return false}filterOnExecution(itemsRaw){const items2=[];for(const c of itemsRaw)if(c.value_.hasRan){this.replayPath.push(true);items2.push(c)}else this.replayPath.push(false);return items2}filterOnReplay(itemsRaw){return itemsRaw.filter((c,idx)=>{const state=this.replayPath[this.replayPathPosition+idx];if(state===undefined)throw new Error(`Too short replayPath`);if(!state&&c.value_.hasRan)throw new Error(`Mismatch between replayPath and real execution`);return state})}filterForShrinkImpl(itemsRaw){if(this.replayPathPosition===0)this.replayPath=this.sourceReplayPath!==null?ReplayPath.parse(this.sourceReplayPath):[];const items2=this.replayPathPosition<this.replayPath.length?this.filterOnReplay(itemsRaw):this.filterOnExecution(itemsRaw);this.replayPathPosition+=itemsRaw.length;return items2}shrink(_value,context4){if(context4===undefined)return Stream.nil();const safeContext=context4;const shrunkOnce=safeContext.shrunkOnce;const itemsRaw=safeContext.items;const items2=this.filterForShrinkImpl(itemsRaw);if(items2.length===0)return Stream.nil();const rootShrink=shrunkOnce?Stream.nil():new Stream([[]][Symbol.iterator]());const nextShrinks=[];for(let numToKeep=0;numToKeep!==items2.length;++numToKeep)nextShrinks.push(makeLazy2(()=>{const fixedStart=items2.slice(0,numToKeep);return this.lengthArb.shrink(items2.length-1-numToKeep,undefined).map((l)=>fixedStart.concat(items2.slice(items2.length-(l.value+1))))}));for(let itemAt=0;itemAt!==items2.length;++itemAt)nextShrinks.push(makeLazy2(()=>this.oneCommandArb.shrink(items2[itemAt].value_,items2[itemAt].context).map((v)=>items2.slice(0,itemAt).concat([v],items2.slice(itemAt+1)))));return rootShrink.join(...nextShrinks).map((shrinkables)=>{return this.buildValueFor(shrinkables.map((c)=>new Value(c.value_.clone(),c.context)),true)})}};function commands(commandArbs,constraints={}){const{size:size6,maxCommands=MaxLengthUpperBound,disableReplayLog=false,replayPath=null}=constraints;return new CommandsArbitrary(commandArbs,maxGeneratedLengthFromSizeForArbitrary(size6,0,maxCommands,constraints.maxCommands!==undefined),maxCommands,replayPath,disableReplayLog)}var ScheduledCommand=class{constructor(s,cmd){this.s=s;this.cmd=cmd}async check(m){let error=null;let checkPassed=false;if((await this.s.scheduleSequence([{label:`check@${this.cmd.toString()}`,builder:async()=>{try{checkPassed=await Promise.resolve(this.cmd.check(m))}catch(err){error=err;throw err}}}]).task).faulty)throw error;return checkPassed}async run(m,r){let error=null;if((await this.s.scheduleSequence([{label:`run@${this.cmd.toString()}`,builder:async()=>{try{await this.cmd.run(m,r)}catch(err){error=err;throw err}}}]).task).faulty)throw error}};var scheduleCommands=function*(s,cmds){for(const cmd of cmds)yield new ScheduledCommand(s,cmd)};var genericModelRun=(s,cmds,initialValue,runCmd,then)=>{return s.then((o)=>{const{model,real}=o;let state=initialValue;for(const c of cmds)state=then(state,()=>{return runCmd(c,model,real)});return state})};var internalModelRun=(s,cmds)=>{const then=(_p,c)=>c();const setupProducer={then:(fun)=>{fun(s())}};const runSync3=(cmd,m,r)=>{if(cmd.check(m))cmd.run(m,r)};return genericModelRun(setupProducer,cmds,undefined,runSync3,then)};var isAsyncSetup=(s)=>{return typeof s.then==="function"};var internalAsyncModelRun=async(s,cmds,defaultPromise=Promise.resolve())=>{const then=(p,c)=>p.then(c);const setupProducer={then:(fun)=>{const out=s();if(isAsyncSetup(out))return out.then(fun);else return fun(out)}};const runAsync=async(cmd,m,r)=>{if(await cmd.check(m))await cmd.run(m,r)};return await genericModelRun(setupProducer,cmds,defaultPromise,runAsync,then)};function modelRun(s,cmds){internalModelRun(s,cmds)}async function asyncModelRun(s,cmds){await internalAsyncModelRun(s,cmds)}async function scheduledModelRun(scheduler,s,cmds){const scheduledCommands=scheduleCommands(scheduler,cmds);const out=internalAsyncModelRun(s,scheduledCommands,scheduler.schedule(Promise.resolve(),"startModel"));await scheduler.waitFor(out);await scheduler.waitAll()}var defaultSchedulerAct=(f)=>f();var SchedulerImplem=class SchedulerImplem2{constructor(act,taskSelector){this.act=act;this.taskSelector=taskSelector;this.lastTaskId=0;this.sourceTaskSelector=taskSelector.clone();this.scheduledTasks=[];this.triggeredTasks=[];this.scheduledWatchers=[];this[cloneMethod]=function(){return new SchedulerImplem2(this.act,this.sourceTaskSelector)}}static buildLog(reportItem){return`[task\${${reportItem.taskId}}] ${reportItem.label.length!==0?`${reportItem.schedulingType}::${reportItem.label}`:reportItem.schedulingType} ${reportItem.status}${reportItem.outputValue!==undefined?` with value ${escapeForTemplateString(reportItem.outputValue)}`:""}`}log(schedulingType,taskId,label,metadata,status,data){this.triggeredTasks.push({status,schedulingType,taskId,label,metadata,outputValue:data!==undefined?stringify(data):undefined})}scheduleInternal(schedulingType,label,task,metadata,customAct,thenTaskToBeAwaited){const taskId=++this.lastTaskId;let trigger=undefined;const scheduledPromise=new Promise((resolve4,reject)=>{trigger=()=>{const promise3=Promise.resolve(thenTaskToBeAwaited!==undefined?task.then(()=>thenTaskToBeAwaited()):task);promise3.then((data)=>{this.log(schedulingType,taskId,label,metadata,"resolved",data);resolve4(data)},(err)=>{this.log(schedulingType,taskId,label,metadata,"rejected",err);reject(err)});return promise3}});this.scheduledTasks.push({original:task,trigger,schedulingType,taskId,label,metadata,customAct});if(this.scheduledWatchers.length!==0)this.scheduledWatchers[0]();return scheduledPromise}schedule(task,label,metadata,customAct){return this.scheduleInternal("promise",label||"",task,metadata,customAct||defaultSchedulerAct)}scheduleFunction(asyncFunction,customAct){return(...args2)=>this.scheduleInternal("function",`${asyncFunction.name}(${args2.map(stringify).join(",")})`,asyncFunction(...args2),undefined,customAct||defaultSchedulerAct)}scheduleSequence(sequenceBuilders,customAct){const status={done:false,faulty:false};const dummyResolvedPromise={then:(f)=>f()};let resolveSequenceTask=()=>{};const sequenceTask=new Promise((resolve4)=>{resolveSequenceTask=()=>resolve4({done:status.done,faulty:status.faulty})});const onFaultyItemNoThrow=()=>{status.faulty=true;resolveSequenceTask()};const onDone=()=>{status.done=true;resolveSequenceTask()};const registerNextBuilder=(index2,previous)=>{if(index2>=sequenceBuilders.length){previous.then(onDone,onFaultyItemNoThrow);return}previous.then(()=>{const item=sequenceBuilders[index2];const[builder,label,metadata]=typeof item==="function"?[item,item.name,undefined]:[item.builder,item.label,item.metadata];const scheduled=this.scheduleInternal("sequence",label,dummyResolvedPromise,metadata,customAct||defaultSchedulerAct,()=>builder());registerNextBuilder(index2+1,scheduled)},onFaultyItemNoThrow)};registerNextBuilder(0,dummyResolvedPromise);return Object.assign(status,{task:sequenceTask})}count(){return this.scheduledTasks.length}internalWaitOne(){if(this.scheduledTasks.length===0)throw new Error("No task scheduled");const taskIndex=this.taskSelector.nextTaskIndex(this.scheduledTasks);const[scheduledTask]=this.scheduledTasks.splice(taskIndex,1);return scheduledTask.customAct(()=>{return scheduledTask.trigger().catch((_err)=>{})})}waitOne(customAct){const waitAct=customAct||defaultSchedulerAct;return this.act(()=>waitAct(()=>this.internalWaitOne()))}async waitAll(customAct){while(this.scheduledTasks.length>0)await this.waitOne(customAct)}async internalWaitFor(unscheduledTask,options){let taskResolved=false;const customAct=options.customAct;const onWaitStart=options.onWaitStart;const onWaitIdle=options.onWaitIdle;const launchAwaiterOnInit=options.launchAwaiterOnInit;let resolveFinal=undefined;let rejectFinal=undefined;let awaiterTicks=0;let awaiterPromise=null;let awaiterScheduledTaskPromise=null;const awaiter=async()=>{awaiterTicks=50;for(awaiterTicks=50;!taskResolved&&awaiterTicks>0;--awaiterTicks)await Promise.resolve();if(!taskResolved&&this.scheduledTasks.length>0){if(onWaitStart!==undefined)onWaitStart();awaiterScheduledTaskPromise=this.waitOne(customAct);return awaiterScheduledTaskPromise.then(()=>{awaiterScheduledTaskPromise=null;return awaiter()},(err)=>{awaiterScheduledTaskPromise=null;taskResolved=true;rejectFinal(err);throw err})}if(!taskResolved&&onWaitIdle!==undefined)onWaitIdle();awaiterPromise=null};const handleNotified=()=>{if(awaiterPromise!==null){awaiterTicks=51;return}awaiterPromise=awaiter().catch(()=>{})};const clearAndReplaceWatcher=()=>{const handleNotifiedIndex=this.scheduledWatchers.indexOf(handleNotified);if(handleNotifiedIndex!==-1)this.scheduledWatchers.splice(handleNotifiedIndex,1);if(handleNotifiedIndex===0&&this.scheduledWatchers.length!==0)this.scheduledWatchers[0]()};const finalTask=new Promise((resolve4,reject)=>{resolveFinal=(value3)=>{clearAndReplaceWatcher();resolve4(value3)};rejectFinal=(error)=>{clearAndReplaceWatcher();reject(error)}});unscheduledTask.then((ret)=>{taskResolved=true;if(awaiterScheduledTaskPromise===null)resolveFinal(ret);else awaiterScheduledTaskPromise.then(()=>resolveFinal(ret),(error)=>rejectFinal(error))},(err)=>{taskResolved=true;if(awaiterScheduledTaskPromise===null)rejectFinal(err);else awaiterScheduledTaskPromise.then(()=>rejectFinal(err),()=>rejectFinal(err))});if((this.scheduledTasks.length>0||launchAwaiterOnInit)&&this.scheduledWatchers.length===0)handleNotified();this.scheduledWatchers.push(handleNotified);return finalTask}waitNext(count,customAct){let resolver=undefined;let remaining=count;const awaited=remaining<=0?Promise.resolve():new Promise((r)=>{resolver=()=>{if(--remaining<=0)r()}});return this.internalWaitFor(awaited,{customAct,onWaitStart:resolver,onWaitIdle:undefined,launchAwaiterOnInit:false})}waitIdle(customAct){let resolver=undefined;const awaited=new Promise((r)=>resolver=r);return this.internalWaitFor(awaited,{customAct,onWaitStart:undefined,onWaitIdle:resolver,launchAwaiterOnInit:true})}waitFor(unscheduledTask,customAct){return this.internalWaitFor(unscheduledTask,{customAct,onWaitStart:undefined,onWaitIdle:undefined,launchAwaiterOnInit:false})}report(){return[...this.triggeredTasks,...this.scheduledTasks.map((t)=>({status:"pending",schedulingType:t.schedulingType,taskId:t.taskId,label:t.label,metadata:t.metadata}))]}toString(){return"schedulerFor()`\n"+this.report().map(SchedulerImplem2.buildLog).map((log2)=>`-> ${log2}`).join(`
222
222
  `)+"`"}};function buildNextTaskIndex$1(ordering){let numTasks=0;return{clone:()=>buildNextTaskIndex$1(ordering),nextTaskIndex:(scheduledTasks)=>{if(ordering.length<=numTasks)throw new Error(`Invalid schedulerFor defined: too many tasks have been scheduled`);const taskIndex=scheduledTasks.findIndex((t)=>t.taskId===ordering[numTasks]);if(taskIndex===-1)throw new Error(`Invalid schedulerFor defined: unable to find next task`);++numTasks;return taskIndex}}}function buildSchedulerFor(act,ordering){return new SchedulerImplem(act,buildNextTaskIndex$1(ordering))}function buildNextTaskIndex(mrng){const clonedMrng=mrng.clone();return{clone:()=>buildNextTaskIndex(clonedMrng),nextTaskIndex:(scheduledTasks)=>{return mrng.nextInt(0,scheduledTasks.length-1)}}}var SchedulerArbitrary=class extends Arbitrary{constructor(act){super();this.act=act}generate(mrng,_biasFactor){return new Value(new SchedulerImplem(this.act,buildNextTaskIndex(mrng.clone())),undefined)}canShrinkWithoutContext(_value){return false}shrink(_value,_context){return Stream.nil()}};function scheduler(constraints){const{act=(f)=>f()}=constraints||{};return new SchedulerArbitrary(act)}function schedulerFor(customOrderingOrConstraints,constraintsOrUndefined){const{act=(f)=>f()}=Array.isArray(customOrderingOrConstraints)?constraintsOrUndefined||{}:customOrderingOrConstraints||{};if(Array.isArray(customOrderingOrConstraints))return buildSchedulerFor(act,customOrderingOrConstraints);return function(_strs,...ordering){return buildSchedulerFor(act,ordering)}}function bigInt64Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,SBigInt2("-9223372036854775808"),SBigInt2("9223372036854775807"),SBigInt64Array,bigInt2)}function bigUint64Array(constraints={}){return typedIntArrayArbitraryArbitraryBuilder(constraints,SBigInt2(0),SBigInt2("18446744073709551615"),SBigUint64Array,bigInt2)}function noSuchValue(_value,returnedValue){return returnedValue}var safeMathFloor=Math.floor;var safeMathMin=Math.min;function clampRegexAstInternal(astNode,maxLength){switch(astNode.type){case"Char":return{astNode,minLength:1};case"Repetition":switch(astNode.quantifier.kind){case"*":{const clamped=clampRegexAstInternal(astNode.expression,maxLength);return{astNode:{type:"Repetition",quantifier:{...astNode.quantifier,kind:"Range",from:0,to:maxLength},expression:clamped.astNode},minLength:0}}case"+":{const clamped=clampRegexAstInternal(astNode.expression,maxLength);const scaledClampedMinLength=clamped.minLength>1?clamped.minLength:1;return{astNode:{type:"Repetition",quantifier:{...astNode.quantifier,kind:"Range",from:1,to:safeMathFloor(maxLength/scaledClampedMinLength)},expression:clamped.astNode},minLength:clamped.minLength}}case"?":{const clamped=clampRegexAstInternal(astNode.expression,maxLength);if(maxLength<clamped.minLength)return{astNode:{type:"Repetition",quantifier:{...astNode.quantifier,kind:"Range",from:0,to:0},expression:clamped.astNode},minLength:0};return{astNode:{...astNode,expression:clamped.astNode},minLength:0}}case"Range":{const scaledMaxLength=astNode.quantifier.from>1?safeMathFloor(maxLength/astNode.quantifier.from):maxLength;const clamped=clampRegexAstInternal(astNode.expression,scaledMaxLength);const scaledClampedMinLength=clamped.minLength>1?clamped.minLength:1;if(astNode.quantifier.to===undefined||astNode.quantifier.to*scaledClampedMinLength>maxLength)return{astNode:{type:"Repetition",quantifier:{...astNode.quantifier,kind:"Range",to:safeMathFloor(maxLength/scaledClampedMinLength)},expression:clamped.astNode},minLength:astNode.quantifier.from*clamped.minLength};return{astNode:{...astNode,expression:clamped.astNode},minLength:astNode.quantifier.from*clamped.minLength}}default:return noSuchValue(astNode.quantifier,{astNode,minLength:0})}case"Quantifier":return{astNode,minLength:0};case"Alternative":{let totalMinLength=0;const extendedClampeds=[];for(let index2=0;index2!==astNode.expressions.length;++index2){const temporaryAllowance=maxLength-totalMinLength;const clamped=clampRegexAstInternal(astNode.expressions[index2],temporaryAllowance);totalMinLength+=clamped.minLength;safePush(extendedClampeds,{value:clamped,allowance:temporaryAllowance})}const refinedExpressions=[];for(let index2=0;index2!==extendedClampeds.length;++index2){const current=extendedClampeds[index2].value;const pastAllowance=extendedClampeds[index2].allowance;const allowance=maxLength-totalMinLength+current.minLength;safePush(refinedExpressions,(allowance!==pastAllowance?clampRegexAstInternal(current.astNode,allowance):current).astNode)}return{astNode:{...astNode,expressions:refinedExpressions},minLength:totalMinLength}}case"CharacterClass":return{astNode,minLength:1};case"ClassRange":return{astNode,minLength:1};case"Group":{const clamped=clampRegexAstInternal(astNode.expression,maxLength);return{astNode:{...astNode,expression:clamped.astNode},minLength:clamped.minLength}}case"Disjunction":{if(astNode.left===null){if(astNode.right===null)return{astNode,minLength:0};const clampedRight2=clampRegexAstInternal(astNode.right,maxLength);const refinedRight=clampedRight2.minLength>maxLength?null:clampedRight2.astNode;return{astNode:{...astNode,left:null,right:refinedRight},minLength:0}}if(astNode.right===null){const clampLeft=clampRegexAstInternal(astNode.left,maxLength);const refinedLeft=clampLeft.minLength>maxLength?null:clampLeft.astNode;return{astNode:{...astNode,left:refinedLeft,right:null},minLength:0}}const clampedLeft=clampRegexAstInternal(astNode.left,maxLength);const clampedRight=clampRegexAstInternal(astNode.right,maxLength);if(clampedLeft.minLength>maxLength)return clampedRight;if(clampedRight.minLength>maxLength)return clampedLeft;return{astNode:{...astNode,left:clampedLeft.astNode,right:clampedRight.astNode},minLength:safeMathMin(clampedLeft.minLength,clampedRight.minLength)}}case"Assertion":return{astNode,minLength:0};case"Backreference":return{astNode,minLength:0};case"UnicodeProperty":return{astNode,minLength:1}}}function clampRegexAst(astNode,maxLength){return clampRegexAstInternal(astNode,maxLength).astNode}function raiseUnsupportedASTNode$1(astNode){return new Error(`Unsupported AST node! Received: ${stringify(astNode)}`)}function addMissingDotStarTraversalAddMissing(astNode,isFirst,isLast){if(!isFirst&&!isLast)return astNode;const traversalResults={hasStart:false,hasEnd:false};const revampedNode=addMissingDotStarTraversal(astNode,isFirst,isLast,traversalResults);const missingStart=isFirst&&!traversalResults.hasStart;const missingEnd=isLast&&!traversalResults.hasEnd;if(!missingStart&&!missingEnd)return revampedNode;const expressions=[];if(missingStart){expressions.push({type:"Assertion",kind:"^"});expressions.push({type:"Repetition",quantifier:{type:"Quantifier",kind:"*",greedy:true},expression:{type:"Char",kind:"meta",symbol:".",value:".",codePoint:NaN}})}expressions.push(revampedNode);if(missingEnd){expressions.push({type:"Repetition",quantifier:{type:"Quantifier",kind:"*",greedy:true},expression:{type:"Char",kind:"meta",symbol:".",value:".",codePoint:NaN}});expressions.push({type:"Assertion",kind:"$"})}return{type:"Group",capturing:false,expression:{type:"Alternative",expressions}}}function addMissingDotStarTraversal(astNode,isFirst,isLast,traversalResults){switch(astNode.type){case"Char":return astNode;case"Repetition":return astNode;case"Quantifier":throw new Error(`Wrongly defined AST tree, Quantifier nodes not supposed to be scanned!`);case"Alternative":traversalResults.hasStart=true;traversalResults.hasEnd=true;return{...astNode,expressions:astNode.expressions.map((node,index2)=>addMissingDotStarTraversalAddMissing(node,isFirst&&index2===0,isLast&&index2===astNode.expressions.length-1))};case"CharacterClass":return astNode;case"ClassRange":return astNode;case"Group":return{...astNode,expression:addMissingDotStarTraversal(astNode.expression,isFirst,isLast,traversalResults)};case"Disjunction":traversalResults.hasStart=true;traversalResults.hasEnd=true;return{...astNode,left:astNode.left!==null?addMissingDotStarTraversalAddMissing(astNode.left,isFirst,isLast):null,right:astNode.right!==null?addMissingDotStarTraversalAddMissing(astNode.right,isFirst,isLast):null};case"Assertion":if(astNode.kind==="^"||astNode.kind==="Lookahead"){traversalResults.hasStart=true;return astNode}else if(astNode.kind==="$"||astNode.kind==="Lookbehind"){traversalResults.hasEnd=true;return astNode}else throw new Error(`Assertions of kind ${astNode.kind} not implemented yet!`);case"Backreference":return astNode;case"UnicodeProperty":return astNode;default:throw raiseUnsupportedASTNode$1(astNode)}}function addMissingDotStar(astNode){return addMissingDotStarTraversalAddMissing(astNode,true,true)}function charSizeAt(text,pos){return text[pos]>="\uD800"&&text[pos]<="\uDBFF"&&text[pos+1]>="\uDC00"&&text[pos+1]<="\uDFFF"?2:1}function isHexaDigit(char){return char>="0"&&char<="9"||char>="a"&&char<="f"||char>="A"&&char<="F"}function isDigit$1(char){return char>="0"&&char<="9"}function squaredBracketBlockContentEndFrom(text,from){for(let index2=from;index2!==text.length;++index2){const char=text[index2];if(char==="\\")index2+=1;else if(char==="]")return index2}throw new Error(`Missing closing ']'`)}function parenthesisBlockContentEndFrom(text,from){let numExtraOpened=0;for(let index2=from;index2!==text.length;++index2){const char=text[index2];if(char==="\\")index2+=1;else if(char===")"){if(numExtraOpened===0)return index2;numExtraOpened-=1}else if(char==="[")index2=squaredBracketBlockContentEndFrom(text,index2);else if(char==="(")numExtraOpened+=1}throw new Error(`Missing closing ')'`)}function curlyBracketBlockContentEndFrom(text,from){let foundComma=false;for(let index2=from;index2!==text.length;++index2){const char=text[index2];if(isDigit$1(char)){}else if(from===index2)return-1;else if(char===","){if(foundComma)return-1;foundComma=true}else if(char==="}")return index2;else return-1}return-1}function blockEndFrom(text,from,unicodeMode,mode){switch(text[from]){case"[":if(mode===1)return from+1;return squaredBracketBlockContentEndFrom(text,from+1)+1;case"{":{if(mode===1)return from+1;const foundEnd=curlyBracketBlockContentEndFrom(text,from+1);if(foundEnd===-1)return from+1;return foundEnd+1}case"(":if(mode===1)return from+1;return parenthesisBlockContentEndFrom(text,from+1)+1;case"]":case"}":case")":return from+1;case"\\":{const next1=text[from+1];switch(next1){case"x":if(isHexaDigit(text[from+2])&&isHexaDigit(text[from+3]))return from+4;throw new Error(`Unexpected token '${text.substring(from,from+4)}' found`);case"u":if(text[from+2]==="{"){if(!unicodeMode)return from+2;if(text[from+4]==="}"){if(isHexaDigit(text[from+3]))return from+5;throw new Error(`Unexpected token '${text.substring(from,from+5)}' found`)}if(text[from+5]==="}"){if(isHexaDigit(text[from+3])&&isHexaDigit(text[from+4]))return from+6;throw new Error(`Unexpected token '${text.substring(from,from+6)}' found`)}if(text[from+6]==="}"){if(isHexaDigit(text[from+3])&&isHexaDigit(text[from+4])&&isHexaDigit(text[from+5]))return from+7;throw new Error(`Unexpected token '${text.substring(from,from+7)}' found`)}if(text[from+7]==="}"){if(isHexaDigit(text[from+3])&&isHexaDigit(text[from+4])&&isHexaDigit(text[from+5])&&isHexaDigit(text[from+6]))return from+8;throw new Error(`Unexpected token '${text.substring(from,from+8)}' found`)}if(text[from+8]==="}"&&isHexaDigit(text[from+3])&&isHexaDigit(text[from+4])&&isHexaDigit(text[from+5])&&isHexaDigit(text[from+6])&&isHexaDigit(text[from+7]))return from+9;throw new Error(`Unexpected token '${text.substring(from,from+9)}' found`)}if(isHexaDigit(text[from+2])&&isHexaDigit(text[from+3])&&isHexaDigit(text[from+4])&&isHexaDigit(text[from+5]))return from+6;throw new Error(`Unexpected token '${text.substring(from,from+6)}' found`);case"p":case"P":{if(!unicodeMode)return from+2;let subIndex=from+2;for(;subIndex<text.length&&text[subIndex]!=="}";subIndex+=text[subIndex]==="\\"?2:1);if(text[subIndex]!=="}")throw new Error(`Invalid \\P definition`);return subIndex+1}case"k":{let subIndex=from+2;for(;subIndex<text.length&&text[subIndex]!==">";++subIndex);if(text[subIndex]!==">"){if(!unicodeMode)return from+2;throw new Error(`Invalid \\k definition`)}return subIndex+1}default:if(isDigit$1(next1)){const maxIndex=unicodeMode?text.length:Math.min(from+4,text.length);let subIndex=from+2;for(;subIndex<maxIndex&&isDigit$1(text[subIndex]);++subIndex);return subIndex}return from+(unicodeMode?charSizeAt(text,from+1):1)+1}}default:return from+(unicodeMode?charSizeAt(text,from):1)}}function readFrom(text,from,unicodeMode,mode){const to=blockEndFrom(text,from,unicodeMode,mode);return text.substring(from,to)}var NON_BINARY_ALIASES_TO_PROP_NAMES={gc:"General_Category",sc:"Script",scx:"Script_Extensions"};var BINARY_PROP_NAMES_TO_ALIASES={ASCII:"ASCII",ASCII_Hex_Digit:"AHex",Alphabetic:"Alpha",Any:"Any",Assigned:"Assigned",Bidi_Control:"Bidi_C",Bidi_Mirrored:"Bidi_M",Case_Ignorable:"CI",Cased:"Cased",Changes_When_Casefolded:"CWCF",Changes_When_Casemapped:"CWCM",Changes_When_Lowercased:"CWL",Changes_When_NFKC_Casefolded:"CWKCF",Changes_When_Titlecased:"CWT",Changes_When_Uppercased:"CWU",Dash:"Dash",Default_Ignorable_Code_Point:"DI",Deprecated:"Dep",Diacritic:"Dia",Emoji:"Emoji",Emoji_Component:"Emoji_Component",Emoji_Modifier:"Emoji_Modifier",Emoji_Modifier_Base:"Emoji_Modifier_Base",Emoji_Presentation:"Emoji_Presentation",Extended_Pictographic:"Extended_Pictographic",Extender:"Ext",Grapheme_Base:"Gr_Base",Grapheme_Extend:"Gr_Ext",Hex_Digit:"Hex",IDS_Binary_Operator:"IDSB",IDS_Trinary_Operator:"IDST",ID_Continue:"IDC",ID_Start:"IDS",Ideographic:"Ideo",Join_Control:"Join_C",Logical_Order_Exception:"LOE",Lowercase:"Lower",Math:"Math",Noncharacter_Code_Point:"NChar",Pattern_Syntax:"Pat_Syn",Pattern_White_Space:"Pat_WS",Quotation_Mark:"QMark",Radical:"Radical",Regional_Indicator:"RI",Sentence_Terminal:"STerm",Soft_Dotted:"SD",Terminal_Punctuation:"Term",Unified_Ideograph:"UIdeo",Uppercase:"Upper",Variation_Selector:"VS",White_Space:"space",XID_Continue:"XIDC",XID_Start:"XIDS"};var BINARY_ALIASES_TO_PROP_NAMES=inverseMap(BINARY_PROP_NAMES_TO_ALIASES);var GENERAL_CATEGORY_VALUE_TO_ALIASES={Cased_Letter:"LC",Close_Punctuation:"Pe",Connector_Punctuation:"Pc",Control:["Cc","cntrl"],Currency_Symbol:"Sc",Dash_Punctuation:"Pd",Decimal_Number:["Nd","digit"],Enclosing_Mark:"Me",Final_Punctuation:"Pf",Format:"Cf",Initial_Punctuation:"Pi",Letter:"L",Letter_Number:"Nl",Line_Separator:"Zl",Lowercase_Letter:"Ll",Mark:["M","Combining_Mark"],Math_Symbol:"Sm",Modifier_Letter:"Lm",Modifier_Symbol:"Sk",Nonspacing_Mark:"Mn",Number:"N",Open_Punctuation:"Ps",Other:"C",Other_Letter:"Lo",Other_Number:"No",Other_Punctuation:"Po",Other_Symbol:"So",Paragraph_Separator:"Zp",Private_Use:"Co",Punctuation:["P","punct"],Separator:"Z",Space_Separator:"Zs",Spacing_Mark:"Mc",Surrogate:"Cs",Symbol:"S",Titlecase_Letter:"Lt",Unassigned:"Cn",Uppercase_Letter:"Lu"};var GENERAL_CATEGORY_VALUE_ALIASES_TO_VALUES=inverseMap(GENERAL_CATEGORY_VALUE_TO_ALIASES);var SCRIPT_VALUE_TO_ALIASES={Adlam:"Adlm",Ahom:"Ahom",Anatolian_Hieroglyphs:"Hluw",Arabic:"Arab",Armenian:"Armn",Avestan:"Avst",Balinese:"Bali",Bamum:"Bamu",Bassa_Vah:"Bass",Batak:"Batk",Bengali:"Beng",Bhaiksuki:"Bhks",Bopomofo:"Bopo",Brahmi:"Brah",Braille:"Brai",Buginese:"Bugi",Buhid:"Buhd",Canadian_Aboriginal:"Cans",Carian:"Cari",Caucasian_Albanian:"Aghb",Chakma:"Cakm",Cham:"Cham",Cherokee:"Cher",Common:"Zyyy",Coptic:["Copt","Qaac"],Cuneiform:"Xsux",Cypriot:"Cprt",Cyrillic:"Cyrl",Deseret:"Dsrt",Devanagari:"Deva",Dogra:"Dogr",Duployan:"Dupl",Egyptian_Hieroglyphs:"Egyp",Elbasan:"Elba",Ethiopic:"Ethi",Georgian:"Geor",Glagolitic:"Glag",Gothic:"Goth",Grantha:"Gran",Greek:"Grek",Gujarati:"Gujr",Gunjala_Gondi:"Gong",Gurmukhi:"Guru",Han:"Hani",Hangul:"Hang",Hanifi_Rohingya:"Rohg",Hanunoo:"Hano",Hatran:"Hatr",Hebrew:"Hebr",Hiragana:"Hira",Imperial_Aramaic:"Armi",Inherited:["Zinh","Qaai"],Inscriptional_Pahlavi:"Phli",Inscriptional_Parthian:"Prti",Javanese:"Java",Kaithi:"Kthi",Kannada:"Knda",Katakana:"Kana",Kayah_Li:"Kali",Kharoshthi:"Khar",Khmer:"Khmr",Khojki:"Khoj",Khudawadi:"Sind",Lao:"Laoo",Latin:"Latn",Lepcha:"Lepc",Limbu:"Limb",Linear_A:"Lina",Linear_B:"Linb",Lisu:"Lisu",Lycian:"Lyci",Lydian:"Lydi",Mahajani:"Mahj",Makasar:"Maka",Malayalam:"Mlym",Mandaic:"Mand",Manichaean:"Mani",Marchen:"Marc",Medefaidrin:"Medf",Masaram_Gondi:"Gonm",Meetei_Mayek:"Mtei",Mende_Kikakui:"Mend",Meroitic_Cursive:"Merc",Meroitic_Hieroglyphs:"Mero",Miao:"Plrd",Modi:"Modi",Mongolian:"Mong",Mro:"Mroo",Multani:"Mult",Myanmar:"Mymr",Nabataean:"Nbat",New_Tai_Lue:"Talu",Newa:"Newa",Nko:"Nkoo",Nushu:"Nshu",Ogham:"Ogam",Ol_Chiki:"Olck",Old_Hungarian:"Hung",Old_Italic:"Ital",Old_North_Arabian:"Narb",Old_Permic:"Perm",Old_Persian:"Xpeo",Old_Sogdian:"Sogo",Old_South_Arabian:"Sarb",Old_Turkic:"Orkh",Oriya:"Orya",Osage:"Osge",Osmanya:"Osma",Pahawh_Hmong:"Hmng",Palmyrene:"Palm",Pau_Cin_Hau:"Pauc",Phags_Pa:"Phag",Phoenician:"Phnx",Psalter_Pahlavi:"Phlp",Rejang:"Rjng",Runic:"Runr",Samaritan:"Samr",Saurashtra:"Saur",Sharada:"Shrd",Shavian:"Shaw",Siddham:"Sidd",SignWriting:"Sgnw",Sinhala:"Sinh",Sogdian:"Sogd",Sora_Sompeng:"Sora",Soyombo:"Soyo",Sundanese:"Sund",Syloti_Nagri:"Sylo",Syriac:"Syrc",Tagalog:"Tglg",Tagbanwa:"Tagb",Tai_Le:"Tale",Tai_Tham:"Lana",Tai_Viet:"Tavt",Takri:"Takr",Tamil:"Taml",Tangut:"Tang",Telugu:"Telu",Thaana:"Thaa",Thai:"Thai",Tibetan:"Tibt",Tifinagh:"Tfng",Tirhuta:"Tirh",Ugaritic:"Ugar",Vai:"Vaii",Warang_Citi:"Wara",Yi:"Yiii",Zanabazar_Square:"Zanb"};var SCRIPT_VALUE_ALIASES_TO_VALUES=inverseMap(SCRIPT_VALUE_TO_ALIASES);function inverseMap(data){const inverse={};for(const name of Object.keys(data)){const value3=data[name];if(Array.isArray(value3))for(let i=0;i!==value3.length;++i)inverse[value3[i]]=name;else inverse[value3]=name}return inverse}function isGeneralCategoryValue(value3){return value3 in GENERAL_CATEGORY_VALUE_TO_ALIASES||value3 in GENERAL_CATEGORY_VALUE_ALIASES_TO_VALUES}function isBinaryPropertyName(name){return name in BINARY_PROP_NAMES_TO_ALIASES||name in BINARY_ALIASES_TO_PROP_NAMES}function getCanonicalName(name){if(name in NON_BINARY_ALIASES_TO_PROP_NAMES)return NON_BINARY_ALIASES_TO_PROP_NAMES[name];if(name in BINARY_ALIASES_TO_PROP_NAMES)return BINARY_ALIASES_TO_PROP_NAMES[name];if(name in BINARY_PROP_NAMES_TO_ALIASES||name==="General_Category"||name==="Script"||name==="Script_Extensions")return name;throw new Error(`Unknown Unicode property name: ${name}`)}function getCanonicalValue(value3){if(value3 in GENERAL_CATEGORY_VALUE_ALIASES_TO_VALUES)return GENERAL_CATEGORY_VALUE_ALIASES_TO_VALUES[value3];if(value3 in SCRIPT_VALUE_ALIASES_TO_VALUES)return SCRIPT_VALUE_ALIASES_TO_VALUES[value3];if(value3 in BINARY_ALIASES_TO_PROP_NAMES)return BINARY_ALIASES_TO_PROP_NAMES[value3];if(value3 in GENERAL_CATEGORY_VALUE_TO_ALIASES||value3 in SCRIPT_VALUE_TO_ALIASES||value3 in BINARY_PROP_NAMES_TO_ALIASES)return value3;throw new Error(`Unknown Unicode property value: ${value3}`)}function resolveUnicodeProperty(propertySpec,negative){const equalIndex=propertySpec.indexOf("=");if(equalIndex!==-1){const name=propertySpec.substring(0,equalIndex);const value3=propertySpec.substring(equalIndex+1);return{type:"UnicodeProperty",name,value:value3,negative,shorthand:false,binary:false,canonicalName:getCanonicalName(name),canonicalValue:getCanonicalValue(value3)}}if(isGeneralCategoryValue(propertySpec))return{type:"UnicodeProperty",name:"General_Category",value:propertySpec,negative,shorthand:true,binary:false,canonicalName:"General_Category",canonicalValue:getCanonicalValue(propertySpec)};if(isBinaryPropertyName(propertySpec)){const canonicalName=getCanonicalName(propertySpec);return{type:"UnicodeProperty",name:propertySpec,value:propertySpec,negative,shorthand:false,binary:true,canonicalName,canonicalValue:canonicalName}}throw new Error(`Invalid Unicode property: ${propertySpec}`)}var safeStringFromCodePoint$2=String.fromCodePoint;function safePop(tokens){const previous=tokens.pop();if(previous===undefined)throw new Error("Unable to extract token preceeding the currently parsed one");return previous}function isDigit(char){return char>="0"&&char<="9"}function simpleChar(char,escaped){return{type:"Char",kind:"simple",symbol:char,value:char,codePoint:char.codePointAt(0)||-1,escaped}}function metaEscapedChar(block,symbol4){return{type:"Char",kind:"meta",symbol:symbol4,value:block,codePoint:symbol4.codePointAt(0)||-1}}function toSingleToken(tokens,allowEmpty){if(tokens.length>1)return{type:"Alternative",expressions:tokens};if(!allowEmpty&&tokens.length===0)throw new Error(`Unsupported no token`);return tokens[0]}function blockToCharToken(block){if(block[0]==="\\"){const next=block[1];switch(next){case"x":{const allDigits=block.substring(2);const codePoint=Number.parseInt(allDigits,16);return{type:"Char",kind:"hex",symbol:safeStringFromCodePoint$2(codePoint),value:block,codePoint}}case"u":{if(block==="\\u")return simpleChar("u",true);const allDigits=block[2]==="{"?block.substring(3,block.length-1):block.substring(2);const codePoint=Number.parseInt(allDigits,16);return{type:"Char",kind:"unicode",symbol:safeStringFromCodePoint$2(codePoint),value:block,codePoint}}case"0":return metaEscapedChar(block,"\x00");case"n":return metaEscapedChar(block,`
223
223
  `);case"f":return metaEscapedChar(block,"\f");case"r":return metaEscapedChar(block,"\r");case"t":return metaEscapedChar(block,"\t");case"v":return metaEscapedChar(block,"\v");case"w":case"W":case"d":case"D":case"s":case"S":case"b":case"B":return{type:"Char",kind:"meta",symbol:undefined,value:block,codePoint:NaN};default:if(isDigit(next)){const allDigits=block.substring(1);const codePoint=Number(allDigits);return{type:"Char",kind:"decimal",symbol:safeStringFromCodePoint$2(codePoint),value:block,codePoint}}if(block.length>2&&(next==="p"||next==="P")){const negative=next==="P";return resolveUnicodeProperty(block.substring(3,block.length-1),negative)}return simpleChar(block.substring(1),true)}}return simpleChar(block)}function pushTokens(tokens,regexSource,unicodeMode,groups){let disjunctions=null;for(let index2=0,block=readFrom(regexSource,index2,unicodeMode,0);index2!==regexSource.length;index2+=block.length,block=readFrom(regexSource,index2,unicodeMode,0)){const firstInBlock=block[0];switch(firstInBlock){case"|":if(disjunctions===null)disjunctions=[];disjunctions.push(toSingleToken(tokens.splice(0),true)||null);break;case".":tokens.push({type:"Char",kind:"meta",symbol:block,value:block,codePoint:NaN});break;case"*":case"+":{const previous=safePop(tokens);tokens.push({type:"Repetition",expression:previous,quantifier:{type:"Quantifier",kind:firstInBlock,greedy:true}});break}case"?":{const previous=safePop(tokens);if(previous.type==="Repetition"){previous.quantifier.greedy=false;tokens.push(previous)}else tokens.push({type:"Repetition",expression:previous,quantifier:{type:"Quantifier",kind:firstInBlock,greedy:true}});break}case"{":{if(block==="{"){tokens.push(simpleChar(block));break}const previous=safePop(tokens);const quantifierTokens=block.substring(1,block.length-1).split(",");const from=Number(quantifierTokens[0]);const to=quantifierTokens.length===1?from:quantifierTokens[1].length!==0?Number(quantifierTokens[1]):undefined;tokens.push({type:"Repetition",expression:previous,quantifier:{type:"Quantifier",kind:"Range",greedy:true,from,to}});break}case"[":{const blockContent=block.substring(1,block.length-1);const subTokens=[];let negative=undefined;let previousWasSimpleDash=false;for(let subIndex=0,subBlock=readFrom(blockContent,subIndex,unicodeMode,1);subIndex!==blockContent.length;subIndex+=subBlock.length,subBlock=readFrom(blockContent,subIndex,unicodeMode,1)){if(subIndex===0&&subBlock==="^"){negative=true;continue}const newToken=blockToCharToken(subBlock);if(subBlock==="-"){subTokens.push(newToken);previousWasSimpleDash=true}else{const operand1Token=subTokens.length>=2?subTokens[subTokens.length-2]:undefined;if(previousWasSimpleDash&&operand1Token!==undefined&&operand1Token.type==="Char"&&newToken.type==="Char"){subTokens.pop();subTokens.pop();subTokens.push({type:"ClassRange",from:operand1Token,to:newToken})}else subTokens.push(newToken);previousWasSimpleDash=false}}tokens.push({type:"CharacterClass",expressions:subTokens,negative});break}case"(":{const blockContent=block.substring(1,block.length-1);const subTokens=[];if(blockContent[0]==="?")if(blockContent[1]===":"){pushTokens(subTokens,blockContent.substring(2),unicodeMode,groups);tokens.push({type:"Group",capturing:false,expression:toSingleToken(subTokens)})}else if(blockContent[1]==="="||blockContent[1]==="!"){pushTokens(subTokens,blockContent.substring(2),unicodeMode,groups);tokens.push({type:"Assertion",kind:"Lookahead",negative:blockContent[1]==="!"?true:undefined,assertion:toSingleToken(subTokens)})}else if(blockContent[1]==="<"&&(blockContent[2]==="="||blockContent[2]==="!")){pushTokens(subTokens,blockContent.substring(3),unicodeMode,groups);tokens.push({type:"Assertion",kind:"Lookbehind",negative:blockContent[2]==="!"?true:undefined,assertion:toSingleToken(subTokens)})}else{const chunks=blockContent.split(">");if(chunks.length<2||chunks[0][1]!=="<")throw new Error(`Unsupported regex content found at ${JSON.stringify(block)}`);const groupIndex=++groups.lastIndex;const nameRaw=chunks[0].substring(2);groups.named.set(nameRaw,groupIndex);pushTokens(subTokens,chunks.slice(1).join(">"),unicodeMode,groups);tokens.push({type:"Group",capturing:true,nameRaw,name:nameRaw,number:groupIndex,expression:toSingleToken(subTokens)})}else{const groupIndex=++groups.lastIndex;pushTokens(subTokens,blockContent,unicodeMode,groups);tokens.push({type:"Group",capturing:true,number:groupIndex,expression:toSingleToken(subTokens)})}break}default:if(block==="^")tokens.push({type:"Assertion",kind:block});else if(block==="$")tokens.push({type:"Assertion",kind:block});else if(block[0]==="\\"&&isDigit(block[1])){const reference=Number(block.substring(1));if(unicodeMode||reference<=groups.lastIndex)tokens.push({type:"Backreference",kind:"number",number:reference,reference});else tokens.push(blockToCharToken(block))}else if(block[0]==="\\"&&block[1]==="k"&&block.length!==2){const referenceRaw=block.substring(3,block.length-1);tokens.push({type:"Backreference",kind:"name",number:groups.named.get(referenceRaw)||0,referenceRaw,reference:referenceRaw})}else tokens.push(blockToCharToken(block));break}}if(disjunctions!==null){disjunctions.push(toSingleToken(tokens.splice(0),true)||null);let currentDisjunction={type:"Disjunction",left:disjunctions[0],right:disjunctions[1]};for(let index2=2;index2<disjunctions.length;++index2)currentDisjunction={type:"Disjunction",left:currentDisjunction,right:disjunctions[index2]};tokens.push(currentDisjunction)}}function tokenizeRegex(regex){const unicodeMode=safeIndexOf([...regex.flags],"u")!==-1;const regexSource=regex.source;const tokens=[];pushTokens(tokens,regexSource,unicodeMode,{lastIndex:0,named:new Map});return toSingleToken(tokens)}var safeStringFromCodePoint$1=String.fromCodePoint;function getPropertySpec(astNode){if(astNode.binary||astNode.shorthand)return astNode.canonicalValue;return`${astNode.canonicalName}=${astNode.canonicalValue}`}function appendRangesForRegex(regex,from,to,ranges){let currentRangeStart=-1;for(let cp=from;cp<=to;++cp)if(regex.test(safeStringFromCodePoint$1(cp))){if(currentRangeStart===-1)currentRangeStart=cp}else if(currentRangeStart!==-1){const rangeEnd=cp-1;ranges.push(currentRangeStart===rangeEnd?[rangeEnd]:[currentRangeStart,rangeEnd]);currentRangeStart=-1}if(currentRangeStart!==-1)ranges.push(currentRangeStart===to?[to]:[currentRangeStart,to])}function extractRangesForProperty(propertySpec,negative){const regex=new RegExp(`^\\${negative?"P":"p"}{${propertySpec}}$`,"u");const ranges=[];appendRangesForRegex(regex,0,55295,ranges);appendRangesForRegex(regex,57344,1114111,ranges);return ranges}var cache=new Map;function extractRangesForPropertyOrFromCache(propertySpec,negative){const cacheKey=`${negative?"P":"p"}:${propertySpec}`;const cachedRanges=cache.get(cacheKey);if(cachedRanges!==undefined)return cachedRanges;const ranges=extractRangesForProperty(propertySpec,negative);cache.set(cacheKey,ranges);return ranges}function unicodePropertyArbitrary(astNode){return mapToConstant(...safeMap(extractRangesForPropertyOrFromCache(getPropertySpec(astNode),astNode.negative),(range2)=>convertGraphemeRangeToMapToConstantEntry(range2)))}var safeStringFromCodePoint=String.fromCodePoint;var wordChars=[..."abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"];var digitChars=[..."0123456789"];var spaceChars=[...` \r
224
224
  \v\f`];var newLineChars=[...`\r
@@ -322,7 +322,7 @@ ${colorRail2({environment,headingTone:"accent",rail:reflowRail(guide,environment
322
322
  `){++position}discardTrailingNewline=false}let lineLength=-1;let fieldLength=startingFieldLength;let character;for(let index2=startingPosition;lineLength<0&&index2<length;++index2){character=buffer2[index2];if(character===":"&&fieldLength<0){fieldLength=index2-position}else if(character==="\r"){discardTrailingNewline=true;lineLength=index2-position}else if(character===`
323
323
  `){lineLength=index2-position}}if(lineLength<0){startingPosition=length-position;startingFieldLength=fieldLength;break}else{startingPosition=0;startingFieldLength=-1}parseEventStreamLine(buffer2,position,fieldLength,lineLength);position+=lineLength+1}if(position===length){buffer2=""}else if(position>0){buffer2=buffer2.slice(position)}}function parseEventStreamLine(lineBuffer,index2,fieldLength,lineLength){if(lineLength===0){if(data.length>0){onParse({_tag:"Event",id:eventId,event:eventName??"message",data:data.slice(0,-1)});data="";eventId=undefined}eventName=undefined;return}const noValue=fieldLength<0;const field=lineBuffer.slice(index2,index2+(noValue?lineLength:fieldLength));let step=0;if(noValue){step=lineLength}else if(lineBuffer[index2+fieldLength+1]===" "){step=fieldLength+2}else{step=fieldLength+1}const position=index2+step;const valueLength=lineLength-step;const value5=lineBuffer.slice(position,position+valueLength).toString();if(field==="data"){data+=value5?`${value5}
324
324
  `:`
325
- `}else if(field==="event"){eventName=value5}else if(field==="id"&&!value5.includes("\x00")){eventId=value5;lastEventId=value5}else if(field==="retry"){const retry5=parseInt(value5,10);if(!Number.isNaN(retry5)){onParse(new Retry({duration:millis(retry5),lastEventId}))}}}}var BOM=[239,187,191];function hasBom(buffer2){return BOM.every((charCode,index2)=>buffer2.charCodeAt(index2)===charCode)}var EventEncoded=Struct({id:optional(String5),event:String5,data:String5});var RetryTypeId="~effect/encoding/Sse/Retry";class Retry extends TaggedClass("Retry"){[RetryTypeId]=RetryTypeId;static is(u){return hasProperty(u,RetryTypeId)}static filter(u){return Retry.is(u)?succeed2(u):fail2(u)}}var SecurityTypeId="~effect/httpapi/HttpApiMiddleware/Security";var isSecurity=(u)=>hasProperty(u,SecurityTypeId);var exports_OpenApi={};__export(exports_OpenApi,{fromApi:()=>fromApi,annotations:()=>annotations,Version:()=>Version2,Transform:()=>Transform,Title:()=>Title,Summary:()=>Summary,Servers:()=>Servers,Override:()=>Override,License:()=>License,Identifier:()=>Identifier,Format:()=>Format,ExternalDocs:()=>ExternalDocs,Exclude:()=>Exclude,Description:()=>Description,Deprecated:()=>Deprecated});class Identifier extends Service()("effect/httpapi/OpenApi/Identifier"){}class Title extends Service()("effect/httpapi/OpenApi/Title"){}class Version2 extends Service()("effect/httpapi/OpenApi/Version"){}class Description extends Service()("effect/httpapi/OpenApi/Description"){}class License extends Service()("effect/httpapi/OpenApi/License"){}class ExternalDocs extends Service()("effect/httpapi/OpenApi/ExternalDocs"){}class Servers extends Service()("effect/httpapi/OpenApi/Servers"){}class Format extends Service()("effect/httpapi/OpenApi/Format"){}class Summary extends Service()("effect/httpapi/OpenApi/Summary"){}class Deprecated extends Service()("effect/httpapi/OpenApi/Deprecated"){}class Override extends Service()("effect/httpapi/OpenApi/Override"){}var Exclude=Reference("effect/httpapi/OpenApi/Exclude",{defaultValue:constFalse});class Transform extends Service()("effect/httpapi/OpenApi/Transform"){}var servicesPartial=(tags2)=>{const entries3=Object.entries(tags2);return(options4)=>{let context4=empty();for(const[key,tag4]of entries3){if(options4[key]!==undefined){context4=add(context4,tag4,options4[key])}}return context4}};var annotations=servicesPartial({identifier:Identifier,title:Title,version:Version2,description:Description,license:License,summary:Summary,deprecated:Deprecated,externalDocs:ExternalDocs,servers:Servers,format:Format,override:Override,exclude:Exclude,transform:Transform});var apiCache=new WeakMap;function processAnnotation(ctx,annotation,f){const o=getOption(ctx,annotation);if(isSome2(o)){f(o.value)}}function fromApi(api){const cached3=apiCache.get(api);if(cached3!==undefined){return cached3}let spec={openapi:"3.1.0",info:{title:"Api",version:"0.0.1"},paths:{},components:{schemas:{},securitySchemes:{}},security:[],tags:[]};const pathOps=[];const pathOperations=new Set;const operationIds=new Set;processAnnotation(api.annotations,Title,(title)=>{spec.info.title=title});processAnnotation(api.annotations,Version2,(version2)=>{spec.info.version=version2});processAnnotation(api.annotations,Description,(description)=>{spec.info.description=description});processAnnotation(api.annotations,License,(license)=>{spec.info.license=license});processAnnotation(api.annotations,Summary,(summary)=>{spec.info.summary=summary});processAnnotation(api.annotations,Servers,(servers)=>{spec.servers=[...servers]});reflect(api,{onGroup({group}){if(get(group.annotations,Exclude)){return}let tag4={name:getOrElse2(group.annotations,Title,()=>group.identifier)};processAnnotation(group.annotations,Description,(description)=>{tag4.description=description});processAnnotation(group.annotations,ExternalDocs,(externalDocs)=>{tag4.externalDocs=externalDocs});processAnnotation(group.annotations,Override,(override)=>{Object.assign(tag4,override)});processAnnotation(group.annotations,Transform,(transformFn)=>{tag4=transformFn(tag4)});spec.tags.push(tag4)},onEndpoint({endpoint,group,mergedAnnotations,middleware:middleware2}){if(get(mergedAnnotations,Exclude)){return}let op={tags:[getOrElse2(group.annotations,Title,()=>group.identifier)],operationId:getOrElse2(endpoint.annotations,Identifier,()=>group.topLevel?endpoint.identifier:`${group.identifier}.${endpoint.identifier}`),parameters:[],security:[],responses:{}};const path4=endpoint.path.replace(/:(\w+)\??/g,"{$1}");const method=endpoint.method.toLowerCase();function processResponseBodies(bodies,defaultDescription){for(const[status2,{content,descriptions,streamContent}]of bodies){const description=descriptions.size>0?Array.from(descriptions).join(" | "):defaultDescription();op.responses[status2]={description};if(content!==undefined){content.forEach((map18,encoding)=>{map18.forEach((schemas,contentType)=>{const asts=Array.from(schemas,getAST);const ast=asts.length===1?asts[0]:new Union(asts,"anyOf");pathOps.push({_tag:"schema",ast:toEncodingAST(ast,encoding),path:["paths",path4,method,"responses",String(status2),"content",contentType,"schema"]});op.responses[status2].content??={};op.responses[status2].content[contentType]={schema:{}}})})}if(streamContent!==undefined){streamContent.forEach((stream3,contentType)=>{op.responses[status2].content??={};if(isStreamSse(stream3)){pathOps.push({_tag:"schema",ast:getAST(stream3.events),path:["paths",path4,method,"responses",String(status2),"content",contentType,"schema"]});pathOps.push({_tag:"schema",ast:getAST(toCodecJson(Cause(stream3.error,Defect()))),path:["paths",path4,method,"responses",String(status2),"content",contentType,"x-effect-stream","causeSchema"]});pathOps.push({_tag:"schema",ast:getAST(stream3.error),path:["paths",path4,method,"responses",String(status2),"content",contentType,"x-effect-stream","errorSchema"]});op.responses[status2].content[contentType]={schema:{},"x-effect-stream":{encoding:"sse",causeSchema:{},errorSchema:{},failureEvent:reservedStreamFailureEvent2}}}else{op.responses[status2].content[contentType]={schema:{type:"string",format:"binary"},"x-effect-stream":{encoding:"uint8array"}}}})}}}function processParameters(schema2,i){if(schema2){const ast=getLastEncoding(schema2.ast);if(isObjects(ast)){for(const ps of ast.propertySignatures){op.parameters.push({name:String(ps.name),in:i,schema:{},required:i==="path"||!isOptional(ps.type)});pathOps.push({_tag:"parameter",ast:ps.type,path:["paths",path4,method,"parameters",String(op.parameters.length-1),"schema"]})}}}}processAnnotation(endpoint.annotations,Description,(description)=>{op.description=description});processAnnotation(endpoint.annotations,Summary,(summary)=>{op.summary=summary});processAnnotation(endpoint.annotations,Deprecated,(deprecated)=>{op.deprecated=deprecated});processAnnotation(endpoint.annotations,ExternalDocs,(externalDocs)=>{op.externalDocs=externalDocs});middleware2.forEach((middleware3)=>{if(!isSecurity(middleware3)){return}for(const[name,security]of Object.entries(middleware3.security)){processHttpApiSecurity(name,security);op.security.push({[name]:[]})}});function processHttpApiSecurity(name,security){const scheme=makeSecurityScheme(security);if(!Object.hasOwn(spec.components.securitySchemes,name)){set(spec.components.securitySchemes,name,scheme);return}if(!equals(securitySchemeForComparison(spec.components.securitySchemes[name]),securitySchemeForComparison(scheme))){throw new globalThis.Error(`Conflicting OpenAPI security scheme: ${name}`)}}const hasBody2=hasBody(endpoint.method);if(hasBody2){const schemasByContentType=new Map;for(const schema2 of getPayloadSchemas(endpoint)){if(isNoContent(schema2.ast))continue;const encoding=getPayloadEncoding(schema2.ast,endpoint.method);const existing=schemasByContentType.get(encoding.contentType);if(existing===undefined){schemasByContentType.set(encoding.contentType,{encoding,schemas:[schema2]})}else{existing.schemas.push(schema2)}}if(schemasByContentType.size>0){const content={};for(const[contentType,{encoding,schemas}]of schemasByContentType){const asts=schemas.map(getAST);const ast=asts.length===1?asts[0]:new Union(asts,"anyOf");pathOps.push({_tag:"schema",ast:toEncodingAST(ast,encoding._tag),path:["paths",path4,method,"requestBody","content",contentType,"schema"]});content[contentType]={schema:{}}}op.requestBody={content,required:true}}}processParameters(endpoint.params,"path");if(!hasBody2&&endpoint.payload.size===1){const entry=endpoint.payload.values().next().value;processParameters(entry.schemas[0],"query")}processParameters(endpoint.headers,"header");processParameters(endpoint.query,"query");processResponseBodies(extractSuccessResponseBodies(endpoint),()=>"Success");processResponseBodies(extractResponseBodies(getErrorSchemas(endpoint),getStatusError,resolveDescriptionOrIdentifier),()=>"Error");processAnnotation(endpoint.annotations,Override,(override)=>{Object.assign(op,override)});processAnnotation(endpoint.annotations,Transform,(transformFn)=>{op=transformFn(op)});const pathOperation=`${method} ${path4.replace(/\{[^}]+\}/g,"{}")}`;if(pathOperations.has(pathOperation)){throw new globalThis.Error(`Duplicate OpenAPI operation for ${endpoint.method} ${path4}`)}const operationId=op.operationId;if(operationId!==undefined){if(operationIds.has(operationId)){throw new globalThis.Error(`Duplicate OpenAPI operationId: ${operationId}`)}operationIds.add(operationId)}pathOperations.add(pathOperation);if(!spec.paths[path4]){spec.paths[path4]={}}spec.paths[path4][method]=op}});processAnnotation(api.annotations,AdditionalSchemas,(componentSchemas)=>{componentSchemas.forEach((componentSchema)=>{const identifier2=resolveIdentifier2(componentSchema.ast);if(identifier2!==undefined){if(identifier2 in spec.components.schemas){throw new globalThis.Error(`Duplicate component schema identifier: ${identifier2}`)}spec.components.schemas[identifier2]={};pathOps.push({_tag:"schema",ast:componentSchema.ast,path:["components","schemas",identifier2]})}})});function escapePath(path4){return"/"+path4.map(escapeToken).join("/")}if(isArrayNonEmpty2(pathOps)){const multiDocument=fromASTs2(map4(pathOps,(op)=>op.ast));const jsonSchemaMultiDocument=toMultiDocumentOpenApi3_1(toJsonSchemaMultiDocument2(multiDocument));const patchOps=pathOps.map((op,i)=>{const oppath=escapePath(op.path);const value5=jsonSchemaMultiDocument.schemas[i];return{op:"replace",path:oppath,value:value5}});Object.entries(jsonSchemaMultiDocument.definitions).forEach(([name,definition])=>{patchOps.push({op:"add",path:escapePath(["components","schemas",name]),value:definition})});spec=apply(patchOps,spec)}Object.keys(spec.components.schemas).forEach((key)=>{if(!VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP.test(key)){throw new globalThis.Error(`Invalid component schema key: ${key}`)}});processAnnotation(api.annotations,Override,(override)=>{Object.assign(spec,override)});processAnnotation(api.annotations,Transform,(transformFn)=>{spec=transformFn(spec)});apiCache.set(api,spec);return spec}var reservedStreamFailureEvent2="effect/httpapi/stream/failure";function extractSuccessResponseBodies(endpoint){return extractResponseBodies(getSuccessSchemas(endpoint),getStatusSuccess,resolveDescriptionOrIdentifier)}function extractResponseBodies(schemas,getStatus,getDescription){const map18=new Map;schemas.forEach(process2);return map18;function process2(schema2){if(isStreamSchema(schema2)){addStreamContent(schema2);return}const ast=schema2.ast;const status2=getStatus(ast);if(isNoContent(ast)){addNoContent(status2,getDescription(schema2.ast)??"<No Content>")}else{addContent(schema2,status2,getResponseEncoding(ast))}}function addNoContent(status2,description){const statusMap=map18.get(status2);if(statusMap===undefined){map18.set(status2,{descriptions:new Set([description]),content:undefined,streamContent:undefined})}else{if(description!==undefined){statusMap.descriptions.add(description)}}}function addContent(schema2,status2,encoding){const description=getDescription(schema2.ast);const statusMap=map18.get(status2);const{_tag,contentType}=encoding;if(statusMap===undefined){map18.set(status2,{descriptions:new Set(description!==undefined?[description]:[]),content:new Map([[_tag,new Map([[contentType,new Set([schema2])]])]]),streamContent:undefined})}else{if(description!==undefined){statusMap.descriptions.add(description)}if(statusMap.content===undefined){statusMap.content=new Map([[_tag,new Map([[contentType,new Set([schema2])]])]])}else{const schemasByContentType=statusMap.content.get(_tag);if(schemasByContentType===undefined){statusMap.content.set(_tag,new Map([[contentType,new Set([schema2])]]))}else{const set7=schemasByContentType.get(contentType);if(set7===undefined){schemasByContentType.set(contentType,new Set([schema2]))}else{set7.add(schema2)}}}}}function addStreamContent(stream3){const status2=getStatusStream(stream3);const statusMap=map18.get(status2);if(statusMap===undefined){map18.set(status2,{descriptions:new Set,content:undefined,streamContent:new Map([[stream3.contentType,stream3]])})}else if(statusMap.streamContent===undefined){statusMap.streamContent=new Map([[stream3.contentType,stream3]])}else{statusMap.streamContent.set(stream3.contentType,stream3)}}}function resolveDescriptionOrIdentifier(ast){return resolveDescription2(ast)??resolveIdentifier2(ast)}var Uint8ArrayEncoding=String5.annotate({format:"binary"});function toEncodingAST(ast,_tag){switch(_tag){case"Uint8Array":return Uint8ArrayEncoding.ast;case"Text":return String5.ast;case"FormUrlEncoded":case"Json":return ast;case"Multipart":return persistedFileToBinaryEncoding(ast)}}function persistedFileToBinaryEncoding(ast){if(isDeclaration(ast)&&ast.annotations?.typeConstructor?._tag==="effect/http/PersistedFile"){return Uint8ArrayEncoding.ast}if(typeof ast?.recur==="function"){return ast.recur(persistedFileToBinaryEncoding)}return ast}var makeSecurityScheme=(security)=>{const meta={};processAnnotation(security.annotations,Description,(description)=>{meta.description=description});switch(security._tag){case"Basic":{return{...meta,type:"http",scheme:"basic"}}case"Http":{const format5=getOption(security.annotations,Format).pipe(map((format6)=>({bearerFormat:format6})),getOrUndefined);return{...meta,type:"http",scheme:security.scheme,...format5}}case"ApiKey":{return{...meta,type:"apiKey",name:security.key,in:security.in}}}};var securitySchemeForComparison=(scheme)=>{if(scheme.type==="http"){return{...scheme,scheme:scheme.scheme.toLowerCase()}}if(scheme.in==="header"){return{...scheme,name:scheme.name.toLowerCase()}}return scheme};var exports_HttpApiClient={};__export(exports_HttpApiClient,{urlBuilder:()=>urlBuilder,makeWith:()=>makeWith3,makeClient:()=>makeClient,make:()=>make46,group:()=>group,endpoint:()=>endpoint});var makeClient=(api,options4)=>gen2(function*(){const services=yield*context2();const httpClient=options4.httpClient.pipe(options4?.baseUrl===undefined?identity:mapRequest(prependUrl(options4.baseUrl.toString())));function executeMiddleware(group,endpoint,request3,middlewareKeys,index2){if(index2===-1){return httpClient.execute(request3)}const middleware2=services.mapUnsafe.get(middlewareKeys[index2]);if(middleware2===undefined){return executeMiddleware(group,endpoint,request3,middlewareKeys,index2-1)}return middleware2({endpoint,group,request:request3,next(request4){return executeMiddleware(group,endpoint,request4,middlewareKeys,index2-1)}})}reflect(api,{predicate:options4?.predicate,onGroup(onGroupOptions){options4.onGroup?.(onGroupOptions)},onEndpoint(onEndpointOptions){const{group,endpoint,errors:errors2,successes}=onEndpointOptions;const makeUrl=compilePath(endpoint.path);const decodeMap={orElse:statusOrElse};const decodeResponse=matchStatus(decodeMap);const errorAlternatives=new Map;for(const[status2,schemas]of errors2.entries()){const grouped=groupSchemasByContentType(schemas);for(const[contentType,schemas2]of grouped.entries()){addResponseAlternative(errorAlternatives,status2,contentType,schemasToResponse(schemas2))}}for(const[status2,alternatives]of errorAlternatives.entries()){const decode4=makeResponseDecoder(alternatives);decodeMap[status2]=(response)=>flatMap4(catchCause2(decode4(response),(cause)=>failCause3(combine2(fail5(new HttpClientError({reason:new StatusCodeError({request:response.request,response})})),cause))),fail6)}const successAlternatives=new Map;for(const[status2,schemas]of successes.entries()){const grouped=groupSchemasByContentType(schemas);for(const[contentType,schemas2]of grouped.entries()){addResponseAlternative(successAlternatives,status2,contentType,schemasToResponse(schemas2))}}for(const streamSuccess of getStreamSuccessSchemas(endpoint)){addResponseAlternative(successAlternatives,getStatusStream(streamSuccess),streamSuccess.contentType,streamToResponse(streamSuccess))}for(const[status2,alternatives]of successAlternatives.entries()){decodeMap[status2]=makeResponseDecoder(alternatives)}const encodeParams=map12(endpoint.params,encodeUnknownEffect2);const payloadSchemas=getPayloadSchemas(endpoint);const encodePayload=isArrayNonEmpty2(payloadSchemas)?hasBody(endpoint.method)?encodeUnknownEffect2(getEncodePayloadSchema(payloadSchemas,endpoint.method)):encodeUnknownEffect2(Union2(payloadSchemas)):undefined;const encodeHeaders=map12(endpoint.headers,encodeUnknownEffect2);const encodeQuery=map12(endpoint.query,encodeUnknownEffect2);const middlewareKeys=Array.from(onEndpointOptions.middleware,(tag4)=>`${tag4.key}/Client`);const endpointFn=fnUntraced2(function*(request3){let httpRequest=make42(endpoint.method)(endpoint.path);if(request3!==undefined){if(encodeParams!==undefined){const params=yield*encodeParams(request3.params);httpRequest=setUrl(httpRequest,makeUrl(params))}if(encodePayload!==undefined){if(hasBody(endpoint.method)){if(request3.payload instanceof FormData){httpRequest=bodyFormData(httpRequest,request3.payload)}else{const body=yield*encodePayload(request3.payload);httpRequest=setBody(httpRequest,body)}}else{const urlParams2=yield*encodePayload(request3.payload);httpRequest=appendUrlParams(httpRequest,urlParams2)}}if(encodeHeaders!==undefined){const headers=yield*encodeHeaders(request3.headers);httpRequest=setHeaders(httpRequest,headers)}if(encodeQuery!==undefined){const query=yield*encodeQuery(request3.query);httpRequest=appendUrlParams(httpRequest,query)}}const response=yield*executeMiddleware(group,endpoint,httpRequest,middlewareKeys,middlewareKeys.length-1);if(request3?.responseMode==="response-only"){return response}const value5=yield*options4.transformResponse===undefined?decodeResponse(response):options4.transformResponse(decodeResponse(response));return request3?.responseMode==="decoded-and-response"?[value5,response]:value5});options4.onEndpoint({...onEndpointOptions,endpointFn})}})});var make46=(api,options4)=>flatMap4(HttpClient,(httpClient)=>makeWith3(api,{...options4,httpClient:options4?.transformClient?options4.transformClient(httpClient):httpClient}));var makeWith3=(api,options4)=>{const client={};return makeClient(api,{...options4,onGroup({group}){if(group.topLevel)return;set(client,group.identifier,{})},onEndpoint({endpoint,endpointFn,group}){set(group.topLevel?client:client[group.identifier],endpoint.identifier,endpointFn)}}).pipe(as2(client))};var group=(api,options4)=>{const client={};return makeClient(api,{...options4,predicate:({group:group2})=>group2.identifier===options4.group,onEndpoint({endpoint,endpointFn}){set(client,endpoint.identifier,endpointFn)}}).pipe(map7(()=>client))};var endpoint=(api,options4)=>{let client=undefined;return makeClient(api,{...options4,httpClient:options4.transformClient?options4.transformClient(options4.httpClient):options4.httpClient,predicate:({endpoint:endpoint2,group:group2})=>group2.identifier===options4.group&&endpoint2.identifier===options4.endpoint,onEndpoint({endpointFn}){client=endpointFn}}).pipe(map7(()=>client))};var urlBuilder=(api,options4)=>{const builder={};reflect(api,{onGroup({group:group2}){if(group2.topLevel)return;set(builder,group2.identifier,{})},onEndpoint({group:group2,endpoint:endpoint2}){const makeUrl=compilePath(endpoint2.path);const encodeParams=endpoint2.params===undefined?undefined:encodeSync2(endpoint2.params);const encodeQuery=endpoint2.query===undefined?undefined:encodeSync2(endpoint2.query);const endpointBuilder=(request3)=>{const params=request3?.params;const path4=params===undefined?endpoint2.path:makeUrl(encodeParams===undefined?params:encodeParams(params));const queryInput=request3?.query===undefined?undefined:encodeQuery===undefined?request3.query:encodeQuery(request3.query);const query=queryInput===undefined?"":toString(fromInput3(queryInput));const url2=query===""?path4:`${path4}?${query}`;return options4?.baseUrl===undefined?url2:new URL(url2,options4.baseUrl.toString()).toString()};set(group2.topLevel?builder:builder[group2.identifier],endpoint2.identifier,endpointBuilder)}});return builder};var paramsRegExp=/(\/?):(\w+)(\?)?/g;var compilePath=(path4)=>{if(!paramsRegExp.test(path4)){return(_)=>path4}paramsRegExp.lastIndex=0;return(params)=>{paramsRegExp.lastIndex=0;return path4.replace(paramsRegExp,(_,slash,key,optional4)=>{const value5=params[key];if(value5===undefined){if(optional4!==undefined){return""}throw new Error(`Missing path parameter: ${key}`)}return`${slash}${encodeURIComponent(value5)}`})}};function schemasToResponse(schemas){const codec=toCodecArrayBuffer(schemas);const decode4=decodeEffect2(codec);return(response)=>flatMap4(response.arrayBuffer,decode4)}function addResponseAlternative(map18,status2,contentType,decode4){const normalizedContentType=normalize2(contentType);const alternatives=map18.get(status2);if(alternatives===undefined){map18.set(status2,[{contentType:normalizedContentType,decode:decode4}])}else{alternatives.push({contentType:normalizedContentType,decode:decode4})}}function makeResponseDecoder(alternatives){const first=alternatives[0];if(alternatives.length===1&&first!==undefined){return first.decode}return(response)=>{const contentType=normalize2(response.headers["content-type"]??"");const alternative=alternatives.find((alternative2)=>alternative2.contentType===contentType);return alternative===undefined?failUnsupportedContentType(response,contentType,alternatives):alternative.decode(response)}}function groupSchemasByContentType(schemas){const grouped=new Map;for(const schema2 of schemas){const contentType=isNoContent(schema2.ast)?"":normalize2(getResponseEncoding(schema2.ast).contentType);const existing=grouped.get(contentType);if(existing===undefined){grouped.set(contentType,[schema2])}else{existing.push(schema2)}}return grouped}function failUnsupportedContentType(response,contentType,alternatives){const expected=Array.from(new Set(alternatives.map((alternative)=>alternative.contentType))).join(", ");return fail6(new HttpClientError({reason:new DecodeError({request:response.request,response,description:`Unsupported response content-type for status ${response.status}: ${contentType||"<missing>"}. Expected one of: ${expected}`})}))}var reservedStreamFailureEvent3="effect/httpapi/stream/failure";function getStreamSuccessSchemas(endpoint2){const schemas=[];for(const schema2 of endpoint2.success){if(isStreamSchema(schema2)){schemas.push(schema2)}}return schemas}function streamToResponse(streamSchema2){const sse=isStreamUint8Array(streamSchema2)?undefined:{declaration:streamSchema2,decoder:makeSseDecoder(streamSchema2)};return(response)=>map7(context2(),(context4)=>provideContext4(sse===undefined?response.stream:decodeSseStream(response.stream,sse.declaration,sse.decoder),context4))}function makeSseDecoder(declaration){const Event=Union2([Struct({event:Literal2(reservedStreamFailureEvent3),data:fromJsonString2(toCodecJson(Cause(declaration.error,Defect())))}),declaration.events]);return decodeSchema(Event)}function decodeSseStream(stream3,declaration,decoder2){const events=transformPull2(stream3.pipe(decodeText,pipeThroughChannel(decoder2)),(pull)=>sync2(()=>{let pendingFailureCause=undefined;return suspend2(()=>{if(pendingFailureCause!==undefined){return failCause3(pendingFailureCause)}return flatMap4(pull,(events2)=>{for(let i=0;i<events2.length;i++){const event=events2[i];if(event.event===reservedStreamFailureEvent3&&isCause2(event.data)){if(i===0){return failCause3(event.data)}pendingFailureCause=event.data;events2=events2.slice(0,i);break}}return succeed6(events2)})})}));if(declaration.sseMode==="data"){return map9(events,(event)=>event.data)}return events}var ArrayBuffer2=instanceOf(globalThis.ArrayBuffer,{expected:"ArrayBuffer"});var Uint8ArrayFromArrayBuffer=ArrayBuffer2.pipe(decodeTo2(Uint8Array2,transform2({decode(fromA){return new Uint8Array(fromA)},encode(arr){return arr.byteLength===arr.buffer.byteLength?arr.buffer:arr.buffer.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)}})));var StringFromArrayBuffer=ArrayBuffer2.pipe(decodeTo2(String5,transform2({decode(fromA){return new TextDecoder().decode(fromA)},encode(toI){const arr=new TextEncoder().encode(toI);return arr.byteLength===arr.buffer.byteLength?arr.buffer:arr.buffer.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)}})));var UnknownFromArrayBuffer=StringFromArrayBuffer.pipe(decodeTo2(Union2([Literal2("").pipe(decodeTo2(Undefined2,transform2({decode:()=>{return},encode:()=>""}))),UnknownFromJsonString])));function toCodecArrayBuffer(schemas){return Union2(schemas.map(onSchema));function onSchema(schema2){const encoding=getResponseEncoding(schema2.ast);switch(encoding._tag){case"Json":{const encodedIsNull=isNull(toEncoded(schema2.ast));return UnknownFromArrayBuffer.pipe(decodeTo2(schema2,encodedIsNull?transform2({decode:(a)=>a===undefined?null:a,encode:(a)=>a===null?undefined:a}):undefined))}case"FormUrlEncoded":return StringFromArrayBuffer.pipe(decodeTo2(schemaRecord),decodeTo2(schema2));case"Uint8Array":return Uint8ArrayFromArrayBuffer.pipe(decodeTo2(schema2));case"Text":return StringFromArrayBuffer.pipe(decodeTo2(schema2))}}}var statusOrElse=(response)=>fail6(new HttpClientError({reason:new DecodeError({request:response.request,response})}));var $HttpBody=declare(isHttpBody);function getEncodePayloadSchema(schemas,method){return Union2(schemas.map((s)=>getEncodePayloadSchemaFromBody(s,method)))}var bodyFromPayloadCache=new WeakMap;function getEncodePayloadSchemaFromBody(schema2,method){const ast=schema2.ast;const cached3=bodyFromPayloadCache.get(ast);if(cached3!==undefined){return cached3}const encoding=getPayloadEncoding(ast,method);const out=$HttpBody.pipe(decodeTo2(schema2,transformOrFail2({decode(httpBody){return fail6(new Forbidden(some2(httpBody),{message:"Encode only schema"}))},encode(t){switch(encoding._tag){case"Multipart":return fail6(new Forbidden(some2(t),{message:"Payload must be a FormData"}));case"Json":{try{const body=JSON.stringify(t);return succeed6(text2(body,encoding.contentType))}catch(error2){return fail6(new InvalidValue(some2(t),{message:globalThis.String(error2)}))}}case"Text":{if(typeof t!=="string"){return fail6(new InvalidValue(some2(t),{message:"Expected a string"}))}return succeed6(text2(t,encoding.contentType))}case"FormUrlEncoded":{if(!isObject(t)){return fail6(new InvalidValue(some2(t),{message:"Expected a record"}))}return succeed6(urlParams(fromInput3(t),encoding.contentType))}case"Uint8Array":{if(!(t instanceof Uint8Array)){return fail6(new InvalidValue(some2(t),{message:"Expected a Uint8Array"}))}return succeed6(uint8Array2(t,encoding.contentType))}}}})));bodyFromPayloadCache.set(ast,out);return out}var exports_HttpApiGroup={};__export(exports_HttpApiGroup,{make:()=>make47,isHttpApiGroup:()=>isHttpApiGroup});var TypeId56="~effect/httpapi/HttpApiGroup";var isHttpApiGroup=(u)=>hasProperty(u,TypeId56);var Proto19={[TypeId56]:TypeId56,add(...toAdd){const endpoints={...this.endpoints};for(const endpoint2 of toAdd){set(endpoints,endpoint2.identifier,endpoint2)}return makeProto4({...optionsFromGroup(this),endpoints})},prefix(prefix){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.prefix(prefix))})},middleware(middleware2){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.middleware(middleware2))})},annotateMerge(annotations2){return makeProto4({...optionsFromGroup(this),annotations:merge(this.annotations,annotations2)})},annotate(annotation,value5){return makeProto4({...optionsFromGroup(this),annotations:add(this.annotations,annotation,value5)})},annotateEndpointsMerge(annotations2){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.annotateMerge(annotations2))})},annotateEndpoints(annotation,value5){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.annotate(annotation,value5))})},pipe(){return pipeArguments(this,arguments)}};var optionsFromGroup=(group2)=>({identifier:group2.identifier,topLevel:group2.topLevel,endpoints:group2.endpoints,annotations:group2.annotations});var makeProto4=(options4)=>{function HttpApiGroup(){}Object.setPrototypeOf(HttpApiGroup,Proto19);HttpApiGroup.key=`effect/httpapi/HttpApiGroup/${options4.identifier}`;return Object.assign(HttpApiGroup,options4)};var make47=(identifier2,options4)=>makeProto4({identifier:identifier2,topLevel:options4?.topLevel??false,endpoints:{},annotations:empty()});var defaultMessage=(message)=>String5.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var BaselineChannel=Literals(["stable","bundled"]);var HarnessReportStatus=Literals(["new","triaged","accepted","wontfix","resolved"]);var OperatorIdentity=Struct({operatorId:String5,email:optionalKey2(String5),emailVerified:optionalKey2(Boolean4)}).annotate({identifier:"OperatorIdentity"});var isoDateTimePattern=/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})(?:\.(?<fraction>\d{1,9}))?(?:Z|[+-]\d{2}:\d{2})$/u;var isValidIsoDateTime=(value5)=>{const groups=isoDateTimePattern.exec(value5)?.groups;if(groups===undefined){return false}const year=Number(groups.year);const month=Number(groups.month);const day=Number(groups.day);const hour=Number(groups.hour);const minute=Number(groups.minute);const second=Number(groups.second);const millisecond=Number((groups.fraction??"").slice(0,3).padEnd(3,"0"));const date7=new Date(Date.UTC(year,month-1,day,hour,minute,second,millisecond));return Number.isFinite(Date.parse(value5))&&date7.getUTCFullYear()===year&&date7.getUTCMonth()===month-1&&date7.getUTCDate()===day&&date7.getUTCHours()===hour&&date7.getUTCMinutes()===minute&&date7.getUTCSeconds()===second};var IsoDateTimeString=String5.pipe(refine((value5)=>isValidIsoDateTime(value5),{identifier:"IsoDateTimeString",description:"an ISO 8601 datetime string with timezone"}));var GitIdentity=Struct({name:optionalKey2(String5),email:optionalKey2(String5)}).annotate({identifier:"GitIdentity"});var ObservedRepositoryInput=Struct({remoteUrl:optionalKey2(String5),remoteHost:optionalKey2(String5),remotePath:optionalKey2(String5),branch:optionalKey2(String5),commitSha:optionalKey2(String5),dirty:optionalKey2(Boolean4),gitIdentity:optionalKey2(GitIdentity)}).annotate({identifier:"ObservedRepositoryInput"});var SymbolPropertyKey=Struct({_tag:Literal2("symbol"),key:String5}).annotate({description:"an object to be decoded into a globally shared symbol"});var PropertyKey2=Union2([String5,Finite,SymbolPropertyKey]).annotate({identifier:"PropertyKey"});var DecodeIssue=Struct({_tag:Literals(["Pointer","Unexpected","Missing","Composite","Refinement","Transformation","Type","Forbidden"]),path:ArraySchema(PropertyKey2),message:String5}).annotate({identifier:"Issue"});class HttpApiDecodeError extends TaggedErrorClass()("HttpApiDecodeError",{issues:ArraySchema(DecodeIssue),message:String5},{httpApiStatus:400,description:"The request did not match the expected schema"}){}class Forbidden2 extends TaggedErrorClass()("@punks/contract/errors/Forbidden",{message:defaultMessage("The supplied credentials cannot access this resource.")},{httpApiStatus:403,title:"Forbidden"}){}var defaultMessage2=(message)=>String5.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var ArtifactKind=Literals(["manifest","archive"]);var BaselineVersion=NonEmptyString.annotate({identifier:"BaselineVersion"});var NonBlankString=String5.check(isTrimmed(),isNonEmpty());var BaselineRevision=String5.check(isPattern2(/^[1-9][0-9]*$/u)).annotate({identifier:"BaselineRevision"});var BaselineSha256=String5.check(isPattern2(/^[0-9a-f]{64}$/u)).annotate({identifier:"BaselineSha256"});var BaselinePromotionArtifact=Struct({url:NonBlankString,sha256:BaselineSha256}).annotate({identifier:"BaselinePromotionArtifact"});var BaselinePromotionCandidate=Struct({releaseId:NonBlankString,version:BaselineVersion,tag:NonBlankString,publishedAt:IsoDateTimeString,commitSha:NonBlankString,provenance:NonBlankString,cliVersionRange:NonBlankString,manifest:BaselinePromotionArtifact,archive:BaselinePromotionArtifact}).annotate({identifier:"BaselinePromotionCandidate"});var BaselinePublishRequest=Struct({mode:Literal2("publish"),candidate:BaselinePromotionCandidate,publicationIdentity:NonBlankString,expectedRevision:optionalKey2(BaselineRevision),reason:optionalKey2(Never2)});var BaselineRollbackRequest=Struct({mode:Literal2("rollback"),candidate:BaselinePromotionCandidate,publicationIdentity:NonBlankString,expectedRevision:BaselineRevision,reason:NonBlankString});var BaselinePromotionRequest=Union2([BaselinePublishRequest,BaselineRollbackRequest]).annotate({identifier:"BaselinePromotionRequest"});var BaselinePromotionResult=Struct({outcome:Literals(["committed","already-committed"]),revision:BaselineRevision,mode:Literals(["publish","rollback"]),candidate:BaselinePromotionCandidate,publicationIdentity:NonBlankString,previousRevision:optionalKey2(BaselineRevision),previousReleaseId:optionalKey2(NonBlankString),committedAt:IsoDateTimeString}).annotate({identifier:"BaselinePromotionResult"});var BaselineRequest=Struct({channel:BaselineChannel,version:optionalKey2(BaselineVersion)}).annotate({identifier:"BaselineRequest"});var BaselineVersionRequest=Struct({version:optionalKey2(BaselineVersion)}).annotate({identifier:"BaselineVersionRequest"});var BaselineSource=Literals(["control-plane","published-release","cache","bundled"]);var BaselineCompatibility=Struct({cliVersionRange:String5}).annotate({identifier:"BaselineCompatibility"});var BaselineRetrievalStatus=Literals(["available","retrieved","cached","fallback"]);var ArtifactMetadata=Struct({kind:ArtifactKind,fileName:String5,contentType:String5,url:String5,sha256:String5,sizeBytes:optionalKey2(Finite)}).annotate({identifier:"ArtifactMetadata"});var BaselineIdentity={requested:BaselineRequest,resolvedVersion:BaselineVersion,digest:String5,source:BaselineSource,provenance:String5,compatibility:BaselineCompatibility,retrieval:BaselineRetrievalStatus};var BaselineResolution=Struct({...BaselineIdentity,manifest:ArtifactMetadata,archive:ArtifactMetadata}).pipe(check2(makeFilter2(({requested,resolvedVersion})=>requested.version===undefined||requested.version===resolvedVersion,{message:"An exact baseline request must resolve to the requested version."})),check2(makeFilter2(({digest:digest2,archive})=>digest2===archive.sha256,{message:"The baseline digest must match the archive digest."}))).annotate({identifier:"BaselineResolution"});var BaselineArtifact=Struct({...BaselineIdentity,artifact:ArtifactMetadata}).pipe(check2(makeFilter2(({requested,resolvedVersion})=>requested.version===undefined||requested.version===resolvedVersion,{message:"Artifact metadata must match the exact requested baseline version."})),check2(makeFilter2(({artifact,digest:digest2})=>artifact.kind!=="archive"||artifact.sha256===digest2,{message:"The baseline artifact digest must match the verified baseline digest."}))).annotate({identifier:"BaselineArtifact"});class BaselineNotFound extends TaggedErrorClass()("@punks/contract/errors/BaselineNotFound",{channel:String5,message:defaultMessage2("No baseline exists for the requested channel.")},{httpApiStatus:404,title:"Baseline Not Found"}){}class ControlPlaneUnavailable extends TaggedErrorClass()("@punks/contract/errors/ControlPlaneUnavailable",{message:defaultMessage2("The control plane cannot resolve this resource yet.")},{httpApiStatus:503,title:"Control Plane Unavailable"}){}class BaselineAuthorityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselineAuthorityFailure",{request:BaselineRequest,resolvedVersion:optionalKey2(BaselineVersion),message:String5},{httpApiStatus:409,title:"Baseline Authority Failure"}){}class BaselineIntegrityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselineIntegrityFailure",{request:BaselineRequest,resolvedVersion:optionalKey2(BaselineVersion),expectedDigest:optionalKey2(String5),actualDigest:optionalKey2(String5),message:defaultMessage2("Baseline identity or artifact integrity verification failed.")},{httpApiStatus:422,title:"Baseline Integrity Failure"}){}var BaselineAvailability=Literals(["authority-unconfigured","network","unavailable-status"]);class BaselineUnavailable extends TaggedErrorClass()("@punks/contract/errors/BaselineUnavailable",{availability:BaselineAvailability,request:BaselineRequest,message:defaultMessage2("The requested baseline is unavailable.")},{httpApiStatus:503,title:"Baseline Unavailable"}){}class BaselinePublisherUnauthorized extends TaggedErrorClass()("@punks/contract/errors/BaselinePublisherUnauthorized",{message:defaultMessage2("Baseline publisher authentication is required.")},{httpApiStatus:401,title:"Baseline Publisher Unauthorized"}){}class BaselinePromotionConflict extends TaggedErrorClass()("@punks/contract/errors/BaselinePromotionConflict",{publicationIdentity:NonBlankString,expectedRevision:optionalKey2(BaselineRevision),actualRevision:optionalKey2(BaselineRevision),message:String5},{httpApiStatus:409,title:"Baseline Promotion Conflict"}){}class BaselinePromotionIntegrityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselinePromotionIntegrityFailure",{publicationIdentity:NonBlankString,releaseId:optionalKey2(NonBlankString),expectedDigest:optionalKey2(BaselineSha256),actualDigest:optionalKey2(BaselineSha256),message:defaultMessage2("Baseline promotion evidence failed integrity verification.")},{httpApiStatus:422,title:"Baseline Promotion Integrity Failure"}){}class BaselinePromotionUnavailable extends TaggedErrorClass()("@punks/contract/errors/BaselinePromotionUnavailable",{publicationIdentity:NonBlankString,outcome:Literals(["not-committed","indeterminate"]),message:defaultMessage2("Baseline promotion is unavailable.")},{httpApiStatus:503,title:"Baseline Promotion Unavailable"}){}var errors2=[HttpApiDecodeError,Forbidden2,BaselineNotFound,BaselineAuthorityFailure,BaselineIntegrityFailure,BaselineUnavailable];var promotionErrors=[HttpApiDecodeError,Forbidden2,BaselinePublisherUnauthorized,BaselinePromotionConflict,BaselinePromotionIntegrityFailure,BaselinePromotionUnavailable];var BaselineApi=exports_HttpApiGroup.make("baseline").add(exports_HttpApiEndpoint.get("resolve","/:channel",{params:{channel:BaselineChannel},query:BaselineVersionRequest,success:BaselineResolution,error:errors2}),exports_HttpApiEndpoint.get("artifact","/:channel/artifacts/:kind",{params:{channel:BaselineChannel,kind:ArtifactKind},query:BaselineVersionRequest,success:BaselineArtifact,error:errors2}),exports_HttpApiEndpoint.post("promote","/stable/promotions",{payload:BaselinePromotionRequest,success:BaselinePromotionResult,error:promotionErrors})).prefix("/baselines").annotateMerge(exports_OpenApi.annotations({title:"Baseline control plane"}));import{createHash as createHash2}from"node:crypto";import{lstatSync,readFileSync,readdirSync,readlinkSync}from"node:fs";import path4 from"node:path";var digestContentRoots=(roots)=>{const entries3=[];for(const{root,prefix,include=()=>true,logicalPath=(value5)=>value5}of roots){const visit2=(directory3)=>{for(const entry of readdirSync(directory3,{withFileTypes:true})){const absolutePath=path4.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}const relativePath=path4.relative(root,absolutePath).split(path4.sep).join("/");if(include(relativePath)){entries3.push({absolutePath,identity:`${prefix}/${logicalPath(relativePath)}`})}}};visit2(root)}const hash3=createHash2("sha256");for(const{absolutePath,identity:identity3}of entries3.toSorted((left,right)=>left.identity.localeCompare(right.identity))){const stat3=lstatSync(absolutePath);hash3.update(identity3);hash3.update("\x00");if(stat3.isSymbolicLink()){hash3.update("symlink\x00");hash3.update(readlinkSync(absolutePath))}else{hash3.update("file\x00");hash3.update(readFileSync(absolutePath))}hash3.update("\x00")}return hash3.digest("hex")};import{existsSync,mkdirSync,readFileSync as readFileSync2,statSync,writeFileSync}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import path5 from"node:path";var embeddedAssets=[];var name="@punks/cli";var version2="3.1.1-beta.0";var findFirst6=(candidates)=>candidates.find((candidate)=>existsSync(candidate));var executableSignature=()=>{try{return String(Math.trunc(statSync(process.execPath).mtimeMs))}catch{return"unknown"}};var extractEmbeddedAssets=()=>{if(embeddedAssets.length===0){return}const root=path5.join(tmpdir2(),"punks-cli-assets",`${version2}-${executableSignature()}`);for(const asset of embeddedAssets){const targetPath=path5.join(root,asset.relativePath);if(existsSync(targetPath)){continue}mkdirSync(path5.dirname(targetPath),{recursive:true});writeFileSync(targetPath,readFileSync2(asset.path))}return root};var findBundledPackageRoot=()=>{let currentDirectory=path5.resolve(import.meta.dirname,"../..");while(true){if(existsSync(path5.join(currentDirectory,"package.json"))){return currentDirectory}const parentDirectory=path5.dirname(currentDirectory);if(parentDirectory===currentDirectory){break}currentDirectory=parentDirectory}return path5.resolve(import.meta.dirname,"../..")};var packageRoot=findBundledPackageRoot();var runtimeRoot=import.meta.dirname;var embeddedAssetsRoot=extractEmbeddedAssets();var executableRoots=[process.argv[1],process.execPath].filter((candidate)=>candidate!==undefined&&candidate.length>0).map((candidate)=>path5.dirname(path5.resolve(candidate)));var dataCandidates=[path5.join(runtimeRoot,"data"),...embeddedAssetsRoot===undefined?[]:[path5.join(embeddedAssetsRoot,"data")],...executableRoots.map((root)=>path5.join(root,"data")),path5.resolve(import.meta.dirname,"../data"),path5.join(packageRoot,"src/data"),path5.resolve(import.meta.dirname,"../../src/data")];var skillCandidates=[path5.join(runtimeRoot,"skills"),...embeddedAssetsRoot===undefined?[]:[path5.join(embeddedAssetsRoot,"skills")],...executableRoots.map((root)=>path5.join(root,"skills")),path5.join(packageRoot,"skills"),path5.resolve(import.meta.dirname,"../../skills"),path5.resolve(import.meta.dirname,"../skills")];var resolvedDataRoot=findFirst6(dataCandidates);var resolvedSkillsRoot=findFirst6(skillCandidates);if(resolvedDataRoot===undefined){throw new Error("Could not locate bundled data directory.")}if(resolvedSkillsRoot===undefined){throw new Error("Could not locate bundled skills directory.")}var dataRoot=resolvedDataRoot;var skillsRoot=resolvedSkillsRoot;var dataPath=(...segments)=>path5.join(dataRoot,...segments);var readDataFile=(...segments)=>readFileSync2(dataPath(...segments),"utf-8");var readBaselineDataFile=(baselineDataRoot,...segments)=>readFileSync2(path5.join(baselineDataRoot,...segments),"utf-8");var resolveBaselinePath=({baselineRoot,baselineSkillsRoot,relativePath})=>{const resolvedPath=relativePath.startsWith("skills/")?findFirst6([path5.join(baselineSkillsRoot,relativePath.slice("skills/".length)),path5.join(baselineRoot,relativePath)]):findFirst6([path5.join(baselineRoot,relativePath)]);if(resolvedPath!==undefined){return resolvedPath}throw new Error(`Could not locate baseline asset: ${relativePath}`)};var bundledBaselineDigest="09c98193f19bd32231fc47644f7ee0bb16aa8e9486d68bc6e9b1b56199cbe3be";var hookCatalog=[{description:"Shared session-start hook that reports whether managed Harness scaffold output is current.",harness:"shared",id:"scaffold-update-check",outputPath:".agents/hooks/scaffold-update-check.mjs",sourcePath:"hooks/scaffold-update-check.mjs"},{description:"Shared hook that auto-formats edited JS/TS/JSON files and lint-checks product files after tool use.",harness:"shared",id:"format-edited-file",outputPath:".agents/hooks/format-edited-file.mjs",sourcePath:"hooks/format-edited-file.mjs"}];var sharedReactPlacement={placementNotes:"Add as an override for detected React-rendered code. Keep backend packages outside this override unless they render React.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-react-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected React workspaces"]};var webOnlyPlacement={placementNotes:"Place this in the Next.js app override. If the repo uses a different frontend app path, retarget the file globs to that workspace before composing the final Oxlint config.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-nextjs-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Next.js workspaces"]};var effectPlacement={placementNotes:"Apply this only where Effect code lives. If the target repo renames or splits backend workspaces, move the override with those code paths instead of broadening it repo-wide.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-effect-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Effect workspaces"]};var vitestPlacement={placementNotes:"Attach this to test-only globs. Expand or narrow the file patterns to match the repo's actual Vitest test layout instead of treating it as a global default.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-test-workspace>/**/*.{test,spec}.{js,jsx,ts,tsx}","<detected-test-workspace>/src/test/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected JavaScript/TypeScript test workspaces"]};var lintCatalog=[{description:"Ultracite React preset for rendered app and shared UI code.",id:"react-core",jsPlugins:[],oxlintPresets:["react"],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"React Hooks lint rules via the JS plugin bridge for Oxlint.",id:"react-hooks",jsPlugins:[{name:"react-hooks-js",specifier:"eslint-plugin-react-hooks"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-hooks"],rules:Object.fromEntries([["react-hooks-js/exhaustive-deps","error"],["react-hooks-js/component-hook-factories","error"],["react-hooks-js/config","error"],["react-hooks-js/error-boundaries","error"],["react-hooks-js/gating","error"],["react-hooks-js/globals","error"],["react-hooks-js/immutability","error"],["react-hooks-js/incompatible-library","error"],["react-hooks-js/preserve-manual-memoization","error"],["react-hooks-js/purity","error"],["react-hooks-js/refs","error"],["react-hooks-js/rules-of-hooks","error"],["react-hooks-js/set-state-in-effect","error"],["react-hooks-js/set-state-in-render","error"],["react-hooks-js/static-components","error"],["react-hooks-js/unsupported-syntax","error"],["react-hooks-js/use-memo","error"]]),settings:{}},{description:"Guidance rules that push React code away from unnecessary effects.",id:"react-you-might-not-need-an-effect",jsPlugins:[{name:"react-you-might-not-need-an-effect-js",specifier:"eslint-plugin-react-you-might-not-need-an-effect"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-you-might-not-need-an-effect"],rules:{"react-you-might-not-need-an-effect-js/no-adjust-state-on-prop-change":"error","react-you-might-not-need-an-effect-js/no-chain-state-updates":"error","react-you-might-not-need-an-effect-js/no-derived-state":"error","react-you-might-not-need-an-effect-js/no-event-handler":"error","react-you-might-not-need-an-effect-js/no-initialize-state":"error","react-you-might-not-need-an-effect-js/no-pass-data-to-parent":"error","react-you-might-not-need-an-effect-js/no-pass-live-state-to-parent":"error","react-you-might-not-need-an-effect-js/no-reset-all-state-on-prop-change":"error"},settings:{}},{description:"Ultracite Next.js preset for the main web application.",id:"next-core",jsPlugins:[],oxlintPresets:["next"],placement:{...webOnlyPlacement,placementNotes:"Place this beside the React app override and set `settings.next.rootDir` to the repo's actual Next workspace roots if the final config needs that plugin setting."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Ultracite TanStack preset for query/router/start framework linting.",id:"tanstack-query-core",jsPlugins:[],oxlintPresets:["tanstack"],placement:{...webOnlyPlacement,placementNotes:"Scope this to client code that owns TanStack Query usage. Keep it out of server-only or shared non-query packages unless those paths actually create queries or mutations."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Effect architectural rule that blocks barrel-package imports.",id:"effect-no-barrel-imports",jsPlugins:[{name:"effect-js",specifier:"@effect/eslint-plugin"}],oxlintPresets:[],placement:effectPlacement,plugins:[],requiredDevDependencies:["@effect/eslint-plugin"],rules:{"effect-js/no-import-from-barrel-package":["error",{packageNames:["effect"]}]},settings:{}},{description:"Ultracite Vitest preset for repo-owned test globs.",id:"vitest-core",jsPlugins:[],oxlintPresets:["vitest"],placement:vitestPlacement,plugins:[],requiredDevDependencies:[],rules:{},settings:{}}];var stableJson=(value5)=>JSON.stringify(value5);var placementKeyOf=(placement)=>[placement.recommendedConfigFile,...placement.recommendedFiles].join("::");var validateLintCatalog=(catalog)=>{const seenIds=new Set;const seenRules=new Map;const seenSettings=new Map;const seenJsPlugins=new Map;for(const asset of catalog){if(seenIds.has(asset.id)){throw new Error(`Duplicate lint asset id: ${asset.id}`)}seenIds.add(asset.id);const placementKey=placementKeyOf(asset.placement);for(const[ruleName,ruleValue]of Object.entries(asset.rules)){const key=`${placementKey}::rule::${ruleName}`;const value5=stableJson(ruleValue);const previous=seenRules.get(key);if(previous!==undefined&&previous.value!==value5){throw new Error(`Conflicting lint rule \`${ruleName}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenRules.set(key,{assetId:asset.id,value:value5})}}for(const[settingName,settingValue]of Object.entries(asset.settings)){const key=`${placementKey}::setting::${settingName}`;const value5=stableJson(settingValue);const previous=seenSettings.get(key);if(previous!==undefined&&previous.value!==value5){throw new Error(`Conflicting lint setting \`${settingName}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenSettings.set(key,{assetId:asset.id,value:value5})}}for(const plugin of asset.jsPlugins){const key=`${placementKey}::js-plugin::${plugin.name}`;const previous=seenJsPlugins.get(key);if(previous!==undefined&&previous.specifier!==plugin.specifier){throw new Error(`Conflicting JS plugin alias \`${plugin.name}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenJsPlugins.set(key,{assetId:asset.id,specifier:plugin.specifier})}}}return catalog};var skillCatalog=[{framework:"browser-automation",id:"agent-browser",language:null,requiresTools:["agent-browser"],sourceDirectory:"skills/agnostic/frontend/agent-browser",tier:"framework"},{framework:null,id:"backend-domain-structure",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/backend-domain-structure",tier:"agnostic"},{framework:null,id:"backend-recoverable-actions",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/backend-recoverable-actions",tier:"agnostic"},{framework:null,id:"logging-best-practices",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/logging-best-practices",tier:"agnostic"},{framework:null,id:"audit-cicd-security",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/security/audit-cicd-security",tier:"agnostic"},{framework:null,id:"security-best-practices",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/security/security-best-practices",tier:"agnostic"},{framework:"better-auth",id:"better-auth-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/better-auth/better-auth-best-practices",tier:"framework"},{framework:"better-auth",id:"better-auth-security-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/better-auth/better-auth-security-best-practices",tier:"framework"},{framework:null,id:"create-plan",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/create-plan",tier:"agnostic"},{framework:null,id:"create-spec",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/create-spec",tier:"agnostic"},{framework:null,id:"delivery-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/delivery-phase",tier:"agnostic"},{framework:null,id:"design-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/design-phase",tier:"agnostic"},{framework:null,id:"debug-agent",language:null,requiresTools:["debug-agent"],sourceDirectory:"skills/agnostic/debug/debug-agent",tier:"agnostic"},{framework:null,id:"debugging-phase",language:null,requiresTools:["debug-agent"],sourceDirectory:"skills/phases/debugging-phase",tier:"agnostic"},{framework:null,id:"bug-discovery-phase",language:null,requiresTools:["clawpatch"],sourceDirectory:"skills/phases/bug-discovery-phase",tier:"agnostic"},{framework:null,id:"bug-resolution-phase",language:null,requiresTools:["clawpatch"],sourceDirectory:"skills/phases/bug-resolution-phase",tier:"agnostic"},{framework:null,id:"docs-ingest-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/docs-ingest-phase",tier:"agnostic"},{framework:null,id:"docs-onboarding",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/docs-onboarding",tier:"agnostic"},{framework:null,id:"writing-fragments",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-fragments",tier:"agnostic"},{framework:null,id:"writing-beats",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-beats",tier:"agnostic"},{framework:null,id:"writing-shape",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-shape",tier:"agnostic"},{framework:"effect",id:"effect-backend-structure",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/effect/effect-backend-structure",tier:"framework"},{framework:"effect",id:"effect",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/effect/effect",tier:"framework"},{framework:"effect",id:"effect-recoverable-actions",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/effect/effect-recoverable-actions",tier:"framework"},{framework:"elysiajs",id:"elysiajs",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/elysia/elysiajs",tier:"framework"},{framework:"expo",id:"add-app-clip",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/add-app-clip",tier:"framework"},{framework:"expo",id:"building-native-ui",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/building-native-ui",tier:"framework"},{framework:"expo",id:"eas-simulator",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/eas-simulator",tier:"framework"},{framework:"expo",id:"eas-update-insights",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/eas-update-insights",tier:"framework"},{framework:"expo",id:"expo-api-routes",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-api-routes",tier:"framework"},{framework:"expo",id:"expo-brownfield",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-brownfield",tier:"framework"},{framework:"expo",id:"expo-cicd-workflows",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-cicd-workflows",tier:"framework"},{framework:"expo",id:"expo-deployment",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-deployment",tier:"framework"},{framework:"expo",id:"expo-dev-client",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-dev-client",tier:"framework"},{framework:"expo",id:"expo-examples",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-examples",tier:"framework"},{framework:"expo",id:"expo-module",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-module",tier:"framework"},{framework:"expo",id:"expo-observe",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-observe",tier:"framework"},{framework:"expo",id:"expo-skill-eval",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-skill-eval",tier:"framework"},{framework:"expo",id:"expo-tailwind-setup",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-tailwind-setup",tier:"framework"},{framework:"expo",id:"expo-ui",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-ui",tier:"framework"},{framework:"expo",id:"native-data-fetching",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/native-data-fetching",tier:"framework"},{framework:"expo",id:"upgrading-expo",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/upgrading-expo",tier:"framework"},{framework:"expo",id:"use-dom",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/use-dom",tier:"framework"},{framework:"expo",id:"web-to-native",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/web-to-native",tier:"framework"},{framework:"pulumi",id:"pulumi-overview",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-overview",tier:"framework"},{framework:"pulumi",id:"pulumi-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-best-practices",tier:"framework"},{framework:"pulumi",id:"pulumi-component",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-component",tier:"framework"},{framework:"pulumi",id:"pulumi-automation-api",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-automation-api",tier:"framework"},{framework:"pulumi",id:"pulumi-esc",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-esc",tier:"framework"},{framework:"pulumi",id:"provider-upgrade",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/provider-upgrade",tier:"framework"},{framework:"pulumi",id:"package-usage",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/package-usage",tier:"framework"},{framework:null,id:"design-taste-frontend",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/design-taste-frontend",tier:"agnostic"},{framework:null,id:"imagegen-frontend-mobile",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/imagegen-frontend-mobile",tier:"agnostic"},{framework:null,id:"imagegen-frontend-web",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/imagegen-frontend-web",tier:"agnostic"},{framework:null,id:"frontend-domain-structure",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/frontend-domain-structure",tier:"agnostic"},{framework:null,id:"finder-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/finder-phase",tier:"agnostic"},{framework:null,id:"goalify",language:null,requiresTools:[],sourceDirectory:"skills/phases/goalify",tier:"agnostic"},{framework:null,id:"grilling",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/grilling",tier:"agnostic"},{framework:null,id:"handoff",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/generic/handoff",tier:"agnostic"},{framework:null,id:"improve-codebase-architecture",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/improve-codebase-architecture",tier:"agnostic"},{framework:null,id:"implement-spec",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/implement-spec",tier:"agnostic"},{framework:null,id:"repo-asset-management",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/repo-asset-management",tier:"agnostic"},{framework:null,id:"stack",language:null,requiresTools:["stack"],sourceDirectory:"skills/agnostic/planning/stack",tier:"agnostic"},{framework:null,id:"wayfinder",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/wayfinder",tier:"agnostic"},{framework:"nextjs",id:"next-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/nextjs/next-best-practices",tier:"framework"},{framework:"nextjs",id:"next-cache-components",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/nextjs/next-cache-components",tier:"framework"},{framework:null,id:"parallel-research",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/parallel-research",tier:"agnostic"},{framework:null,id:"prototype",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/prototype",tier:"agnostic"},{framework:null,id:"async-python-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/async-python-patterns",tier:"language"},{framework:null,id:"python-code-style",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-code-style",tier:"language"},{framework:null,id:"python-design-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-design-patterns",tier:"language"},{framework:null,id:"python-project-structure",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-project-structure",tier:"language"},{framework:null,id:"python-testing-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-testing-patterns",tier:"language"},{framework:null,id:"quality-types",language:"typescript",requiresTools:[],sourceDirectory:"skills/languages/typescript/quality-types",tier:"language"},{framework:null,id:"codebase-design",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/codebase-design",tier:"agnostic"},{framework:"react",id:"async-react-patterns",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/async-react-patterns",tier:"framework"},{framework:"react",id:"react-doctor",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/react-doctor",tier:"framework"},{framework:null,id:"requirements-grill",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/requirements-grill",tier:"agnostic"},{framework:null,id:"requirements-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/requirements-phase",tier:"agnostic"},{framework:null,id:"resolve-debt-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/resolve-debt-phase",tier:"agnostic"},{framework:null,id:"review-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/review-phase",tier:"agnostic"},{framework:null,id:"review",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/review",tier:"agnostic"},{framework:null,id:"autoreview",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/autoreview",tier:"agnostic"},{framework:null,id:"simplify",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/simplify",tier:"agnostic"},{framework:null,id:"swarm-planner",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/subagents/swarm-planner",tier:"agnostic"},{framework:"tanstack-query",id:"tanstack-query",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/tanstack-query/tanstack-query",tier:"framework"},{framework:null,id:"tdd",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/tdd",tier:"agnostic"},{framework:null,id:"writing-great-skills",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-great-skills",tier:"agnostic"},{framework:"turborepo",id:"turborepo",language:null,requiresTools:[],sourceDirectory:"skills/frameworks/turborepo/turborepo",tier:"framework"},{framework:"react",id:"vercel-composition-patterns",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/vercel-composition-patterns",tier:"framework"},{framework:"react",id:"vercel-react-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/vercel-react-best-practices",tier:"framework"},{framework:null,id:"write-backlog",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/write-backlog",tier:"agnostic"}];var toolCatalog=[{ensureCommands:[["agent-browser","install"]],id:"agent-browser",latestInstallTarget:"agent-browser@latest",packageName:"agent-browser",requiredBins:["node"],skipEnsureCommandsIfAnyCommandExists:[{env:"AGENT_BROWSER_EXECUTABLE_PATH"},"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","google-chrome","google-chrome-stable","chromium","chromium-browser","brave-browser","brave-browser-stable","C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"]},{ensureCommands:[],id:"debug-agent",latestInstallTarget:"debug-agent@latest",packageName:"debug-agent",requiredBins:["node"]},{ensureCommands:[],id:"clawpatch",latestInstallTarget:"clawpatch@latest",packageName:"clawpatch",requiredBins:["node"]},{ensureCommands:[],id:"opensrc",latestInstallTarget:"opensrc@latest",minimumVersion:"0.7.2",packageName:"opensrc@^0.7.2",requiredBins:["node"],versionCommand:["opensrc","--version"]},{ensureCommands:[],id:"portless",latestInstallTarget:"portless@latest",packageName:"portless",requiredBins:["node"]},{ensureCommands:[],id:"skills",latestInstallTarget:"skills@latest",packageName:"skills",requiredBins:["node"]},{ensureCommands:[],id:"stack",latestInstallTarget:"@kitlangton/stack@latest",packageName:"@kitlangton/stack",requiredBins:["node"]}];var bundledNpmInstallAliasManifest=[{expectedSha256:"d1a3b15bb12948cfbd82acdd54889efc5d1263809550cb4d379863bbc1cc2f82",logicalRelativePath:"frameworks/nestjs/nestjs-best-practices/.gitignore",physicalRelativePath:"frameworks/nestjs/nestjs-best-practices/.npmignore"}];var fileSha256=(filePath)=>createHash3("sha256").update(readFileSync3(filePath)).digest("hex");var npmIgnoreFiles=(root)=>{const files=[];const visit2=(directory3)=>{for(const entry of readdirSync2(directory3,{withFileTypes:true})){const absolutePath=path6.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath)}else if(entry.isFile()&&entry.name===".npmignore"){files.push(path6.relative(root,absolutePath).split(path6.sep).join("/"))}}};visit2(root);return files};var resolveBundledSkillAliases=(root)=>{const aliases=new Map;const expectedPhysicalPaths=new Set(bundledNpmInstallAliasManifest.map(({physicalRelativePath})=>physicalRelativePath));for(const relativePath of npmIgnoreFiles(root)){if(!expectedPhysicalPaths.has(relativePath)){throw new Error(`Bundled baseline contains an unexpected npm alias: ${relativePath}`)}}for(const alias of bundledNpmInstallAliasManifest){const logicalPath=path6.join(root,alias.logicalRelativePath);const physicalPath=path6.join(root,alias.physicalRelativePath);const hasLogical=existsSync2(logicalPath);const hasPhysical=existsSync2(physicalPath);if(hasLogical&&hasPhysical){throw new Error(`Bundled baseline npm alias is ambiguous: ${alias.logicalRelativePath}`)}let resolvedPath=null;if(hasLogical){resolvedPath=logicalPath}else if(hasPhysical){resolvedPath=physicalPath}if(resolvedPath===null){throw new Error(`Bundled baseline asset is missing: ${alias.logicalRelativePath}`)}if(fileSha256(resolvedPath)!==alias.expectedSha256){throw new Error(`Bundled baseline npm alias hash mismatch: ${alias.logicalRelativePath}`)}if(hasPhysical){aliases.set(alias.physicalRelativePath,alias.logicalRelativePath)}}return aliases};var logicalBundledSkillRelativePath=(relativePath)=>bundledNpmInstallAliasManifest.find(({physicalRelativePath})=>physicalRelativePath===relativePath)?.logicalRelativePath??relativePath;var materializeBundledSkillDirectoryAliases=({sourceDirectory,sourceSkillsRoot,targetDirectory})=>{for(const alias of bundledNpmInstallAliasManifest){const sourcePhysicalPath=path6.join(sourceSkillsRoot,alias.physicalRelativePath);if(!existsSync2(sourcePhysicalPath)){continue}const relativePhysicalPath=path6.relative(sourceDirectory,sourcePhysicalPath);if(relativePhysicalPath===".."||relativePhysicalPath.startsWith(`..${path6.sep}`)){continue}const physicalPath=path6.join(targetDirectory,relativePhysicalPath);if(!existsSync2(physicalPath)){continue}const logicalPath=path6.join(targetDirectory,path6.relative(sourceDirectory,path6.join(sourceSkillsRoot,alias.logicalRelativePath)));if(existsSync2(logicalPath)){throw new Error(`Bundled baseline npm alias is ambiguous: ${alias.logicalRelativePath}`)}renameSync(physicalPath,logicalPath)}};var bundledBaseline={dataRoot,hooks:hookCatalog,lintAssets:validateLintCatalog(lintCatalog),packs:packCatalog,root:path6.dirname(dataRoot),skills:skillCatalog,skillsRoot,summary:{authoritySource:"bundled",channel:"bundled",commit:null,compatibility:{cliVersionRange:`=${version2}`},digest:bundledBaselineDigest,provenance:"packaged-cli",requested:{channel:"bundled"},resolvedVersion:version2,retrieval:"available",sha256:bundledBaselineDigest,source:"bundled",tag:null,version:version2},tools:toolCatalog};var resolveVerifiedBundledBaseline=(requested=bundledBaseline.summary.requested,retrieval="available")=>{const aliases=resolveBundledSkillAliases(skillsRoot);const actualDigest=digestContentRoots([{include:(relativePath)=>!relativePath.endsWith(".ts"),prefix:"data",root:dataRoot},{logicalPath:(relativePath)=>aliases.get(relativePath)??relativePath,prefix:"skills",root:skillsRoot}]);if(actualDigest!==bundledBaselineDigest){throw new BaselineIntegrityFailure({actualDigest,expectedDigest:bundledBaselineDigest,message:"Packaged baseline content no longer matches its verified identity.",request:requested,resolvedVersion:bundledBaseline.summary.resolvedVersion})}return{...bundledBaseline,summary:{...bundledBaseline.summary,channel:requested.channel,requested,retrieval}}};var packContents=packCatalog;var packContentsForBaseline=(baseline=bundledBaseline)=>baseline.packs;var packContentsByIdForBaseline=(baseline=bundledBaseline)=>{const contents={};for(const pack of packContentsForBaseline(baseline)){contents[pack.id]=pack}return contents};var packContentsById=packContentsByIdForBaseline();var defaultPackIds=packContents.filter((pack)=>pack.category==="default").map((pack)=>pack.id).toSorted();var languagePackIds=packContents.filter((pack)=>pack.category==="language").map((pack)=>pack.id).toSorted();var detectedPackIds=packContents.filter((pack)=>pack.category==="detected").map((pack)=>pack.id).toSorted();var surfacePackIds=packContents.filter((pack)=>pack.category==="surface").map((pack)=>pack.id).toSorted();var knownPackIds=packContents.map((pack)=>pack.id).toSorted();var defaultPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="default").map((pack)=>pack.id).toSorted();var languagePackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="language").map((pack)=>pack.id).toSorted();var detectedPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="detected").map((pack)=>pack.id).toSorted();var surfacePackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="surface").map((pack)=>pack.id).toSorted();var knownPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).map((pack)=>pack.id).toSorted();var skillsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.skills??[];var lintAssetsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.lintAssets??[];var hooksForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.hooks??[];var promptDetailsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.promptDetails??[];var exampleRepositoriesForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.exampleRepositories??[];var formatToolBootstrapStatus=(entry)=>{switch(entry.status){case"already-present":{return"already present"}case"installed":{return"installed during scaffold"}case"failed":{return"bootstrap failed"}default:{return entry.status}}};var formatToolBootstrapFailureDetails=(statuses)=>{const failures=statuses.filter((entry)=>entry.status==="failed");if(failures.length===0){return null}return["Required tool bootstrap failed, but scaffold/update output can still be written.","","Agent recovery prompt:","Read `.devpunks/settings.json`, verify each listed required tool manually, then fix the failed install before deeper repo work. If `agent-browser` failed while installing Chromium, install or repair that browser dependency outside the scaffold command, then rerun `agent-browser install` or the documented tool check.","","Failure stack traces:",...failures.flatMap((failure)=>["",`--- ${failure.toolId} ---`,failure.errorStack??failure.errorMessage??"Unknown tool bootstrap failure."])].join(`
325
+ `}else if(field==="event"){eventName=value5}else if(field==="id"&&!value5.includes("\x00")){eventId=value5;lastEventId=value5}else if(field==="retry"){const retry5=parseInt(value5,10);if(!Number.isNaN(retry5)){onParse(new Retry({duration:millis(retry5),lastEventId}))}}}}var BOM=[239,187,191];function hasBom(buffer2){return BOM.every((charCode,index2)=>buffer2.charCodeAt(index2)===charCode)}var EventEncoded=Struct({id:optional(String5),event:String5,data:String5});var RetryTypeId="~effect/encoding/Sse/Retry";class Retry extends TaggedClass("Retry"){[RetryTypeId]=RetryTypeId;static is(u){return hasProperty(u,RetryTypeId)}static filter(u){return Retry.is(u)?succeed2(u):fail2(u)}}var SecurityTypeId="~effect/httpapi/HttpApiMiddleware/Security";var isSecurity=(u)=>hasProperty(u,SecurityTypeId);var exports_OpenApi={};__export(exports_OpenApi,{fromApi:()=>fromApi,annotations:()=>annotations,Version:()=>Version2,Transform:()=>Transform,Title:()=>Title,Summary:()=>Summary,Servers:()=>Servers,Override:()=>Override,License:()=>License,Identifier:()=>Identifier,Format:()=>Format,ExternalDocs:()=>ExternalDocs,Exclude:()=>Exclude,Description:()=>Description,Deprecated:()=>Deprecated});class Identifier extends Service()("effect/httpapi/OpenApi/Identifier"){}class Title extends Service()("effect/httpapi/OpenApi/Title"){}class Version2 extends Service()("effect/httpapi/OpenApi/Version"){}class Description extends Service()("effect/httpapi/OpenApi/Description"){}class License extends Service()("effect/httpapi/OpenApi/License"){}class ExternalDocs extends Service()("effect/httpapi/OpenApi/ExternalDocs"){}class Servers extends Service()("effect/httpapi/OpenApi/Servers"){}class Format extends Service()("effect/httpapi/OpenApi/Format"){}class Summary extends Service()("effect/httpapi/OpenApi/Summary"){}class Deprecated extends Service()("effect/httpapi/OpenApi/Deprecated"){}class Override extends Service()("effect/httpapi/OpenApi/Override"){}var Exclude=Reference("effect/httpapi/OpenApi/Exclude",{defaultValue:constFalse});class Transform extends Service()("effect/httpapi/OpenApi/Transform"){}var servicesPartial=(tags2)=>{const entries3=Object.entries(tags2);return(options4)=>{let context4=empty();for(const[key,tag4]of entries3){if(options4[key]!==undefined){context4=add(context4,tag4,options4[key])}}return context4}};var annotations=servicesPartial({identifier:Identifier,title:Title,version:Version2,description:Description,license:License,summary:Summary,deprecated:Deprecated,externalDocs:ExternalDocs,servers:Servers,format:Format,override:Override,exclude:Exclude,transform:Transform});var apiCache=new WeakMap;function processAnnotation(ctx,annotation,f){const o=getOption(ctx,annotation);if(isSome2(o)){f(o.value)}}function fromApi(api){const cached3=apiCache.get(api);if(cached3!==undefined){return cached3}let spec={openapi:"3.1.0",info:{title:"Api",version:"0.0.1"},paths:{},components:{schemas:{},securitySchemes:{}},security:[],tags:[]};const pathOps=[];const pathOperations=new Set;const operationIds=new Set;processAnnotation(api.annotations,Title,(title)=>{spec.info.title=title});processAnnotation(api.annotations,Version2,(version2)=>{spec.info.version=version2});processAnnotation(api.annotations,Description,(description)=>{spec.info.description=description});processAnnotation(api.annotations,License,(license)=>{spec.info.license=license});processAnnotation(api.annotations,Summary,(summary)=>{spec.info.summary=summary});processAnnotation(api.annotations,Servers,(servers)=>{spec.servers=[...servers]});reflect(api,{onGroup({group}){if(get(group.annotations,Exclude)){return}let tag4={name:getOrElse2(group.annotations,Title,()=>group.identifier)};processAnnotation(group.annotations,Description,(description)=>{tag4.description=description});processAnnotation(group.annotations,ExternalDocs,(externalDocs)=>{tag4.externalDocs=externalDocs});processAnnotation(group.annotations,Override,(override)=>{Object.assign(tag4,override)});processAnnotation(group.annotations,Transform,(transformFn)=>{tag4=transformFn(tag4)});spec.tags.push(tag4)},onEndpoint({endpoint,group,mergedAnnotations,middleware:middleware2}){if(get(mergedAnnotations,Exclude)){return}let op={tags:[getOrElse2(group.annotations,Title,()=>group.identifier)],operationId:getOrElse2(endpoint.annotations,Identifier,()=>group.topLevel?endpoint.identifier:`${group.identifier}.${endpoint.identifier}`),parameters:[],security:[],responses:{}};const path4=endpoint.path.replace(/:(\w+)\??/g,"{$1}");const method=endpoint.method.toLowerCase();function processResponseBodies(bodies,defaultDescription){for(const[status2,{content,descriptions,streamContent}]of bodies){const description=descriptions.size>0?Array.from(descriptions).join(" | "):defaultDescription();op.responses[status2]={description};if(content!==undefined){content.forEach((map18,encoding)=>{map18.forEach((schemas,contentType)=>{const asts=Array.from(schemas,getAST);const ast=asts.length===1?asts[0]:new Union(asts,"anyOf");pathOps.push({_tag:"schema",ast:toEncodingAST(ast,encoding),path:["paths",path4,method,"responses",String(status2),"content",contentType,"schema"]});op.responses[status2].content??={};op.responses[status2].content[contentType]={schema:{}}})})}if(streamContent!==undefined){streamContent.forEach((stream3,contentType)=>{op.responses[status2].content??={};if(isStreamSse(stream3)){pathOps.push({_tag:"schema",ast:getAST(stream3.events),path:["paths",path4,method,"responses",String(status2),"content",contentType,"schema"]});pathOps.push({_tag:"schema",ast:getAST(toCodecJson(Cause(stream3.error,Defect()))),path:["paths",path4,method,"responses",String(status2),"content",contentType,"x-effect-stream","causeSchema"]});pathOps.push({_tag:"schema",ast:getAST(stream3.error),path:["paths",path4,method,"responses",String(status2),"content",contentType,"x-effect-stream","errorSchema"]});op.responses[status2].content[contentType]={schema:{},"x-effect-stream":{encoding:"sse",causeSchema:{},errorSchema:{},failureEvent:reservedStreamFailureEvent2}}}else{op.responses[status2].content[contentType]={schema:{type:"string",format:"binary"},"x-effect-stream":{encoding:"uint8array"}}}})}}}function processParameters(schema2,i){if(schema2){const ast=getLastEncoding(schema2.ast);if(isObjects(ast)){for(const ps of ast.propertySignatures){op.parameters.push({name:String(ps.name),in:i,schema:{},required:i==="path"||!isOptional(ps.type)});pathOps.push({_tag:"parameter",ast:ps.type,path:["paths",path4,method,"parameters",String(op.parameters.length-1),"schema"]})}}}}processAnnotation(endpoint.annotations,Description,(description)=>{op.description=description});processAnnotation(endpoint.annotations,Summary,(summary)=>{op.summary=summary});processAnnotation(endpoint.annotations,Deprecated,(deprecated)=>{op.deprecated=deprecated});processAnnotation(endpoint.annotations,ExternalDocs,(externalDocs)=>{op.externalDocs=externalDocs});middleware2.forEach((middleware3)=>{if(!isSecurity(middleware3)){return}for(const[name,security]of Object.entries(middleware3.security)){processHttpApiSecurity(name,security);op.security.push({[name]:[]})}});function processHttpApiSecurity(name,security){const scheme=makeSecurityScheme(security);if(!Object.hasOwn(spec.components.securitySchemes,name)){set(spec.components.securitySchemes,name,scheme);return}if(!equals(securitySchemeForComparison(spec.components.securitySchemes[name]),securitySchemeForComparison(scheme))){throw new globalThis.Error(`Conflicting OpenAPI security scheme: ${name}`)}}const hasBody2=hasBody(endpoint.method);if(hasBody2){const schemasByContentType=new Map;for(const schema2 of getPayloadSchemas(endpoint)){if(isNoContent(schema2.ast))continue;const encoding=getPayloadEncoding(schema2.ast,endpoint.method);const existing=schemasByContentType.get(encoding.contentType);if(existing===undefined){schemasByContentType.set(encoding.contentType,{encoding,schemas:[schema2]})}else{existing.schemas.push(schema2)}}if(schemasByContentType.size>0){const content={};for(const[contentType,{encoding,schemas}]of schemasByContentType){const asts=schemas.map(getAST);const ast=asts.length===1?asts[0]:new Union(asts,"anyOf");pathOps.push({_tag:"schema",ast:toEncodingAST(ast,encoding._tag),path:["paths",path4,method,"requestBody","content",contentType,"schema"]});content[contentType]={schema:{}}}op.requestBody={content,required:true}}}processParameters(endpoint.params,"path");if(!hasBody2&&endpoint.payload.size===1){const entry=endpoint.payload.values().next().value;processParameters(entry.schemas[0],"query")}processParameters(endpoint.headers,"header");processParameters(endpoint.query,"query");processResponseBodies(extractSuccessResponseBodies(endpoint),()=>"Success");processResponseBodies(extractResponseBodies(getErrorSchemas(endpoint),getStatusError,resolveDescriptionOrIdentifier),()=>"Error");processAnnotation(endpoint.annotations,Override,(override)=>{Object.assign(op,override)});processAnnotation(endpoint.annotations,Transform,(transformFn)=>{op=transformFn(op)});const pathOperation=`${method} ${path4.replace(/\{[^}]+\}/g,"{}")}`;if(pathOperations.has(pathOperation)){throw new globalThis.Error(`Duplicate OpenAPI operation for ${endpoint.method} ${path4}`)}const operationId=op.operationId;if(operationId!==undefined){if(operationIds.has(operationId)){throw new globalThis.Error(`Duplicate OpenAPI operationId: ${operationId}`)}operationIds.add(operationId)}pathOperations.add(pathOperation);if(!spec.paths[path4]){spec.paths[path4]={}}spec.paths[path4][method]=op}});processAnnotation(api.annotations,AdditionalSchemas,(componentSchemas)=>{componentSchemas.forEach((componentSchema)=>{const identifier2=resolveIdentifier2(componentSchema.ast);if(identifier2!==undefined){if(identifier2 in spec.components.schemas){throw new globalThis.Error(`Duplicate component schema identifier: ${identifier2}`)}spec.components.schemas[identifier2]={};pathOps.push({_tag:"schema",ast:componentSchema.ast,path:["components","schemas",identifier2]})}})});function escapePath(path4){return"/"+path4.map(escapeToken).join("/")}if(isArrayNonEmpty2(pathOps)){const multiDocument=fromASTs2(map4(pathOps,(op)=>op.ast));const jsonSchemaMultiDocument=toMultiDocumentOpenApi3_1(toJsonSchemaMultiDocument2(multiDocument));const patchOps=pathOps.map((op,i)=>{const oppath=escapePath(op.path);const value5=jsonSchemaMultiDocument.schemas[i];return{op:"replace",path:oppath,value:value5}});Object.entries(jsonSchemaMultiDocument.definitions).forEach(([name,definition])=>{patchOps.push({op:"add",path:escapePath(["components","schemas",name]),value:definition})});spec=apply(patchOps,spec)}Object.keys(spec.components.schemas).forEach((key)=>{if(!VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP.test(key)){throw new globalThis.Error(`Invalid component schema key: ${key}`)}});processAnnotation(api.annotations,Override,(override)=>{Object.assign(spec,override)});processAnnotation(api.annotations,Transform,(transformFn)=>{spec=transformFn(spec)});apiCache.set(api,spec);return spec}var reservedStreamFailureEvent2="effect/httpapi/stream/failure";function extractSuccessResponseBodies(endpoint){return extractResponseBodies(getSuccessSchemas(endpoint),getStatusSuccess,resolveDescriptionOrIdentifier)}function extractResponseBodies(schemas,getStatus,getDescription){const map18=new Map;schemas.forEach(process2);return map18;function process2(schema2){if(isStreamSchema(schema2)){addStreamContent(schema2);return}const ast=schema2.ast;const status2=getStatus(ast);if(isNoContent(ast)){addNoContent(status2,getDescription(schema2.ast)??"<No Content>")}else{addContent(schema2,status2,getResponseEncoding(ast))}}function addNoContent(status2,description){const statusMap=map18.get(status2);if(statusMap===undefined){map18.set(status2,{descriptions:new Set([description]),content:undefined,streamContent:undefined})}else{if(description!==undefined){statusMap.descriptions.add(description)}}}function addContent(schema2,status2,encoding){const description=getDescription(schema2.ast);const statusMap=map18.get(status2);const{_tag,contentType}=encoding;if(statusMap===undefined){map18.set(status2,{descriptions:new Set(description!==undefined?[description]:[]),content:new Map([[_tag,new Map([[contentType,new Set([schema2])]])]]),streamContent:undefined})}else{if(description!==undefined){statusMap.descriptions.add(description)}if(statusMap.content===undefined){statusMap.content=new Map([[_tag,new Map([[contentType,new Set([schema2])]])]])}else{const schemasByContentType=statusMap.content.get(_tag);if(schemasByContentType===undefined){statusMap.content.set(_tag,new Map([[contentType,new Set([schema2])]]))}else{const set7=schemasByContentType.get(contentType);if(set7===undefined){schemasByContentType.set(contentType,new Set([schema2]))}else{set7.add(schema2)}}}}}function addStreamContent(stream3){const status2=getStatusStream(stream3);const statusMap=map18.get(status2);if(statusMap===undefined){map18.set(status2,{descriptions:new Set,content:undefined,streamContent:new Map([[stream3.contentType,stream3]])})}else if(statusMap.streamContent===undefined){statusMap.streamContent=new Map([[stream3.contentType,stream3]])}else{statusMap.streamContent.set(stream3.contentType,stream3)}}}function resolveDescriptionOrIdentifier(ast){return resolveDescription2(ast)??resolveIdentifier2(ast)}var Uint8ArrayEncoding=String5.annotate({format:"binary"});function toEncodingAST(ast,_tag){switch(_tag){case"Uint8Array":return Uint8ArrayEncoding.ast;case"Text":return String5.ast;case"FormUrlEncoded":case"Json":return ast;case"Multipart":return persistedFileToBinaryEncoding(ast)}}function persistedFileToBinaryEncoding(ast){if(isDeclaration(ast)&&ast.annotations?.typeConstructor?._tag==="effect/http/PersistedFile"){return Uint8ArrayEncoding.ast}if(typeof ast?.recur==="function"){return ast.recur(persistedFileToBinaryEncoding)}return ast}var makeSecurityScheme=(security)=>{const meta={};processAnnotation(security.annotations,Description,(description)=>{meta.description=description});switch(security._tag){case"Basic":{return{...meta,type:"http",scheme:"basic"}}case"Http":{const format5=getOption(security.annotations,Format).pipe(map((format6)=>({bearerFormat:format6})),getOrUndefined);return{...meta,type:"http",scheme:security.scheme,...format5}}case"ApiKey":{return{...meta,type:"apiKey",name:security.key,in:security.in}}}};var securitySchemeForComparison=(scheme)=>{if(scheme.type==="http"){return{...scheme,scheme:scheme.scheme.toLowerCase()}}if(scheme.in==="header"){return{...scheme,name:scheme.name.toLowerCase()}}return scheme};var exports_HttpApiClient={};__export(exports_HttpApiClient,{urlBuilder:()=>urlBuilder,makeWith:()=>makeWith3,makeClient:()=>makeClient,make:()=>make46,group:()=>group,endpoint:()=>endpoint});var makeClient=(api,options4)=>gen2(function*(){const services=yield*context2();const httpClient=options4.httpClient.pipe(options4?.baseUrl===undefined?identity:mapRequest(prependUrl(options4.baseUrl.toString())));function executeMiddleware(group,endpoint,request3,middlewareKeys,index2){if(index2===-1){return httpClient.execute(request3)}const middleware2=services.mapUnsafe.get(middlewareKeys[index2]);if(middleware2===undefined){return executeMiddleware(group,endpoint,request3,middlewareKeys,index2-1)}return middleware2({endpoint,group,request:request3,next(request4){return executeMiddleware(group,endpoint,request4,middlewareKeys,index2-1)}})}reflect(api,{predicate:options4?.predicate,onGroup(onGroupOptions){options4.onGroup?.(onGroupOptions)},onEndpoint(onEndpointOptions){const{group,endpoint,errors:errors2,successes}=onEndpointOptions;const makeUrl=compilePath(endpoint.path);const decodeMap={orElse:statusOrElse};const decodeResponse=matchStatus(decodeMap);const errorAlternatives=new Map;for(const[status2,schemas]of errors2.entries()){const grouped=groupSchemasByContentType(schemas);for(const[contentType,schemas2]of grouped.entries()){addResponseAlternative(errorAlternatives,status2,contentType,schemasToResponse(schemas2))}}for(const[status2,alternatives]of errorAlternatives.entries()){const decode4=makeResponseDecoder(alternatives);decodeMap[status2]=(response)=>flatMap4(catchCause2(decode4(response),(cause)=>failCause3(combine2(fail5(new HttpClientError({reason:new StatusCodeError({request:response.request,response})})),cause))),fail6)}const successAlternatives=new Map;for(const[status2,schemas]of successes.entries()){const grouped=groupSchemasByContentType(schemas);for(const[contentType,schemas2]of grouped.entries()){addResponseAlternative(successAlternatives,status2,contentType,schemasToResponse(schemas2))}}for(const streamSuccess of getStreamSuccessSchemas(endpoint)){addResponseAlternative(successAlternatives,getStatusStream(streamSuccess),streamSuccess.contentType,streamToResponse(streamSuccess))}for(const[status2,alternatives]of successAlternatives.entries()){decodeMap[status2]=makeResponseDecoder(alternatives)}const encodeParams=map12(endpoint.params,encodeUnknownEffect2);const payloadSchemas=getPayloadSchemas(endpoint);const encodePayload=isArrayNonEmpty2(payloadSchemas)?hasBody(endpoint.method)?encodeUnknownEffect2(getEncodePayloadSchema(payloadSchemas,endpoint.method)):encodeUnknownEffect2(Union2(payloadSchemas)):undefined;const encodeHeaders=map12(endpoint.headers,encodeUnknownEffect2);const encodeQuery=map12(endpoint.query,encodeUnknownEffect2);const middlewareKeys=Array.from(onEndpointOptions.middleware,(tag4)=>`${tag4.key}/Client`);const endpointFn=fnUntraced2(function*(request3){let httpRequest=make42(endpoint.method)(endpoint.path);if(request3!==undefined){if(encodeParams!==undefined){const params=yield*encodeParams(request3.params);httpRequest=setUrl(httpRequest,makeUrl(params))}if(encodePayload!==undefined){if(hasBody(endpoint.method)){if(request3.payload instanceof FormData){httpRequest=bodyFormData(httpRequest,request3.payload)}else{const body=yield*encodePayload(request3.payload);httpRequest=setBody(httpRequest,body)}}else{const urlParams2=yield*encodePayload(request3.payload);httpRequest=appendUrlParams(httpRequest,urlParams2)}}if(encodeHeaders!==undefined){const headers=yield*encodeHeaders(request3.headers);httpRequest=setHeaders(httpRequest,headers)}if(encodeQuery!==undefined){const query=yield*encodeQuery(request3.query);httpRequest=appendUrlParams(httpRequest,query)}}const response=yield*executeMiddleware(group,endpoint,httpRequest,middlewareKeys,middlewareKeys.length-1);if(request3?.responseMode==="response-only"){return response}const value5=yield*options4.transformResponse===undefined?decodeResponse(response):options4.transformResponse(decodeResponse(response));return request3?.responseMode==="decoded-and-response"?[value5,response]:value5});options4.onEndpoint({...onEndpointOptions,endpointFn})}})});var make46=(api,options4)=>flatMap4(HttpClient,(httpClient)=>makeWith3(api,{...options4,httpClient:options4?.transformClient?options4.transformClient(httpClient):httpClient}));var makeWith3=(api,options4)=>{const client={};return makeClient(api,{...options4,onGroup({group}){if(group.topLevel)return;set(client,group.identifier,{})},onEndpoint({endpoint,endpointFn,group}){set(group.topLevel?client:client[group.identifier],endpoint.identifier,endpointFn)}}).pipe(as2(client))};var group=(api,options4)=>{const client={};return makeClient(api,{...options4,predicate:({group:group2})=>group2.identifier===options4.group,onEndpoint({endpoint,endpointFn}){set(client,endpoint.identifier,endpointFn)}}).pipe(map7(()=>client))};var endpoint=(api,options4)=>{let client=undefined;return makeClient(api,{...options4,httpClient:options4.transformClient?options4.transformClient(options4.httpClient):options4.httpClient,predicate:({endpoint:endpoint2,group:group2})=>group2.identifier===options4.group&&endpoint2.identifier===options4.endpoint,onEndpoint({endpointFn}){client=endpointFn}}).pipe(map7(()=>client))};var urlBuilder=(api,options4)=>{const builder={};reflect(api,{onGroup({group:group2}){if(group2.topLevel)return;set(builder,group2.identifier,{})},onEndpoint({group:group2,endpoint:endpoint2}){const makeUrl=compilePath(endpoint2.path);const encodeParams=endpoint2.params===undefined?undefined:encodeSync2(endpoint2.params);const encodeQuery=endpoint2.query===undefined?undefined:encodeSync2(endpoint2.query);const endpointBuilder=(request3)=>{const params=request3?.params;const path4=params===undefined?endpoint2.path:makeUrl(encodeParams===undefined?params:encodeParams(params));const queryInput=request3?.query===undefined?undefined:encodeQuery===undefined?request3.query:encodeQuery(request3.query);const query=queryInput===undefined?"":toString(fromInput3(queryInput));const url2=query===""?path4:`${path4}?${query}`;return options4?.baseUrl===undefined?url2:new URL(url2,options4.baseUrl.toString()).toString()};set(group2.topLevel?builder:builder[group2.identifier],endpoint2.identifier,endpointBuilder)}});return builder};var paramsRegExp=/(\/?):(\w+)(\?)?/g;var compilePath=(path4)=>{if(!paramsRegExp.test(path4)){return(_)=>path4}paramsRegExp.lastIndex=0;return(params)=>{paramsRegExp.lastIndex=0;return path4.replace(paramsRegExp,(_,slash,key,optional4)=>{const value5=params[key];if(value5===undefined){if(optional4!==undefined){return""}throw new Error(`Missing path parameter: ${key}`)}return`${slash}${encodeURIComponent(value5)}`})}};function schemasToResponse(schemas){const codec=toCodecArrayBuffer(schemas);const decode4=decodeEffect2(codec);return(response)=>flatMap4(response.arrayBuffer,decode4)}function addResponseAlternative(map18,status2,contentType,decode4){const normalizedContentType=normalize2(contentType);const alternatives=map18.get(status2);if(alternatives===undefined){map18.set(status2,[{contentType:normalizedContentType,decode:decode4}])}else{alternatives.push({contentType:normalizedContentType,decode:decode4})}}function makeResponseDecoder(alternatives){const first=alternatives[0];if(alternatives.length===1&&first!==undefined){return first.decode}return(response)=>{const contentType=normalize2(response.headers["content-type"]??"");const alternative=alternatives.find((alternative2)=>alternative2.contentType===contentType);return alternative===undefined?failUnsupportedContentType(response,contentType,alternatives):alternative.decode(response)}}function groupSchemasByContentType(schemas){const grouped=new Map;for(const schema2 of schemas){const contentType=isNoContent(schema2.ast)?"":normalize2(getResponseEncoding(schema2.ast).contentType);const existing=grouped.get(contentType);if(existing===undefined){grouped.set(contentType,[schema2])}else{existing.push(schema2)}}return grouped}function failUnsupportedContentType(response,contentType,alternatives){const expected=Array.from(new Set(alternatives.map((alternative)=>alternative.contentType))).join(", ");return fail6(new HttpClientError({reason:new DecodeError({request:response.request,response,description:`Unsupported response content-type for status ${response.status}: ${contentType||"<missing>"}. Expected one of: ${expected}`})}))}var reservedStreamFailureEvent3="effect/httpapi/stream/failure";function getStreamSuccessSchemas(endpoint2){const schemas=[];for(const schema2 of endpoint2.success){if(isStreamSchema(schema2)){schemas.push(schema2)}}return schemas}function streamToResponse(streamSchema2){const sse=isStreamUint8Array(streamSchema2)?undefined:{declaration:streamSchema2,decoder:makeSseDecoder(streamSchema2)};return(response)=>map7(context2(),(context4)=>provideContext4(sse===undefined?response.stream:decodeSseStream(response.stream,sse.declaration,sse.decoder),context4))}function makeSseDecoder(declaration){const Event=Union2([Struct({event:Literal2(reservedStreamFailureEvent3),data:fromJsonString2(toCodecJson(Cause(declaration.error,Defect())))}),declaration.events]);return decodeSchema(Event)}function decodeSseStream(stream3,declaration,decoder2){const events=transformPull2(stream3.pipe(decodeText,pipeThroughChannel(decoder2)),(pull)=>sync2(()=>{let pendingFailureCause=undefined;return suspend2(()=>{if(pendingFailureCause!==undefined){return failCause3(pendingFailureCause)}return flatMap4(pull,(events2)=>{for(let i=0;i<events2.length;i++){const event=events2[i];if(event.event===reservedStreamFailureEvent3&&isCause2(event.data)){if(i===0){return failCause3(event.data)}pendingFailureCause=event.data;events2=events2.slice(0,i);break}}return succeed6(events2)})})}));if(declaration.sseMode==="data"){return map9(events,(event)=>event.data)}return events}var ArrayBuffer2=instanceOf(globalThis.ArrayBuffer,{expected:"ArrayBuffer"});var Uint8ArrayFromArrayBuffer=ArrayBuffer2.pipe(decodeTo2(Uint8Array2,transform2({decode(fromA){return new Uint8Array(fromA)},encode(arr){return arr.byteLength===arr.buffer.byteLength?arr.buffer:arr.buffer.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)}})));var StringFromArrayBuffer=ArrayBuffer2.pipe(decodeTo2(String5,transform2({decode(fromA){return new TextDecoder().decode(fromA)},encode(toI){const arr=new TextEncoder().encode(toI);return arr.byteLength===arr.buffer.byteLength?arr.buffer:arr.buffer.slice(arr.byteOffset,arr.byteOffset+arr.byteLength)}})));var UnknownFromArrayBuffer=StringFromArrayBuffer.pipe(decodeTo2(Union2([Literal2("").pipe(decodeTo2(Undefined2,transform2({decode:()=>{return},encode:()=>""}))),UnknownFromJsonString])));function toCodecArrayBuffer(schemas){return Union2(schemas.map(onSchema));function onSchema(schema2){const encoding=getResponseEncoding(schema2.ast);switch(encoding._tag){case"Json":{const encodedIsNull=isNull(toEncoded(schema2.ast));return UnknownFromArrayBuffer.pipe(decodeTo2(schema2,encodedIsNull?transform2({decode:(a)=>a===undefined?null:a,encode:(a)=>a===null?undefined:a}):undefined))}case"FormUrlEncoded":return StringFromArrayBuffer.pipe(decodeTo2(schemaRecord),decodeTo2(schema2));case"Uint8Array":return Uint8ArrayFromArrayBuffer.pipe(decodeTo2(schema2));case"Text":return StringFromArrayBuffer.pipe(decodeTo2(schema2))}}}var statusOrElse=(response)=>fail6(new HttpClientError({reason:new DecodeError({request:response.request,response})}));var $HttpBody=declare(isHttpBody);function getEncodePayloadSchema(schemas,method){return Union2(schemas.map((s)=>getEncodePayloadSchemaFromBody(s,method)))}var bodyFromPayloadCache=new WeakMap;function getEncodePayloadSchemaFromBody(schema2,method){const ast=schema2.ast;const cached3=bodyFromPayloadCache.get(ast);if(cached3!==undefined){return cached3}const encoding=getPayloadEncoding(ast,method);const out=$HttpBody.pipe(decodeTo2(schema2,transformOrFail2({decode(httpBody){return fail6(new Forbidden(some2(httpBody),{message:"Encode only schema"}))},encode(t){switch(encoding._tag){case"Multipart":return fail6(new Forbidden(some2(t),{message:"Payload must be a FormData"}));case"Json":{try{const body=JSON.stringify(t);return succeed6(text2(body,encoding.contentType))}catch(error2){return fail6(new InvalidValue(some2(t),{message:globalThis.String(error2)}))}}case"Text":{if(typeof t!=="string"){return fail6(new InvalidValue(some2(t),{message:"Expected a string"}))}return succeed6(text2(t,encoding.contentType))}case"FormUrlEncoded":{if(!isObject(t)){return fail6(new InvalidValue(some2(t),{message:"Expected a record"}))}return succeed6(urlParams(fromInput3(t),encoding.contentType))}case"Uint8Array":{if(!(t instanceof Uint8Array)){return fail6(new InvalidValue(some2(t),{message:"Expected a Uint8Array"}))}return succeed6(uint8Array2(t,encoding.contentType))}}}})));bodyFromPayloadCache.set(ast,out);return out}var exports_HttpApiGroup={};__export(exports_HttpApiGroup,{make:()=>make47,isHttpApiGroup:()=>isHttpApiGroup});var TypeId56="~effect/httpapi/HttpApiGroup";var isHttpApiGroup=(u)=>hasProperty(u,TypeId56);var Proto19={[TypeId56]:TypeId56,add(...toAdd){const endpoints={...this.endpoints};for(const endpoint2 of toAdd){set(endpoints,endpoint2.identifier,endpoint2)}return makeProto4({...optionsFromGroup(this),endpoints})},prefix(prefix){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.prefix(prefix))})},middleware(middleware2){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.middleware(middleware2))})},annotateMerge(annotations2){return makeProto4({...optionsFromGroup(this),annotations:merge(this.annotations,annotations2)})},annotate(annotation,value5){return makeProto4({...optionsFromGroup(this),annotations:add(this.annotations,annotation,value5)})},annotateEndpointsMerge(annotations2){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.annotateMerge(annotations2))})},annotateEndpoints(annotation,value5){return makeProto4({...optionsFromGroup(this),endpoints:map3(this.endpoints,(endpoint2)=>endpoint2.annotate(annotation,value5))})},pipe(){return pipeArguments(this,arguments)}};var optionsFromGroup=(group2)=>({identifier:group2.identifier,topLevel:group2.topLevel,endpoints:group2.endpoints,annotations:group2.annotations});var makeProto4=(options4)=>{function HttpApiGroup(){}Object.setPrototypeOf(HttpApiGroup,Proto19);HttpApiGroup.key=`effect/httpapi/HttpApiGroup/${options4.identifier}`;return Object.assign(HttpApiGroup,options4)};var make47=(identifier2,options4)=>makeProto4({identifier:identifier2,topLevel:options4?.topLevel??false,endpoints:{},annotations:empty()});var defaultMessage=(message)=>String5.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var BaselineChannel=Literals(["stable","bundled"]);var HarnessReportStatus=Literals(["new","triaged","accepted","wontfix","resolved"]);var OperatorIdentity=Struct({operatorId:String5,email:optionalKey2(String5),emailVerified:optionalKey2(Boolean4)}).annotate({identifier:"OperatorIdentity"});var isoDateTimePattern=/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})(?:\.(?<fraction>\d{1,9}))?(?:Z|[+-]\d{2}:\d{2})$/u;var isValidIsoDateTime=(value5)=>{const groups=isoDateTimePattern.exec(value5)?.groups;if(groups===undefined){return false}const year=Number(groups.year);const month=Number(groups.month);const day=Number(groups.day);const hour=Number(groups.hour);const minute=Number(groups.minute);const second=Number(groups.second);const millisecond=Number((groups.fraction??"").slice(0,3).padEnd(3,"0"));const date7=new Date(Date.UTC(year,month-1,day,hour,minute,second,millisecond));return Number.isFinite(Date.parse(value5))&&date7.getUTCFullYear()===year&&date7.getUTCMonth()===month-1&&date7.getUTCDate()===day&&date7.getUTCHours()===hour&&date7.getUTCMinutes()===minute&&date7.getUTCSeconds()===second};var IsoDateTimeString=String5.pipe(refine((value5)=>isValidIsoDateTime(value5),{identifier:"IsoDateTimeString",description:"an ISO 8601 datetime string with timezone"}));var GitIdentity=Struct({name:optionalKey2(String5),email:optionalKey2(String5)}).annotate({identifier:"GitIdentity"});var ObservedRepositoryInput=Struct({remoteUrl:optionalKey2(String5),remoteHost:optionalKey2(String5),remotePath:optionalKey2(String5),branch:optionalKey2(String5),commitSha:optionalKey2(String5),dirty:optionalKey2(Boolean4),gitIdentity:optionalKey2(GitIdentity)}).annotate({identifier:"ObservedRepositoryInput"});var SymbolPropertyKey=Struct({_tag:Literal2("symbol"),key:String5}).annotate({description:"an object to be decoded into a globally shared symbol"});var PropertyKey2=Union2([String5,Finite,SymbolPropertyKey]).annotate({identifier:"PropertyKey"});var DecodeIssue=Struct({_tag:Literals(["Pointer","Unexpected","Missing","Composite","Refinement","Transformation","Type","Forbidden"]),path:ArraySchema(PropertyKey2),message:String5}).annotate({identifier:"Issue"});class HttpApiDecodeError extends TaggedErrorClass()("HttpApiDecodeError",{issues:ArraySchema(DecodeIssue),message:String5},{httpApiStatus:400,description:"The request did not match the expected schema"}){}class Forbidden2 extends TaggedErrorClass()("@punks/contract/errors/Forbidden",{message:defaultMessage("The supplied credentials cannot access this resource.")},{httpApiStatus:403,title:"Forbidden"}){}var defaultMessage2=(message)=>String5.pipe(optionalKey2,withConstructorDefault2(succeed6(message)));var ArtifactKind=Literals(["manifest","archive"]);var BaselineVersion=NonEmptyString.annotate({identifier:"BaselineVersion"});var NonBlankString=String5.check(isTrimmed(),isNonEmpty());var BaselineRevision=String5.check(isPattern2(/^[1-9][0-9]*$/u)).annotate({identifier:"BaselineRevision"});var BaselineSha256=String5.check(isPattern2(/^[0-9a-f]{64}$/u)).annotate({identifier:"BaselineSha256"});var BaselinePromotionArtifact=Struct({url:NonBlankString,sha256:BaselineSha256}).annotate({identifier:"BaselinePromotionArtifact"});var BaselinePromotionCandidate=Struct({releaseId:NonBlankString,version:BaselineVersion,tag:NonBlankString,publishedAt:IsoDateTimeString,commitSha:NonBlankString,provenance:NonBlankString,cliVersionRange:NonBlankString,manifest:BaselinePromotionArtifact,archive:BaselinePromotionArtifact}).annotate({identifier:"BaselinePromotionCandidate"});var BaselinePublishRequest=Struct({mode:Literal2("publish"),candidate:BaselinePromotionCandidate,publicationIdentity:NonBlankString,expectedRevision:optionalKey2(BaselineRevision),reason:optionalKey2(Never2)});var BaselineRollbackRequest=Struct({mode:Literal2("rollback"),candidate:BaselinePromotionCandidate,publicationIdentity:NonBlankString,expectedRevision:BaselineRevision,reason:NonBlankString});var BaselinePromotionRequest=Union2([BaselinePublishRequest,BaselineRollbackRequest]).annotate({identifier:"BaselinePromotionRequest"});var BaselinePromotionResult=Struct({outcome:Literals(["committed","already-committed"]),revision:BaselineRevision,mode:Literals(["publish","rollback"]),candidate:BaselinePromotionCandidate,publicationIdentity:NonBlankString,previousRevision:optionalKey2(BaselineRevision),previousReleaseId:optionalKey2(NonBlankString),committedAt:IsoDateTimeString}).annotate({identifier:"BaselinePromotionResult"});var BaselineRequest=Struct({channel:BaselineChannel,version:optionalKey2(BaselineVersion)}).annotate({identifier:"BaselineRequest"});var BaselineVersionRequest=Struct({version:optionalKey2(BaselineVersion)}).annotate({identifier:"BaselineVersionRequest"});var BaselineSource=Literals(["control-plane","published-release","cache","bundled"]);var BaselineCompatibility=Struct({cliVersionRange:String5}).annotate({identifier:"BaselineCompatibility"});var BaselineRetrievalStatus=Literals(["available","retrieved","cached","fallback"]);var ArtifactMetadata=Struct({kind:ArtifactKind,fileName:String5,contentType:String5,url:String5,sha256:String5,sizeBytes:optionalKey2(Finite)}).annotate({identifier:"ArtifactMetadata"});var BaselineIdentity={requested:BaselineRequest,resolvedVersion:BaselineVersion,digest:String5,source:BaselineSource,provenance:String5,compatibility:BaselineCompatibility,retrieval:BaselineRetrievalStatus};var BaselineResolution=Struct({...BaselineIdentity,manifest:ArtifactMetadata,archive:ArtifactMetadata}).pipe(check2(makeFilter2(({requested,resolvedVersion})=>requested.version===undefined||requested.version===resolvedVersion,{message:"An exact baseline request must resolve to the requested version."})),check2(makeFilter2(({digest:digest2,archive})=>digest2===archive.sha256,{message:"The baseline digest must match the archive digest."}))).annotate({identifier:"BaselineResolution"});var BaselineArtifact=Struct({...BaselineIdentity,artifact:ArtifactMetadata}).pipe(check2(makeFilter2(({requested,resolvedVersion})=>requested.version===undefined||requested.version===resolvedVersion,{message:"Artifact metadata must match the exact requested baseline version."})),check2(makeFilter2(({artifact,digest:digest2})=>artifact.kind!=="archive"||artifact.sha256===digest2,{message:"The baseline artifact digest must match the verified baseline digest."}))).annotate({identifier:"BaselineArtifact"});class BaselineNotFound extends TaggedErrorClass()("@punks/contract/errors/BaselineNotFound",{channel:String5,message:defaultMessage2("No baseline exists for the requested channel.")},{httpApiStatus:404,title:"Baseline Not Found"}){}class ControlPlaneUnavailable extends TaggedErrorClass()("@punks/contract/errors/ControlPlaneUnavailable",{message:defaultMessage2("The control plane cannot resolve this resource yet.")},{httpApiStatus:503,title:"Control Plane Unavailable"}){}class BaselineAuthorityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselineAuthorityFailure",{request:BaselineRequest,resolvedVersion:optionalKey2(BaselineVersion),message:String5},{httpApiStatus:409,title:"Baseline Authority Failure"}){}class BaselineIntegrityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselineIntegrityFailure",{request:BaselineRequest,resolvedVersion:optionalKey2(BaselineVersion),expectedDigest:optionalKey2(String5),actualDigest:optionalKey2(String5),message:defaultMessage2("Baseline identity or artifact integrity verification failed.")},{httpApiStatus:422,title:"Baseline Integrity Failure"}){}var BaselineAvailability=Literals(["authority-unconfigured","network","unavailable-status"]);class BaselineUnavailable extends TaggedErrorClass()("@punks/contract/errors/BaselineUnavailable",{availability:BaselineAvailability,request:BaselineRequest,message:defaultMessage2("The requested baseline is unavailable.")},{httpApiStatus:503,title:"Baseline Unavailable"}){}class BaselinePublisherUnauthorized extends TaggedErrorClass()("@punks/contract/errors/BaselinePublisherUnauthorized",{message:defaultMessage2("Baseline publisher authentication is required.")},{httpApiStatus:401,title:"Baseline Publisher Unauthorized"}){}class BaselinePromotionConflict extends TaggedErrorClass()("@punks/contract/errors/BaselinePromotionConflict",{publicationIdentity:NonBlankString,expectedRevision:optionalKey2(BaselineRevision),actualRevision:optionalKey2(BaselineRevision),message:String5},{httpApiStatus:409,title:"Baseline Promotion Conflict"}){}class BaselinePromotionIntegrityFailure extends TaggedErrorClass()("@punks/contract/errors/BaselinePromotionIntegrityFailure",{publicationIdentity:NonBlankString,releaseId:optionalKey2(NonBlankString),expectedDigest:optionalKey2(BaselineSha256),actualDigest:optionalKey2(BaselineSha256),message:defaultMessage2("Baseline promotion evidence failed integrity verification.")},{httpApiStatus:422,title:"Baseline Promotion Integrity Failure"}){}class BaselinePromotionUnavailable extends TaggedErrorClass()("@punks/contract/errors/BaselinePromotionUnavailable",{publicationIdentity:NonBlankString,outcome:Literals(["not-committed","indeterminate"]),message:defaultMessage2("Baseline promotion is unavailable.")},{httpApiStatus:503,title:"Baseline Promotion Unavailable"}){}var errors2=[HttpApiDecodeError,Forbidden2,BaselineNotFound,BaselineAuthorityFailure,BaselineIntegrityFailure,BaselineUnavailable];var promotionErrors=[HttpApiDecodeError,Forbidden2,BaselinePublisherUnauthorized,BaselinePromotionConflict,BaselinePromotionIntegrityFailure,BaselinePromotionUnavailable];var BaselineApi=exports_HttpApiGroup.make("baseline").add(exports_HttpApiEndpoint.get("resolve","/:channel",{params:{channel:BaselineChannel},query:BaselineVersionRequest,success:BaselineResolution,error:errors2}),exports_HttpApiEndpoint.get("artifact","/:channel/artifacts/:kind",{params:{channel:BaselineChannel,kind:ArtifactKind},query:BaselineVersionRequest,success:BaselineArtifact,error:errors2}),exports_HttpApiEndpoint.post("promote","/stable/promotions",{payload:BaselinePromotionRequest,success:BaselinePromotionResult,error:promotionErrors})).prefix("/baselines").annotateMerge(exports_OpenApi.annotations({title:"Baseline control plane"}));import{createHash as createHash2}from"node:crypto";import{lstatSync,readFileSync,readdirSync,readlinkSync}from"node:fs";import path4 from"node:path";var digestContentRoots=(roots)=>{const entries3=[];for(const{root,prefix,include=()=>true,logicalPath=(value5)=>value5}of roots){const visit2=(directory3)=>{for(const entry of readdirSync(directory3,{withFileTypes:true})){const absolutePath=path4.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}const relativePath=path4.relative(root,absolutePath).split(path4.sep).join("/");if(include(relativePath)){entries3.push({absolutePath,identity:`${prefix}/${logicalPath(relativePath)}`})}}};visit2(root)}const hash3=createHash2("sha256");for(const{absolutePath,identity:identity3}of entries3.toSorted((left,right)=>left.identity.localeCompare(right.identity))){const stat3=lstatSync(absolutePath);hash3.update(identity3);hash3.update("\x00");if(stat3.isSymbolicLink()){hash3.update("symlink\x00");hash3.update(readlinkSync(absolutePath))}else{hash3.update("file\x00");hash3.update(readFileSync(absolutePath))}hash3.update("\x00")}return hash3.digest("hex")};import{existsSync,mkdirSync,readFileSync as readFileSync2,statSync,writeFileSync}from"node:fs";import{tmpdir as tmpdir2}from"node:os";import path5 from"node:path";var embeddedAssets=[];var name="@punks/cli";var version2="3.1.1";var findFirst6=(candidates)=>candidates.find((candidate)=>existsSync(candidate));var executableSignature=()=>{try{return String(Math.trunc(statSync(process.execPath).mtimeMs))}catch{return"unknown"}};var extractEmbeddedAssets=()=>{if(embeddedAssets.length===0){return}const root=path5.join(tmpdir2(),"punks-cli-assets",`${version2}-${executableSignature()}`);for(const asset of embeddedAssets){const targetPath=path5.join(root,asset.relativePath);if(existsSync(targetPath)){continue}mkdirSync(path5.dirname(targetPath),{recursive:true});writeFileSync(targetPath,readFileSync2(asset.path))}return root};var findBundledPackageRoot=()=>{let currentDirectory=path5.resolve(import.meta.dirname,"../..");while(true){if(existsSync(path5.join(currentDirectory,"package.json"))){return currentDirectory}const parentDirectory=path5.dirname(currentDirectory);if(parentDirectory===currentDirectory){break}currentDirectory=parentDirectory}return path5.resolve(import.meta.dirname,"../..")};var packageRoot=findBundledPackageRoot();var runtimeRoot=import.meta.dirname;var embeddedAssetsRoot=extractEmbeddedAssets();var executableRoots=[process.argv[1],process.execPath].filter((candidate)=>candidate!==undefined&&candidate.length>0).map((candidate)=>path5.dirname(path5.resolve(candidate)));var dataCandidates=[path5.join(runtimeRoot,"data"),...embeddedAssetsRoot===undefined?[]:[path5.join(embeddedAssetsRoot,"data")],...executableRoots.map((root)=>path5.join(root,"data")),path5.resolve(import.meta.dirname,"../data"),path5.join(packageRoot,"src/data"),path5.resolve(import.meta.dirname,"../../src/data")];var skillCandidates=[path5.join(runtimeRoot,"skills"),...embeddedAssetsRoot===undefined?[]:[path5.join(embeddedAssetsRoot,"skills")],...executableRoots.map((root)=>path5.join(root,"skills")),path5.join(packageRoot,"skills"),path5.resolve(import.meta.dirname,"../../skills"),path5.resolve(import.meta.dirname,"../skills")];var resolvedDataRoot=findFirst6(dataCandidates);var resolvedSkillsRoot=findFirst6(skillCandidates);if(resolvedDataRoot===undefined){throw new Error("Could not locate bundled data directory.")}if(resolvedSkillsRoot===undefined){throw new Error("Could not locate bundled skills directory.")}var dataRoot=resolvedDataRoot;var skillsRoot=resolvedSkillsRoot;var dataPath=(...segments)=>path5.join(dataRoot,...segments);var readDataFile=(...segments)=>readFileSync2(dataPath(...segments),"utf-8");var readBaselineDataFile=(baselineDataRoot,...segments)=>readFileSync2(path5.join(baselineDataRoot,...segments),"utf-8");var resolveBaselinePath=({baselineRoot,baselineSkillsRoot,relativePath})=>{const resolvedPath=relativePath.startsWith("skills/")?findFirst6([path5.join(baselineSkillsRoot,relativePath.slice("skills/".length)),path5.join(baselineRoot,relativePath)]):findFirst6([path5.join(baselineRoot,relativePath)]);if(resolvedPath!==undefined){return resolvedPath}throw new Error(`Could not locate baseline asset: ${relativePath}`)};var bundledBaselineDigest="09c98193f19bd32231fc47644f7ee0bb16aa8e9486d68bc6e9b1b56199cbe3be";var hookCatalog=[{description:"Shared session-start hook that reports whether managed Harness scaffold output is current.",harness:"shared",id:"scaffold-update-check",outputPath:".agents/hooks/scaffold-update-check.mjs",sourcePath:"hooks/scaffold-update-check.mjs"},{description:"Shared hook that auto-formats edited JS/TS/JSON files and lint-checks product files after tool use.",harness:"shared",id:"format-edited-file",outputPath:".agents/hooks/format-edited-file.mjs",sourcePath:"hooks/format-edited-file.mjs"}];var sharedReactPlacement={placementNotes:"Add as an override for detected React-rendered code. Keep backend packages outside this override unless they render React.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-react-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected React workspaces"]};var webOnlyPlacement={placementNotes:"Place this in the Next.js app override. If the repo uses a different frontend app path, retarget the file globs to that workspace before composing the final Oxlint config.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-nextjs-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Next.js workspaces"]};var effectPlacement={placementNotes:"Apply this only where Effect code lives. If the target repo renames or splits backend workspaces, move the override with those code paths instead of broadening it repo-wide.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-effect-workspace>/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected Effect workspaces"]};var vitestPlacement={placementNotes:"Attach this to test-only globs. Expand or narrow the file patterns to match the repo's actual Vitest test layout instead of treating it as a global default.",recommendedConfigFile:"oxlint.config.ts",recommendedFiles:["<detected-test-workspace>/**/*.{test,spec}.{js,jsx,ts,tsx}","<detected-test-workspace>/src/test/**/*.{js,jsx,ts,tsx}"],recommendedWorkspaces:["detected JavaScript/TypeScript test workspaces"]};var lintCatalog=[{description:"Ultracite React preset for rendered app and shared UI code.",id:"react-core",jsPlugins:[],oxlintPresets:["react"],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"React Hooks lint rules via the JS plugin bridge for Oxlint.",id:"react-hooks",jsPlugins:[{name:"react-hooks-js",specifier:"eslint-plugin-react-hooks"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-hooks"],rules:Object.fromEntries([["react-hooks-js/exhaustive-deps","error"],["react-hooks-js/component-hook-factories","error"],["react-hooks-js/config","error"],["react-hooks-js/error-boundaries","error"],["react-hooks-js/gating","error"],["react-hooks-js/globals","error"],["react-hooks-js/immutability","error"],["react-hooks-js/incompatible-library","error"],["react-hooks-js/preserve-manual-memoization","error"],["react-hooks-js/purity","error"],["react-hooks-js/refs","error"],["react-hooks-js/rules-of-hooks","error"],["react-hooks-js/set-state-in-effect","error"],["react-hooks-js/set-state-in-render","error"],["react-hooks-js/static-components","error"],["react-hooks-js/unsupported-syntax","error"],["react-hooks-js/use-memo","error"]]),settings:{}},{description:"Guidance rules that push React code away from unnecessary effects.",id:"react-you-might-not-need-an-effect",jsPlugins:[{name:"react-you-might-not-need-an-effect-js",specifier:"eslint-plugin-react-you-might-not-need-an-effect"}],oxlintPresets:[],placement:sharedReactPlacement,plugins:[],requiredDevDependencies:["eslint-plugin-react-you-might-not-need-an-effect"],rules:{"react-you-might-not-need-an-effect-js/no-adjust-state-on-prop-change":"error","react-you-might-not-need-an-effect-js/no-chain-state-updates":"error","react-you-might-not-need-an-effect-js/no-derived-state":"error","react-you-might-not-need-an-effect-js/no-event-handler":"error","react-you-might-not-need-an-effect-js/no-initialize-state":"error","react-you-might-not-need-an-effect-js/no-pass-data-to-parent":"error","react-you-might-not-need-an-effect-js/no-pass-live-state-to-parent":"error","react-you-might-not-need-an-effect-js/no-reset-all-state-on-prop-change":"error"},settings:{}},{description:"Ultracite Next.js preset for the main web application.",id:"next-core",jsPlugins:[],oxlintPresets:["next"],placement:{...webOnlyPlacement,placementNotes:"Place this beside the React app override and set `settings.next.rootDir` to the repo's actual Next workspace roots if the final config needs that plugin setting."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Ultracite TanStack preset for query/router/start framework linting.",id:"tanstack-query-core",jsPlugins:[],oxlintPresets:["tanstack"],placement:{...webOnlyPlacement,placementNotes:"Scope this to client code that owns TanStack Query usage. Keep it out of server-only or shared non-query packages unless those paths actually create queries or mutations."},plugins:[],requiredDevDependencies:[],rules:{},settings:{}},{description:"Effect architectural rule that blocks barrel-package imports.",id:"effect-no-barrel-imports",jsPlugins:[{name:"effect-js",specifier:"@effect/eslint-plugin"}],oxlintPresets:[],placement:effectPlacement,plugins:[],requiredDevDependencies:["@effect/eslint-plugin"],rules:{"effect-js/no-import-from-barrel-package":["error",{packageNames:["effect"]}]},settings:{}},{description:"Ultracite Vitest preset for repo-owned test globs.",id:"vitest-core",jsPlugins:[],oxlintPresets:["vitest"],placement:vitestPlacement,plugins:[],requiredDevDependencies:[],rules:{},settings:{}}];var stableJson=(value5)=>JSON.stringify(value5);var placementKeyOf=(placement)=>[placement.recommendedConfigFile,...placement.recommendedFiles].join("::");var validateLintCatalog=(catalog)=>{const seenIds=new Set;const seenRules=new Map;const seenSettings=new Map;const seenJsPlugins=new Map;for(const asset of catalog){if(seenIds.has(asset.id)){throw new Error(`Duplicate lint asset id: ${asset.id}`)}seenIds.add(asset.id);const placementKey=placementKeyOf(asset.placement);for(const[ruleName,ruleValue]of Object.entries(asset.rules)){const key=`${placementKey}::rule::${ruleName}`;const value5=stableJson(ruleValue);const previous=seenRules.get(key);if(previous!==undefined&&previous.value!==value5){throw new Error(`Conflicting lint rule \`${ruleName}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenRules.set(key,{assetId:asset.id,value:value5})}}for(const[settingName,settingValue]of Object.entries(asset.settings)){const key=`${placementKey}::setting::${settingName}`;const value5=stableJson(settingValue);const previous=seenSettings.get(key);if(previous!==undefined&&previous.value!==value5){throw new Error(`Conflicting lint setting \`${settingName}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenSettings.set(key,{assetId:asset.id,value:value5})}}for(const plugin of asset.jsPlugins){const key=`${placementKey}::js-plugin::${plugin.name}`;const previous=seenJsPlugins.get(key);if(previous!==undefined&&previous.specifier!==plugin.specifier){throw new Error(`Conflicting JS plugin alias \`${plugin.name}\` for placement \`${placementKey}\`: ${previous.assetId} vs ${asset.id}`)}if(previous===undefined){seenJsPlugins.set(key,{assetId:asset.id,specifier:plugin.specifier})}}}return catalog};var skillCatalog=[{framework:"browser-automation",id:"agent-browser",language:null,requiresTools:["agent-browser"],sourceDirectory:"skills/agnostic/frontend/agent-browser",tier:"framework"},{framework:null,id:"backend-domain-structure",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/backend-domain-structure",tier:"agnostic"},{framework:null,id:"backend-recoverable-actions",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/backend-recoverable-actions",tier:"agnostic"},{framework:null,id:"logging-best-practices",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/backend/logging-best-practices",tier:"agnostic"},{framework:null,id:"audit-cicd-security",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/security/audit-cicd-security",tier:"agnostic"},{framework:null,id:"security-best-practices",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/security/security-best-practices",tier:"agnostic"},{framework:"better-auth",id:"better-auth-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/better-auth/better-auth-best-practices",tier:"framework"},{framework:"better-auth",id:"better-auth-security-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/better-auth/better-auth-security-best-practices",tier:"framework"},{framework:null,id:"create-plan",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/create-plan",tier:"agnostic"},{framework:null,id:"create-spec",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/create-spec",tier:"agnostic"},{framework:null,id:"delivery-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/delivery-phase",tier:"agnostic"},{framework:null,id:"design-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/design-phase",tier:"agnostic"},{framework:null,id:"debug-agent",language:null,requiresTools:["debug-agent"],sourceDirectory:"skills/agnostic/debug/debug-agent",tier:"agnostic"},{framework:null,id:"debugging-phase",language:null,requiresTools:["debug-agent"],sourceDirectory:"skills/phases/debugging-phase",tier:"agnostic"},{framework:null,id:"bug-discovery-phase",language:null,requiresTools:["clawpatch"],sourceDirectory:"skills/phases/bug-discovery-phase",tier:"agnostic"},{framework:null,id:"bug-resolution-phase",language:null,requiresTools:["clawpatch"],sourceDirectory:"skills/phases/bug-resolution-phase",tier:"agnostic"},{framework:null,id:"docs-ingest-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/docs-ingest-phase",tier:"agnostic"},{framework:null,id:"docs-onboarding",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/docs-onboarding",tier:"agnostic"},{framework:null,id:"writing-fragments",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-fragments",tier:"agnostic"},{framework:null,id:"writing-beats",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-beats",tier:"agnostic"},{framework:null,id:"writing-shape",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-shape",tier:"agnostic"},{framework:"effect",id:"effect-backend-structure",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/effect/effect-backend-structure",tier:"framework"},{framework:"effect",id:"effect",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/effect/effect",tier:"framework"},{framework:"effect",id:"effect-recoverable-actions",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/effect/effect-recoverable-actions",tier:"framework"},{framework:"elysiajs",id:"elysiajs",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/elysia/elysiajs",tier:"framework"},{framework:"expo",id:"add-app-clip",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/add-app-clip",tier:"framework"},{framework:"expo",id:"building-native-ui",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/building-native-ui",tier:"framework"},{framework:"expo",id:"eas-simulator",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/eas-simulator",tier:"framework"},{framework:"expo",id:"eas-update-insights",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/eas-update-insights",tier:"framework"},{framework:"expo",id:"expo-api-routes",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-api-routes",tier:"framework"},{framework:"expo",id:"expo-brownfield",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-brownfield",tier:"framework"},{framework:"expo",id:"expo-cicd-workflows",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-cicd-workflows",tier:"framework"},{framework:"expo",id:"expo-deployment",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-deployment",tier:"framework"},{framework:"expo",id:"expo-dev-client",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-dev-client",tier:"framework"},{framework:"expo",id:"expo-examples",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-examples",tier:"framework"},{framework:"expo",id:"expo-module",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-module",tier:"framework"},{framework:"expo",id:"expo-observe",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-observe",tier:"framework"},{framework:"expo",id:"expo-skill-eval",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-skill-eval",tier:"framework"},{framework:"expo",id:"expo-tailwind-setup",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-tailwind-setup",tier:"framework"},{framework:"expo",id:"expo-ui",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/expo-ui",tier:"framework"},{framework:"expo",id:"native-data-fetching",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/native-data-fetching",tier:"framework"},{framework:"expo",id:"upgrading-expo",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/upgrading-expo",tier:"framework"},{framework:"expo",id:"use-dom",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/use-dom",tier:"framework"},{framework:"expo",id:"web-to-native",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/expo/web-to-native",tier:"framework"},{framework:"pulumi",id:"pulumi-overview",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-overview",tier:"framework"},{framework:"pulumi",id:"pulumi-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-best-practices",tier:"framework"},{framework:"pulumi",id:"pulumi-component",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-component",tier:"framework"},{framework:"pulumi",id:"pulumi-automation-api",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-automation-api",tier:"framework"},{framework:"pulumi",id:"pulumi-esc",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/pulumi-esc",tier:"framework"},{framework:"pulumi",id:"provider-upgrade",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/provider-upgrade",tier:"framework"},{framework:"pulumi",id:"package-usage",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/pulumi/package-usage",tier:"framework"},{framework:null,id:"design-taste-frontend",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/design-taste-frontend",tier:"agnostic"},{framework:null,id:"imagegen-frontend-mobile",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/imagegen-frontend-mobile",tier:"agnostic"},{framework:null,id:"imagegen-frontend-web",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/imagegen-frontend-web",tier:"agnostic"},{framework:null,id:"frontend-domain-structure",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/frontend/frontend-domain-structure",tier:"agnostic"},{framework:null,id:"finder-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/finder-phase",tier:"agnostic"},{framework:null,id:"goalify",language:null,requiresTools:[],sourceDirectory:"skills/phases/goalify",tier:"agnostic"},{framework:null,id:"grilling",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/grilling",tier:"agnostic"},{framework:null,id:"handoff",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/generic/handoff",tier:"agnostic"},{framework:null,id:"improve-codebase-architecture",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/improve-codebase-architecture",tier:"agnostic"},{framework:null,id:"implement-spec",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/implement-spec",tier:"agnostic"},{framework:null,id:"repo-asset-management",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/repo-asset-management",tier:"agnostic"},{framework:null,id:"stack",language:null,requiresTools:["stack"],sourceDirectory:"skills/agnostic/planning/stack",tier:"agnostic"},{framework:null,id:"wayfinder",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/planning/wayfinder",tier:"agnostic"},{framework:"nextjs",id:"next-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/nextjs/next-best-practices",tier:"framework"},{framework:"nextjs",id:"next-cache-components",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/nextjs/next-cache-components",tier:"framework"},{framework:null,id:"parallel-research",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/parallel-research",tier:"agnostic"},{framework:null,id:"prototype",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/research/prototype",tier:"agnostic"},{framework:null,id:"async-python-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/async-python-patterns",tier:"language"},{framework:null,id:"python-code-style",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-code-style",tier:"language"},{framework:null,id:"python-design-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-design-patterns",tier:"language"},{framework:null,id:"python-project-structure",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-project-structure",tier:"language"},{framework:null,id:"python-testing-patterns",language:"python",requiresTools:[],sourceDirectory:"skills/languages/python/python-testing-patterns",tier:"language"},{framework:null,id:"quality-types",language:"typescript",requiresTools:[],sourceDirectory:"skills/languages/typescript/quality-types",tier:"language"},{framework:null,id:"codebase-design",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/codebase-design",tier:"agnostic"},{framework:"react",id:"async-react-patterns",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/async-react-patterns",tier:"framework"},{framework:"react",id:"react-doctor",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/react-doctor",tier:"framework"},{framework:null,id:"requirements-grill",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/requirements-grill",tier:"agnostic"},{framework:null,id:"requirements-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/requirements-phase",tier:"agnostic"},{framework:null,id:"resolve-debt-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/resolve-debt-phase",tier:"agnostic"},{framework:null,id:"review-phase",language:null,requiresTools:[],sourceDirectory:"skills/phases/review-phase",tier:"agnostic"},{framework:null,id:"review",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/review",tier:"agnostic"},{framework:null,id:"autoreview",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/autoreview",tier:"agnostic"},{framework:null,id:"simplify",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/simplify",tier:"agnostic"},{framework:null,id:"swarm-planner",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/subagents/swarm-planner",tier:"agnostic"},{framework:"tanstack-query",id:"tanstack-query",language:"typescript",requiresTools:["opensrc"],sourceDirectory:"skills/frameworks/tanstack-query/tanstack-query",tier:"framework"},{framework:null,id:"tdd",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/quality/tdd",tier:"agnostic"},{framework:null,id:"writing-great-skills",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/docs/writing-great-skills",tier:"agnostic"},{framework:"turborepo",id:"turborepo",language:null,requiresTools:[],sourceDirectory:"skills/frameworks/turborepo/turborepo",tier:"framework"},{framework:"react",id:"vercel-composition-patterns",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/vercel-composition-patterns",tier:"framework"},{framework:"react",id:"vercel-react-best-practices",language:"typescript",requiresTools:[],sourceDirectory:"skills/frameworks/react/vercel-react-best-practices",tier:"framework"},{framework:null,id:"write-backlog",language:null,requiresTools:[],sourceDirectory:"skills/agnostic/requirements/write-backlog",tier:"agnostic"}];var toolCatalog=[{ensureCommands:[["agent-browser","install"]],id:"agent-browser",latestInstallTarget:"agent-browser@latest",packageName:"agent-browser",requiredBins:["node"],skipEnsureCommandsIfAnyCommandExists:[{env:"AGENT_BROWSER_EXECUTABLE_PATH"},"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","google-chrome","google-chrome-stable","chromium","chromium-browser","brave-browser","brave-browser-stable","C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"]},{ensureCommands:[],id:"debug-agent",latestInstallTarget:"debug-agent@latest",packageName:"debug-agent",requiredBins:["node"]},{ensureCommands:[],id:"clawpatch",latestInstallTarget:"clawpatch@latest",packageName:"clawpatch",requiredBins:["node"]},{ensureCommands:[],id:"opensrc",latestInstallTarget:"opensrc@latest",minimumVersion:"0.7.2",packageName:"opensrc@^0.7.2",requiredBins:["node"],versionCommand:["opensrc","--version"]},{ensureCommands:[],id:"portless",latestInstallTarget:"portless@latest",packageName:"portless",requiredBins:["node"]},{ensureCommands:[],id:"skills",latestInstallTarget:"skills@latest",packageName:"skills",requiredBins:["node"]},{ensureCommands:[],id:"stack",latestInstallTarget:"@kitlangton/stack@latest",packageName:"@kitlangton/stack",requiredBins:["node"]}];var bundledNpmInstallAliasManifest=[{expectedSha256:"d1a3b15bb12948cfbd82acdd54889efc5d1263809550cb4d379863bbc1cc2f82",logicalRelativePath:"frameworks/nestjs/nestjs-best-practices/.gitignore",physicalRelativePath:"frameworks/nestjs/nestjs-best-practices/.npmignore"}];var fileSha256=(filePath)=>createHash3("sha256").update(readFileSync3(filePath)).digest("hex");var npmIgnoreFiles=(root)=>{const files=[];const visit2=(directory3)=>{for(const entry of readdirSync2(directory3,{withFileTypes:true})){const absolutePath=path6.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath)}else if(entry.isFile()&&entry.name===".npmignore"){files.push(path6.relative(root,absolutePath).split(path6.sep).join("/"))}}};visit2(root);return files};var resolveBundledSkillAliases=(root)=>{const aliases=new Map;const expectedPhysicalPaths=new Set(bundledNpmInstallAliasManifest.map(({physicalRelativePath})=>physicalRelativePath));for(const relativePath of npmIgnoreFiles(root)){if(!expectedPhysicalPaths.has(relativePath)){throw new Error(`Bundled baseline contains an unexpected npm alias: ${relativePath}`)}}for(const alias of bundledNpmInstallAliasManifest){const logicalPath=path6.join(root,alias.logicalRelativePath);const physicalPath=path6.join(root,alias.physicalRelativePath);const hasLogical=existsSync2(logicalPath);const hasPhysical=existsSync2(physicalPath);if(hasLogical&&hasPhysical){throw new Error(`Bundled baseline npm alias is ambiguous: ${alias.logicalRelativePath}`)}let resolvedPath=null;if(hasLogical){resolvedPath=logicalPath}else if(hasPhysical){resolvedPath=physicalPath}if(resolvedPath===null){throw new Error(`Bundled baseline asset is missing: ${alias.logicalRelativePath}`)}if(fileSha256(resolvedPath)!==alias.expectedSha256){throw new Error(`Bundled baseline npm alias hash mismatch: ${alias.logicalRelativePath}`)}if(hasPhysical){aliases.set(alias.physicalRelativePath,alias.logicalRelativePath)}}return aliases};var logicalBundledSkillRelativePath=(relativePath)=>bundledNpmInstallAliasManifest.find(({physicalRelativePath})=>physicalRelativePath===relativePath)?.logicalRelativePath??relativePath;var materializeBundledSkillDirectoryAliases=({sourceDirectory,sourceSkillsRoot,targetDirectory})=>{for(const alias of bundledNpmInstallAliasManifest){const sourcePhysicalPath=path6.join(sourceSkillsRoot,alias.physicalRelativePath);if(!existsSync2(sourcePhysicalPath)){continue}const relativePhysicalPath=path6.relative(sourceDirectory,sourcePhysicalPath);if(relativePhysicalPath===".."||relativePhysicalPath.startsWith(`..${path6.sep}`)){continue}const physicalPath=path6.join(targetDirectory,relativePhysicalPath);if(!existsSync2(physicalPath)){continue}const logicalPath=path6.join(targetDirectory,path6.relative(sourceDirectory,path6.join(sourceSkillsRoot,alias.logicalRelativePath)));if(existsSync2(logicalPath)){throw new Error(`Bundled baseline npm alias is ambiguous: ${alias.logicalRelativePath}`)}renameSync(physicalPath,logicalPath)}};var bundledBaseline={dataRoot,hooks:hookCatalog,lintAssets:validateLintCatalog(lintCatalog),packs:packCatalog,root:path6.dirname(dataRoot),skills:skillCatalog,skillsRoot,summary:{authoritySource:"bundled",channel:"bundled",commit:null,compatibility:{cliVersionRange:`=${version2}`},digest:bundledBaselineDigest,provenance:"packaged-cli",requested:{channel:"bundled"},resolvedVersion:version2,retrieval:"available",sha256:bundledBaselineDigest,source:"bundled",tag:null,version:version2},tools:toolCatalog};var resolveVerifiedBundledBaseline=(requested=bundledBaseline.summary.requested,retrieval="available")=>{const aliases=resolveBundledSkillAliases(skillsRoot);const actualDigest=digestContentRoots([{include:(relativePath)=>!relativePath.endsWith(".ts"),prefix:"data",root:dataRoot},{logicalPath:(relativePath)=>aliases.get(relativePath)??relativePath,prefix:"skills",root:skillsRoot}]);if(actualDigest!==bundledBaselineDigest){throw new BaselineIntegrityFailure({actualDigest,expectedDigest:bundledBaselineDigest,message:"Packaged baseline content no longer matches its verified identity.",request:requested,resolvedVersion:bundledBaseline.summary.resolvedVersion})}return{...bundledBaseline,summary:{...bundledBaseline.summary,channel:requested.channel,requested,retrieval}}};var packContents=packCatalog;var packContentsForBaseline=(baseline=bundledBaseline)=>baseline.packs;var packContentsByIdForBaseline=(baseline=bundledBaseline)=>{const contents={};for(const pack of packContentsForBaseline(baseline)){contents[pack.id]=pack}return contents};var packContentsById=packContentsByIdForBaseline();var defaultPackIds=packContents.filter((pack)=>pack.category==="default").map((pack)=>pack.id).toSorted();var languagePackIds=packContents.filter((pack)=>pack.category==="language").map((pack)=>pack.id).toSorted();var detectedPackIds=packContents.filter((pack)=>pack.category==="detected").map((pack)=>pack.id).toSorted();var surfacePackIds=packContents.filter((pack)=>pack.category==="surface").map((pack)=>pack.id).toSorted();var knownPackIds=packContents.map((pack)=>pack.id).toSorted();var defaultPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="default").map((pack)=>pack.id).toSorted();var languagePackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="language").map((pack)=>pack.id).toSorted();var detectedPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="detected").map((pack)=>pack.id).toSorted();var surfacePackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).filter((pack)=>pack.category==="surface").map((pack)=>pack.id).toSorted();var knownPackIdsForBaseline=(baseline=bundledBaseline)=>packContentsForBaseline(baseline).map((pack)=>pack.id).toSorted();var skillsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.skills??[];var lintAssetsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.lintAssets??[];var hooksForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.hooks??[];var promptDetailsForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.promptDetails??[];var exampleRepositoriesForPack=(packId,baseline=bundledBaseline)=>packContentsByIdForBaseline(baseline)[packId]?.exampleRepositories??[];var formatToolBootstrapStatus=(entry)=>{switch(entry.status){case"already-present":{return"already present"}case"installed":{return"installed during scaffold"}case"failed":{return"bootstrap failed"}default:{return entry.status}}};var formatToolBootstrapFailureDetails=(statuses)=>{const failures=statuses.filter((entry)=>entry.status==="failed");if(failures.length===0){return null}return["Required tool bootstrap failed, but scaffold/update output can still be written.","","Agent recovery prompt:","Read `.devpunks/settings.json`, verify each listed required tool manually, then fix the failed install before deeper repo work. If `agent-browser` failed while installing Chromium, install or repair that browser dependency outside the scaffold command, then rerun `agent-browser install` or the documented tool check.","","Failure stack traces:",...failures.flatMap((failure)=>["",`--- ${failure.toolId} ---`,failure.errorStack??failure.errorMessage??"Unknown tool bootstrap failure."])].join(`
326
326
  `)};var formatList=(values3)=>values3.length===0?[" ∅"]:values3.map((value5)=>` • ${value5}`);var wrapInlineValues=({values:values3,firstPrefix,continuationPrefix,maxLineLength=88})=>{if(values3.length===0){return[`${firstPrefix}∅`]}const lines2=[];let currentLine=firstPrefix;for(const value5 of values3){const candidate=currentLine===firstPrefix?`${currentLine}${value5}`:`${currentLine}, ${value5}`;if(candidate.length<=maxLineLength||currentLine===firstPrefix){currentLine=candidate;continue}lines2.push(currentLine);currentLine=`${continuationPrefix}${value5}`}lines2.push(currentLine);return lines2};var formatPackRows=({label,values:values3,isLast})=>wrapInlineValues({continuationPrefix:`${isLast?" ":" │ "}${" ".repeat(`${label}: `.length)}`,firstPrefix:` ${isLast?"└":"├"} ${label}: `,values:values3});var formatPackList=(values3,baseline=bundledBaseline)=>values3.length===0?[" ∅"]:values3.flatMap((packId)=>{const skills=skillsForPack(packId,baseline);const lintAssets=lintAssetsForPack(packId,baseline);const hooks=hooksForPack(packId,baseline);const detailRows=[...skills.length===0?[]:[{label:"skills",values:skills}],...lintAssets.length===0?[]:[{label:"lint",values:lintAssets}],...hooks.length===0?[]:[{label:"hooks",values:hooks}],...(()=>{const promptLabels=promptDetailsForPack(packId,baseline);return promptLabels.length===0?[]:[{label:"prompts",values:promptLabels}]})()];return[` • ${packId}`,...detailRows.flatMap((row,index2)=>formatPackRows({isLast:index2===detailRows.length-1,label:row.label,values:row.values}))]});var formatCompactPackList=(values3)=>values3.length===0?[" ∅"]:wrapInlineValues({continuationPrefix:" ",firstPrefix:" • ",values:values3});var section=(title,lines2)=>[title,...lines2];var maybeSection=(title,lines2)=>lines2.length===1&&lines2[0]===" ∅"?[]:section(title,lines2);var formatDetectionSummary=(detection)=>["Scaffold detection summary",`cwd: ${detection.cwd}`,...section("detected languages:",formatList(detection.detectedLanguages)),...section("detected technologies:",formatList(detection.detectedTechnologies)),...section("manifest files:",formatList(detection.manifests.map((manifest)=>path7.relative(detection.cwd,manifest.path)||"package.json"))),...section("monorepo signals:",formatList(detection.monorepoSignals.map((signal)=>`${signal.type} (${path7.relative(detection.cwd,signal.path)||"."})`)))].join(`
327
327
  `);var formatConfirmationSummary=(result4,baseline=bundledBaseline)=>["Confirmed scaffold selection",`baseline: ${result4.baseline.source}/${result4.baseline.channel} ${result4.baseline.version}`,`cwd: ${result4.cwd}`,`repo shape mode: ${result4.repoShapeMode}`,`effective repo shape: ${result4.monorepo?"monorepo":"single"}`,...section("detected languages:",formatList(result4.detectedLanguages)),...section("detected technologies:",formatList(result4.detectedTechnologies)),...section("default packs:",formatPackList(result4.defaultPacks,baseline)),...section("language packs:",formatPackList(result4.languagePacks,baseline)),...section("detected packs:",formatPackList(result4.detectedPacks,baseline)),...section("surface packs:",formatPackList(result4.surfacePacks,baseline)),...maybeSection("added packs:",formatPackList(result4.addedPacks,baseline)),...maybeSection("removed packs:",formatPackList(result4.removedPacks,baseline)),...section("final packs:",formatCompactPackList(result4.finalPacks)),`output directory: ${result4.outputDirectory}`,...section("shared core files:",formatList(result4.promptOutputs)),...section("lint spec files:",formatList(result4.lintSpecFiles)),...section("source guide files:",formatList(result4.sourceGuideFiles)),...section("skill files:",formatList(result4.skillFiles)),...section("prompt spec files:",formatList(result4.promptSpecFiles)),...section("subagent scaffold files:",formatList(result4.subagentFiles)),...section("script files:",formatList(result4.scriptFiles)),...section("hook files:",formatList(result4.hookFiles)),...section("harness files:",formatList(result4.harnessFiles)),...maybeSection("hidden output directories:",formatList(result4.hiddenOutputDirectories)),...section("agent handoff file:",formatList([result4.agentHandoffFile])),...section("required tools source:",formatList([".devpunks/settings.json"])),...maybeSection("tool bootstrap:",formatList(result4.toolBootstrapStatuses.map((entry)=>`${entry.toolId}: ${formatToolBootstrapStatus(entry)}`))),...section("scaffold manifest:",formatList([result4.scaffoldManifestFile]))].join(`
328
328
  `);var formatAgentHandoffSummary=(result4)=>["Give this to the next agent","","You are continuing a `hi scaffold` run.","","Read first:",` • \`${result4.scaffoldManifestFile}\``,` • \`${result4.agentHandoffFile}\``," • `.devpunks/settings.json`","",...result4.toolBootstrapStatuses.length===0?[]:["Tool bootstrap status:",...result4.toolBootstrapStatuses.map((entry)=>` • \`${entry.toolId}\`: ${formatToolBootstrapStatus(entry)}`),""],...result4.toolBootstrapStatuses.some((entry)=>entry.status==="failed")?["Tool bootstrap recovery:"," • Read `.devpunks/settings.json` and manually verify every listed required tool before deeper repo work."," • Repair failed installs outside the scaffold command. For `agent-browser` Chromium failures, rerun `agent-browser install` after fixing the local browser dependency.",""]:[],"What was scaffolded:"," • final scoped/root prompt files were not written yet",...formatList([...result4.promptOutputs,...result4.lintSpecFiles,...result4.sourceGuideFiles,...result4.skillFiles,...result4.promptSpecFiles,...result4.subagentFiles,...result4.scriptFiles,...result4.hookFiles,...result4.harnessFiles]),"","What you must do:"," 1. Treat the prompt spec markdown files as instructions, not final prompt bodies.",result4.monorepo?" 2. Repo is in monorepo mode. Generate final prompt files for root, docs, and each relevant app/package scope.":" 2. Repo is in single-repo mode. Stitch scoped guidance into one root prompt, plus docs guidance when present."," 3. Read `.devpunks/settings.json` and verify listed required tools such as `skills`, `portless`, `opensrc`, and `agent-browser` are actually available. If any are missing, install/fix that first."," 4. Use the root prompt spec criteria to author root `AGENTS.md` from real repo evidence: surface map, workflow routing, cross-surface contract rules, validation routing, then short source/URL/docs rules. Do not add a root `Primary skills here` line."," 4a. Author scoped `AGENTS.md` files with `Primary skills here` lines for local defaults only. Never put phase skills in scoped primary-skill lines; keep them as global orchestration entrypoints."," 5. Treat every authored root/docs/workspace `AGENTS.md` file as the neutral scoped prompt source and create a sibling `CLAUDE.md` symlink mirror beside each one."," 6. Keep `.agents/AGENTS.md` as the shared global prompt source behind the scoped prompt tree; `.claude/CLAUDE.md` should mirror that neutral file."," 7. Before relying on subagents, verify the active harness global/project settings enable subagent execution, then verify `.agents/subagents/manifest.mjs` and selected specialist path/guidance/skill coverage. Repair settings/setup or execute locally if the guard fails."," 8. Keep `.agents/hooks/` as the neutral hook source, `.agents/skills/` as the main skill directory, and `.agents/scripts/sync-subagents.mjs` as the harness sync entrypoint. Only `.claude/skills` should mirror `.agents/skills`."," 9. Reconcile `.agents/subagents/manifest.mjs` with both `.agents/subagents/manifest.prompt.md` and `.devpunks/specs/subagents/manifest-spec.json`."," 10. Update owned paths / guidance file references in the subagent manifest to match the real repo shape."," 11. Use `portless` as the local-dev URL baseline. Prefer stable subdomains over raw `localhost:<port>` values in env examples, endpoint defaults, callback URLs, allowed origins, CORS, and app-to-app proxies."," 12. If adopting Oxlint or Oxfmt, replace existing lint/format setup deliberately: package scripts, task pipelines, CI, editor/docs references, and hooks should agree on the new tools."," 13. Before authoring final prompts or implementation plans, identify the core detected libraries whose source behavior matters."," 14. If an `opensrc/<package>.md` guide exists for a package, read that card first, then run its `opensrc path --cwd . <package>` command or fallback repository lookup."," 15. Inspect the returned checkout paths. Clone the major framework/runtime libraries you will reason about; do not clone every dependency mechanically."].join(`
@@ -340,9 +340,9 @@ ${colorRail2({environment,headingTone:"accent",rail:reflowRail(guide,environment
340
340
  `))]}case"Json":{return[encodePrettyJson(publicUpdateResult(event.result))]}}};var makeUpdateInteraction=(prompt)=>({confirmApply:()=>map7(prompt.readLine(renderQuestion("Apply managed scaffold updates? [Y/n]: ")),(answer)=>{const normalized=answer.trim().toLowerCase();return normalized===""||normalized==="y"||normalized==="yes"}),emit:(event)=>forEach2(renderUpdateEvent(event),prompt.writeLine,{discard:true})});var updateInteractionLayer=effect(UpdateInteraction,map7(CliPrompt,makeUpdateInteraction));var publicCheckResult=(result4)=>{const{facts:_facts,...operation}=result4.operation;return{...result4,operation,update:publicUpdateResult(result4.update)}};var commandOutputModes=["interactive","plain","json"];var commandInteractionRequirements=["none","optional","required"];var metadataKeys=new Set(["path","name","group","summary","options","examples","interaction","outputModes"]);var optionKeys=new Set(["name","summary"]);var exampleKeys=new Set(["command","summary"]);class CommandMetadataError extends Error{_tag="CommandMetadataError";constructor(message){super(message);this.name="CommandMetadataError"}}var isRecord3=(value5)=>typeof value5==="object"&&value5!==null&&!Array.isArray(value5);var assertString=(value5,label)=>{if(typeof value5!=="string"||value5.trim()===""){throw new CommandMetadataError(`${label} must be a non-empty string.`)}};var assertAllowedKeys=(value5,keys3,label)=>{for(const key of Object.keys(value5)){if(!keys3.has(key)){throw new CommandMetadataError(`${label} contains unsupported behavior or metadata key '${key}'.`)}}};var validateOption=(value5,index2)=>{if(!isRecord3(value5)){throw new CommandMetadataError(`Command option ${index2} must be an object.`)}assertAllowedKeys(value5,optionKeys,`Command option ${index2}`);assertString(value5.name,`Command option ${index2}.name`);assertString(value5.summary,`Command option ${index2}.summary`);return{name:value5.name,summary:value5.summary}};var validateExample=(value5,index2)=>{if(!isRecord3(value5)){throw new CommandMetadataError(`Command example ${index2} must be an object.`)}assertAllowedKeys(value5,exampleKeys,`Command example ${index2}`);assertString(value5.command,`Command example ${index2}.command`);assertString(value5.summary,`Command example ${index2}.summary`);return{command:value5.command,summary:value5.summary}};var validateEntry=(value5,index2)=>{if(!isRecord3(value5)){throw new CommandMetadataError(`Command metadata entry ${index2} must be an object.`)}assertAllowedKeys(value5,metadataKeys,`Command metadata entry ${index2}`);if(!Array.isArray(value5.path)||value5.path.length===0){throw new CommandMetadataError(`Command metadata entry ${index2}.path must not be empty.`)}for(const[segmentIndex,segment]of value5.path.entries()){assertString(segment,`Command metadata entry ${index2}.path[${segmentIndex}]`);if(/^[-_]/u.test(segment)||/\s/u.test(segment)){throw new CommandMetadataError(`Command metadata entry ${index2}.path contains an invalid segment.`)}}assertString(value5.name,`Command metadata entry ${index2}.name`);if(value5.name!==value5.path.at(-1)){throw new CommandMetadataError(`Command metadata entry ${index2}.name must match the final path segment.`)}assertString(value5.group,`Command metadata entry ${index2}.group`);assertString(value5.summary,`Command metadata entry ${index2}.summary`);if(!Array.isArray(value5.options)){throw new CommandMetadataError(`Command metadata entry ${index2}.options must be an array.`)}if(!Array.isArray(value5.examples)){throw new CommandMetadataError(`Command metadata entry ${index2}.examples must be an array.`)}if(!commandInteractionRequirements.includes(value5.interaction)){throw new CommandMetadataError(`Command metadata entry ${index2}.interaction is invalid.`)}if(!Array.isArray(value5.outputModes)||value5.outputModes.length===0){throw new CommandMetadataError(`Command metadata entry ${index2}.outputModes must not be empty.`)}const outputModes=value5.outputModes.map((mode,modeIndex)=>{if(!commandOutputModes.includes(mode)){throw new CommandMetadataError(`Command metadata entry ${index2}.outputModes[${modeIndex}] is invalid.`)}return mode});if(new Set(outputModes).size!==outputModes.length){throw new CommandMetadataError(`Command metadata entry ${index2} has duplicate output modes.`)}const options4=value5.options.map(validateOption);if(new Set(options4.map((option6)=>option6.name)).size!==options4.length){throw new CommandMetadataError(`Command metadata entry ${index2} has duplicate option names.`)}return{examples:value5.examples.map(validateExample),group:value5.group,interaction:value5.interaction,name:value5.name,options:options4,outputModes,path:[...value5.path],summary:value5.summary}};var createCommandMetadataRegistry=(entries3)=>{const validated=entries3.map(validateEntry);const paths=new Set;for(const entry of validated){const key=entry.path.join(" ");if(paths.has(key)){throw new CommandMetadataError(`Duplicate command path '${key}'.`)}paths.add(key)}for(const entry of validated){for(let depth=1;depth<entry.path.length;depth+=1){const parent=entry.path.slice(0,depth).join(" ");if(!paths.has(parent)){throw new CommandMetadataError(`Command '${entry.path.join(" ")}' has missing parent '${parent}'.`)}}}return validated.toSorted((left,right)=>left.path.join(" ").localeCompare(right.path.join(" "),"en",{numeric:false}))};var declareCommandMetadata=(declaration)=>declaration;var commandMetadataFromDeclaration=(path8,declaration)=>({...declaration,path:path8});var optionMetadata=(declaration,name2)=>{const option6=declaration.options.find((candidate)=>candidate.name===name2);if(option6===undefined){throw new Error(`Command metadata for '${declaration.name}' does not declare '--${name2}'.`)}return option6};var metadataOptionName=(declaration,name2)=>optionMetadata(declaration,name2).name;var withOptionMetadata=(declaration,name2)=>(flag)=>exports_Flag.withDescription(flag,optionMetadata(declaration,name2).summary);var withCommandMetadata=(declaration)=>(command)=>command.pipe(exports_Command.withDescription(declaration.summary),exports_Command.withExamples(declaration.examples.map(({command:exampleCommand,summary})=>({command:exampleCommand,description:summary}))));var checkCommandMetadata=declareCommandMetadata({examples:[{command:"hi check",summary:"Check the current repository."}],group:"commands",interaction:"none",name:"check",options:[{name:"input",summary:"Scaffolded repository root check. Defaults current working directory."},{name:"json",summary:"Print machine-readable check result."},{name:"baseline",summary:"Scaffold baseline to use: stable, bundled, or an exact version. Defaults to stable."},{name:"refresh-baseline",summary:"Retained for compatibility; check already refreshes remote baseline metadata and bytes."}],outputModes:["interactive","plain","json"],summary:"Check managed scaffold, baseline, and CLI drift without writing files."});var inputOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(checkCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(checkCommandMetadata,"input")));var jsonOption=exports_Flag.boolean(metadataOptionName(checkCommandMetadata,"json")).pipe(exports_Flag.withDefault(false),withOptionMetadata(checkCommandMetadata,"json"));var baselineOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(checkCommandMetadata,"baseline")).pipe(withOptionMetadata(checkCommandMetadata,"baseline")));var refreshBaselineOption=exports_Flag.boolean(metadataOptionName(checkCommandMetadata,"refresh-baseline")).pipe(exports_Flag.withDefault(false),withOptionMetadata(checkCommandMetadata,"refresh-baseline"));var executeCheckCommand=(input2,operation=runRepositoryCheckApplication)=>scoped2(gen2(function*executeCheck(){const result4=yield*operation(input2);return input2.json?{jsonPayload:publicCheckResult(result4),operation:result4.operation}:{operation:result4.operation}}));var makeCheckCommand=(operation=runRepositoryCheckApplication)=>exports_Command.make(checkCommandMetadata.name,{baseline:baselineOption,input:inputOption,json:jsonOption,refreshBaseline:refreshBaselineOption},({input:input2,json:json3,baseline,refreshBaseline})=>gen2(function*runCheckCommand(){const selectedOutputMode=yield*SelectedOutputMode;return yield*captureCommandResult(executeCheckCommand({baseline:getOrUndefined(baseline),changelogRoots:[process.cwd(),path8.resolve(import.meta.dirname,".."),path8.resolve(import.meta.dirname,"../.."),path8.resolve(import.meta.dirname,"../../.."),path8.resolve(import.meta.dirname,"../../../..")],json:json3||selectedOutputMode==="json",refreshBaseline,rootDirectory:path8.resolve(process.cwd(),getOrElse(input2,()=>"."))},operation))})).pipe(withCommandMetadata(checkCommandMetadata));var checkCommand=makeCheckCommand();class ProjectSettingsAccessFailure extends TaggedErrorClass()("@punks/cli/project-settings/ProjectSettingsAccessFailure",{cause:Defect(),message:String5,operation:Literals(["read","write"]),path:String5}){}class ProjectSettingsAlreadyExists extends TaggedErrorClass()("ProjectSettingsAlreadyExists",{message:String5,path:String5}){}var RepositoryManager=Literals(["azure-devops","bitbucket","github","gitlab"]);var BacklogProvider=Literals(["azure-devops","github","linear","monday"]);var AssetProvider=Union2([BacklogProvider,RepositoryManager]);var ProjectSettingsDocument=Struct({assetProviderSlug:optional(AssetProvider),backlogProjectUrl:optional(String5),backlogProvider:optional(BacklogProvider),baselineVersion:optional(String5),cliVersion:optional(String5),repositoryManager:optional(RepositoryManager),requiredTools:optional(ArraySchema(String5))});var repositoryManagerTools={"azure-devops":["az"],bitbucket:[],github:["gh"],gitlab:["glab"]};var requiredToolsForRepositoryManager=(repositoryManager)=>repositoryManagerTools[repositoryManager];var deriveRequiredTools=({repositoryManager,requiredTools})=>[...new Set([...requiredTools,...requiredToolsForRepositoryManager(repositoryManager)])].toSorted();class AmbiguousSettingsUpgrade extends TaggedErrorClass()("AmbiguousSettingsUpgrade",{message:String5,path:String5,providers:ArraySchema(AssetProvider)}){}class InvalidProjectSettings extends TaggedErrorClass()("InvalidProjectSettings",{cause:optional(Unknown2),message:String5,path:String5}){}class ProjectSettingsMissing extends TaggedErrorClass()("ProjectSettingsMissing",{message:String5,path:String5}){}var projectSettingsFile=".devpunks/settings.json";var ProjectSettingsFileSystem=Service("@punks/cli/ProjectSettingsFileSystem");var wikiRoots=["apps/wiki","app/wiki","wiki","."];var backlogProviders=BacklogProvider.literals;var repositoryManagers=RepositoryManager.literals;var parseSettings=fn2("ProjectSettings.parseSettings")(function*parseSettings2(settingsPath,content){const parsed=yield*try_3({catch:(cause)=>new InvalidProjectSettings({cause,message:`Invalid JSON in ${settingsPath}.`,path:settingsPath}),try:()=>JSON.parse(content)});const decoded=decodeUnknownResult2(ProjectSettingsDocument)(parsed);if(isFailure2(decoded)){return yield*new InvalidProjectSettings({cause:decoded.failure,message:`Invalid project settings in ${settingsPath}.`,path:settingsPath})}return{document:decoded.success,raw:parsed}});var providerHints=fn2("ProjectSettings.providerHints")(function*providerHints2(fileSystem,rootDirectory){const contents=yield*all2(wikiRoots.map((wikiRoot)=>fileSystem.readTextFile(fileSystem.joinPath(rootDirectory,wikiRoot,"backlog-provider.md"))));return[...new Set(contents.flatMap((content)=>match(content,{onNone:()=>[],onSome:(value5)=>backlogProviders.filter((provider)=>value5.includes(`\`${provider}\``))})))].toSorted()});var repositoryManagerHintsFromGitConfig=fn2("ProjectSettings.repositoryManagerHintsFromGitConfig")(function*repositoryManagerHintsFromGitConfig2(fileSystem,rootDirectory){const config=yield*fileSystem.readRepositoryGitConfig(rootDirectory);return match(config,{onNone:()=>[],onSome:(content)=>repositoryManagers.filter((repositoryManager)=>value4(repositoryManager).pipe(when4("azure-devops",()=>["dev.azure.com","visualstudio.com"].some((host)=>content.includes(host))),when4("bitbucket",()=>content.includes("bitbucket.org")),when4("github",()=>content.includes("github.com")),when4("gitlab",()=>content.includes("gitlab.com")),exhaustive2)).toSorted()})});var readProjectSettings=fn2("ProjectSettings.read")(function*readProjectSettings2(fileSystem,rootDirectory){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const content=yield*fileSystem.readTextFile(settingsPath);if(isNone2(content)){return yield*new ProjectSettingsMissing({message:`Project settings are missing at ${settingsPath}.`,path:settingsPath})}const{document}=yield*parseSettings(settingsPath,content.value);const backlogProviderOption=fromNullishOr(document.backlogProvider);const repositoryManagerOption=fromNullishOr(document.repositoryManager);const hints=isNone2(backlogProviderOption)?yield*providerHints(fileSystem,rootDirectory):[];if(hints.length>1){return yield*new AmbiguousSettingsUpgrade({message:`Conflicting legacy backlog provider hints found: ${hints.join(", ")}.`,path:settingsPath,providers:hints})}const backlogProvider=getOrElse(backlogProviderOption,()=>hints[0]);if(backlogProvider===undefined){return yield*new InvalidProjectSettings({message:`Project settings do not identify a backlog provider.`,path:settingsPath})}const repositoryManagerHints=isNone2(repositoryManagerOption)?yield*repositoryManagerHintsFromGitConfig(fileSystem,rootDirectory):[];if(repositoryManagerHints.length>1){return yield*new AmbiguousSettingsUpgrade({message:`Conflicting legacy repository manager hints found: ${repositoryManagerHints.join(", ")}.`,path:settingsPath,providers:repositoryManagerHints})}const repositoryManager=getOrElse(repositoryManagerOption,()=>repositoryManagerHints[0]);if(repositoryManager===undefined){return yield*new AmbiguousSettingsUpgrade({message:`Legacy project settings do not identify a repository manager for ${backlogProvider}.`,path:settingsPath,providers:[]})}const settings={assetProviderSlug:document.assetProviderSlug??backlogProvider,backlogProvider,...document.backlogProjectUrl===undefined?{}:{backlogProjectUrl:document.backlogProjectUrl},...document.baselineVersion===undefined?{}:{baselineVersion:document.baselineVersion},...document.cliVersion===undefined?{}:{cliVersion:document.cliVersion},repositoryManager,requiredTools:deriveRequiredTools({repositoryManager,requiredTools:document.requiredTools??[]})};const upgradedFields=["assetProviderSlug","backlogProvider","repositoryManager"].filter((field)=>document[field]===undefined);const requiredToolsNeedUpgrade=document.requiredTools===undefined||document.requiredTools.length!==settings.requiredTools.length||document.requiredTools.some((tool,index2)=>tool!==settings.requiredTools[index2]);const safeUpgradeFields=requiredToolsNeedUpgrade?[...upgradedFields,"requiredTools"]:upgradedFields;return{settings,upgrade:safeUpgradeFields.length===0?{_tag:"CurrentSettings"}:{_tag:"SafeSettingsUpgrade",fields:safeUpgradeFields}}});var inferProjectSettings=fn2("ProjectSettings.infer")(function*inferProjectSettings2(fileSystem,rootDirectory){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const backlogProviderHints=yield*providerHints(fileSystem,rootDirectory);if(backlogProviderHints.length>1){return yield*new AmbiguousSettingsUpgrade({message:`Conflicting legacy backlog provider hints found: ${backlogProviderHints.join(", ")}.`,path:settingsPath,providers:backlogProviderHints})}const[backlogProvider]=backlogProviderHints;if(backlogProvider===undefined){return none2()}const repositoryManagerHints=yield*repositoryManagerHintsFromGitConfig(fileSystem,rootDirectory);if(repositoryManagerHints.length>1){return yield*new AmbiguousSettingsUpgrade({message:`Conflicting legacy repository manager hints found: ${repositoryManagerHints.join(", ")}.`,path:settingsPath,providers:repositoryManagerHints})}const repositoryManager=repositoryManagerHints[0]??(backlogProvider==="github"||backlogProvider==="azure-devops"?backlogProvider:undefined);if(repositoryManager===undefined){return none2()}return some2({assetProviderSlug:backlogProvider,backlogProvider,repositoryManager,requiredTools:deriveRequiredTools({repositoryManager,requiredTools:[]})})});var writeProjectSettings=fn2("ProjectSettings.write")(function*writeProjectSettings2(fileSystem,rootDirectory,change){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const content=yield*fileSystem.readTextFile(settingsPath);if(isNone2(content)){return yield*new ProjectSettingsMissing({message:`Project settings are missing at ${settingsPath}.`,path:settingsPath})}const{document,raw:raw2}=yield*parseSettings(settingsPath,content.value);const next={...raw2};if(change._tag==="ReconfigurationChange"){const requiredTools=deriveRequiredTools({repositoryManager:change.repositoryManager,requiredTools:change.requiredTools});next.assetProviderSlug=change.assetProviderSlug;next.backlogProvider=change.backlogProvider;next.repositoryManager=change.repositoryManager;next.requiredTools=requiredTools;if(change.backlogProjectUrl===undefined){delete next.backlogProjectUrl}else{next.backlogProjectUrl=change.backlogProjectUrl}yield*fileSystem.writeTextFile(settingsPath,`${JSON.stringify(next,null,2)}
341
341
  `);return{settings:{assetProviderSlug:change.assetProviderSlug,backlogProvider:change.backlogProvider,...change.backlogProjectUrl===undefined?{}:{backlogProjectUrl:change.backlogProjectUrl},...document.baselineVersion===undefined?{}:{baselineVersion:document.baselineVersion},...document.cliVersion===undefined?{}:{cliVersion:document.cliVersion},repositoryManager:change.repositoryManager,requiredTools},upgrade:{_tag:"CurrentSettings"}}}yield*value4(change).pipe(tag3("UserChoicesChange",(choices)=>sync2(()=>{next.assetProviderSlug=choices.assetProviderSlug;next.backlogProvider=choices.backlogProvider;next.repositoryManager=choices.repositoryManager;if(choices.backlogProjectUrl===undefined){delete next.backlogProjectUrl}else{next.backlogProjectUrl=choices.backlogProjectUrl}})),tag3("CalculatedToolsChange",({requiredTools})=>gen2(function*applyCalculatedToolsChange(){const current=yield*readProjectSettings(fileSystem,rootDirectory);next.requiredTools=deriveRequiredTools({repositoryManager:current.settings.repositoryManager,requiredTools})})),tag3("ManagedVersionsChange",({baselineVersion,cliVersion})=>gen2(function*applyManagedVersionsChange(){yield*readProjectSettings(fileSystem,rootDirectory);next.baselineVersion=baselineVersion;next.cliVersion=cliVersion})),tag3("ScaffoldChange",({baselineVersion,cliVersion,requiredTools})=>gen2(function*applyScaffoldChange(){const current=yield*readProjectSettings(fileSystem,rootDirectory);next.baselineVersion=baselineVersion;next.cliVersion=cliVersion;next.requiredTools=deriveRequiredTools({repositoryManager:current.settings.repositoryManager,requiredTools})})),exhaustive2);yield*fileSystem.writeTextFile(settingsPath,`${JSON.stringify(next,null,2)}
342
342
  `);return yield*readProjectSettings(fileSystem,rootDirectory)});var projectSettingsInitializationContent=(initialization)=>{const{calculatedTools,managedVersions,userChoices}=initialization;const settings={...userChoices,...managedVersions,requiredTools:deriveRequiredTools({repositoryManager:userChoices.repositoryManager,requiredTools:calculatedTools.requiredTools})};return`${JSON.stringify(settings,null,2)}
343
- `};var initializeProjectSettings=fn2("ProjectSettings.initialize")(function*initializeProjectSettings2(fileSystem,rootDirectory,initialization){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const settingsDirectory=fileSystem.joinPath(rootDirectory,".devpunks");const settingsDirectoryExisted=yield*fileSystem.directoryExists(settingsDirectory);const expectedContent=projectSettingsInitializationContent(initialization);const created=yield*fileSystem.createTextFile(settingsPath,expectedContent);if(!created){return yield*new ProjectSettingsAlreadyExists({message:`Project settings already exist at ${settingsPath}.`,path:settingsPath})}const read3=yield*readProjectSettings(fileSystem,rootDirectory).pipe(result2);if(isSuccess2(read3)){return read3.success}yield*gen2(function*rollbackProjectSettingsInitialization(){yield*fileSystem.removeTextFileIfContent(settingsPath,expectedContent);if(!settingsDirectoryExisted){yield*fileSystem.removeEmptyDirectory(settingsDirectory)}}).pipe(result2);return yield*read3.failure});var rollbackProjectSettingsInitialization=fn2("ProjectSettings.rollbackInitialization")(function*rollbackProjectSettingsInitialization2(fileSystem,rootDirectory,rollback){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const settingsDirectory=fileSystem.joinPath(rootDirectory,".devpunks");const removed=yield*fileSystem.removeTextFileIfContent(settingsPath,projectSettingsInitializationContent(rollback.initialization));if(rollback.removeSettingsDirectory){yield*fileSystem.removeEmptyDirectory(settingsDirectory)}return removed});var ProjectSettings=Service("@punks/cli/ProjectSettings");var ProjectSettingsDefault=effect(ProjectSettings,gen2(function*ProjectSettingsDefault2(){const fileSystem=yield*ProjectSettingsFileSystem;return{infer:(rootDirectory)=>inferProjectSettings(fileSystem,rootDirectory),initialize:(rootDirectory,initialization)=>initializeProjectSettings(fileSystem,rootDirectory,initialization),read:(rootDirectory)=>readProjectSettings(fileSystem,rootDirectory),rollbackInitialization:(rootDirectory,rollback)=>rollbackProjectSettingsInitialization(fileSystem,rootDirectory,rollback),write:(rootDirectory,change)=>writeProjectSettings(fileSystem,rootDirectory,change)}}));import{execFileSync}from"node:child_process";import{accessSync,constants as constants2,existsSync as existsSync3,mkdirSync as mkdirSync2,readFileSync as readFileSync4,writeFileSync as writeFileSync2}from"node:fs";import{homedir}from"node:os";import path9 from"node:path";class ToolManagementFailure extends TaggedErrorClass()("@punks/cli/integrations/tool-management/ToolManagementFailure",{cause:Defect(),message:String5,operation:Literals(["ensure-required-tool","infer-repo-settings"])}){}var toolManagementFailure=(operation,message)=>new ToolManagementFailure({cause:new Error(message),message,operation});var repoSettingsFile=".devpunks/settings.json";var repositoryManagerTools2={"azure-devops":["az"],bitbucket:[],github:["gh"],gitlab:["glab"]};var repositoryManagers2=new Set(Object.keys(repositoryManagerTools2));var backlogProviders2=new Set(["azure-devops","github","linear","monday"]);var assetProviders=new Set([...backlogProviders2,...repositoryManagers2]);var requiredToolsForRepositoryManager2=(repositoryManager)=>repositoryManagerTools2[repositoryManager];var reconcileRepositoryManagerTools=({previousRepositoryManager,requiredTools,repositoryManager})=>{const previousManagerTools=new Set(requiredToolsForRepositoryManager2(previousRepositoryManager));return[...new Set([...requiredTools.filter((tool)=>!previousManagerTools.has(tool)),...requiredToolsForRepositoryManager2(repositoryManager)])].toSorted()};var isRepositoryManager=(value5)=>typeof value5==="string"&&repositoryManagers2.has(value5);var isBacklogProvider=(value5)=>typeof value5==="string"&&backlogProviders2.has(value5);var isAssetProvider=(value5)=>typeof value5==="string"&&assetProviders.has(value5);var isStringArray=(value5)=>Array.isArray(value5)&&value5.every((tool)=>typeof tool==="string");var normalizeRepoSettings=(value5)=>{if(typeof value5!=="object"||value5===null){return null}const record3=value5;if(!isBacklogProvider(record3.backlogProvider)||!isAssetProvider(record3.assetProviderSlug)||!isRepositoryManager(record3.repositoryManager)||!isStringArray(record3.requiredTools)){return null}return Object.fromEntries([["backlogProvider",record3.backlogProvider],["assetProviderSlug",record3.assetProviderSlug],...typeof record3.backlogProjectUrl==="string"?[["backlogProjectUrl",record3.backlogProjectUrl]]:[],...typeof record3.baselineVersion==="string"?[["baselineVersion",record3.baselineVersion]]:[],...typeof record3.cliVersion==="string"?[["cliVersion",record3.cliVersion]]:[],["repositoryManager",record3.repositoryManager],["requiredTools",[...new Set([...record3.requiredTools,...requiredToolsForRepositoryManager2(record3.repositoryManager)])].toSorted()]])};var readRepoSettings=(rootDirectory)=>{const settingsPath=path9.join(rootDirectory,repoSettingsFile);if(!existsSync3(settingsPath)){return null}return normalizeRepoSettings(JSON.parse(readFileSync4(settingsPath,"utf-8")))};var commandExistsOnPath=(command,env={},platform=process.platform)=>{const pathValue=env.PATH??env.Path;if(pathValue===undefined||pathValue.length===0){return false}const isWindows=platform==="win32";const pathSeparator=isWindows?";":":";const pathEntries=pathValue.split(pathSeparator).filter((entry)=>entry.length>0);const pathExtensions=isWindows?(env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter((extension)=>extension.length>0):[""];const commandExtensions=isWindows&&path9.extname(command).length===0?pathExtensions:[""];const hasPathSegment=command.includes("/")||command.includes("\\");const candidates=(hasPathSegment?[""]:pathEntries).flatMap((entry)=>commandExtensions.map((extension)=>hasPathSegment?`${command}${extension}`:path9.join(entry,`${command}${extension}`)));return candidates.some((candidate)=>{try{accessSync(candidate,isWindows?constants2.F_OK:constants2.X_OK);return true}catch{return false}})};var makeToolCommandRuntime=(environment)=>({commandExists:(command)=>commandExistsOnPath(command,environment),cwd:homedir(),env:environment,execFile:(command,args2,options4)=>{execFileSync(command,[...args2],{cwd:options4?.cwd,env:environment,stdio:options4?.stdio==="inherit"?["ignore","inherit","inherit"]:"ignore"})},execFileOutput:(command,args2,options4)=>execFileSync(command,[...args2],{cwd:options4?.cwd,encoding:"utf-8",env:environment})});var defaultRuntime=makeToolCommandRuntime({});var defaultToolBootstrapOptions={mode:"repair",stdio:"inherit"};var detectGlobalPackageManager=(runtime)=>{if(runtime.commandExists("bun")){return"bun"}if(runtime.commandExists("pnpm")){return"pnpm"}if(runtime.commandExists("npm")){return"npm"}return null};var globalInstallCommandFor=(packageManager,packageName)=>{switch(packageManager){case"bun":{return["bun","add","-g",packageName]}case"pnpm":{return["pnpm","add","-g",packageName]}case"npm":{return["npm","install","-g",packageName]}default:{return packageManager}}};var parseVersionParts=(value5)=>{const match8=value5.match(/\d+(?:\.\d+){0,2}/u);if(match8===null){return null}const[matchedVersion]=match8;return matchedVersion===undefined?null:matchedVersion.split(".").map((part)=>Number.parseInt(part,10))};var compareVersions=(actual,minimum)=>{const length=Math.max(actual.length,minimum.length);for(let index2=0;index2<length;index2+=1){const actualPart=actual[index2]??0;const minimumPart=minimum[index2]??0;if(actualPart>minimumPart){return 1}if(actualPart<minimumPart){return-1}}return 0};var isMinimumVersionSatisfied=(tool,runtime,cwd)=>{if(tool.minimumVersion===undefined||tool.versionCommand===undefined){return true}const[command,...args2]=tool.versionCommand;if(command===undefined||runtime.execFileOutput===undefined){return true}const actual=parseVersionParts(runtime.execFileOutput(command,args2,{cwd}));const minimum=parseVersionParts(tool.minimumVersion);if(actual===null||minimum===null){throw toolManagementFailure("ensure-required-tool",`Cannot verify required tool version from \`${tool.versionCommand.join(" ")}\`.`)}return compareVersions(actual,minimum)>=0};var commandCandidateValue=(candidate,env)=>{if(typeof candidate==="string"){return candidate}const value5=env[candidate.env];return value5===undefined||value5.length===0?null:value5};var shouldSkipEnsureCommands=(tool,runtime)=>tool.skipEnsureCommandsIfAnyCommandExists?.some((candidate)=>{const command=commandCandidateValue(candidate,runtime.env??{});return command!==null&&runtime.commandExists(command)})??false;var manualProviderCliTools=Object.fromEntries([...new Set(Object.values(repositoryManagerTools2).flat())].map((toolId)=>[toolId,{ensureCommands:[],manual:true,requiredBins:[]}]));var installTool=({cwd,installTarget,runtime,stdio,toolId,versionContract})=>{const packageManager=detectGlobalPackageManager(runtime);if(packageManager===null){throw toolManagementFailure("ensure-required-tool","Cannot install required tools because no supported global package manager was found on PATH. Install Bun, pnpm, or npm first.")}if(installTarget===undefined){throw toolManagementFailure("ensure-required-tool",`Required tool \`${toolId}\` cannot be installed automatically.`)}const[command,...args2]=globalInstallCommandFor(packageManager,installTarget);runtime.execFile(command,args2,{cwd,stdio});if(!runtime.commandExists(toolId)){throw toolManagementFailure("ensure-required-tool",`Tried to install required tool \`${toolId}\`, but the binary is still not available on PATH afterwards.`)}if(!isMinimumVersionSatisfied(versionContract,runtime,cwd)){throw toolManagementFailure("ensure-required-tool",`Tried to install required tool \`${toolId}\`, but the installed version does not satisfy ${versionContract.minimumVersion}.`)}};var ensureToolsInstalled=(toolIds,baseline=bundledBaseline,runtime=defaultRuntime,options4=defaultToolBootstrapOptions)=>{const statuses=[];const toolCatalogById=Object.fromEntries(baseline.tools.map((tool)=>[tool.id,tool]));const cwd=runtime.cwd??homedir();for(const toolId of toolIds){const tool=toolCatalogById[toolId]===undefined?manualProviderCliTools[toolId]:{...toolCatalogById[toolId],manual:false};if(tool===undefined){throw toolManagementFailure("ensure-required-tool",`Unknown required tool \`${toolId}\` in baseline.`)}const missingPrerequisites=tool.requiredBins.filter((command)=>!runtime.commandExists(command));if(missingPrerequisites.length>0){throw toolManagementFailure("ensure-required-tool",`Cannot install required tool \`${toolId}\` because ${missingPrerequisites.join(", ")} is not available on PATH.`)}const versionContract=tool;const alreadyPresent=runtime.commandExists(toolId)&&isMinimumVersionSatisfied(versionContract,runtime,cwd);const refreshLatest=options4.mode==="refresh-latest"&&!tool.manual;if(!alreadyPresent&&tool.manual){throw toolManagementFailure("ensure-required-tool",`Required external tool \`${toolId}\` is not available on PATH. Install it before running scaffold/update workflows.`)}if(!alreadyPresent||refreshLatest){const installTarget=refreshLatest?tool.latestInstallTarget:tool.packageName;installTool({cwd,installTarget,runtime,stdio:options4.stdio,toolId,versionContract})}const ensureCommandContract=tool;if(!shouldSkipEnsureCommands(ensureCommandContract,runtime)){for(const[command,...args2]of tool.ensureCommands){runtime.execFile(command,args2,{cwd,stdio:options4.stdio})}}statuses.push({status:alreadyPresent&&!refreshLatest?"already-present":"installed",toolId})}return statuses};var errorMessage=(cause)=>cause instanceof Error?cause.message:String(cause);var errorStack=(cause)=>cause instanceof Error?cause.stack??cause.message:String(cause);var ensureToolsInstalledBestEffort=(toolIds,baseline=bundledBaseline,runtime=defaultRuntime,options4=defaultToolBootstrapOptions)=>toolIds.flatMap((toolId)=>{try{return ensureToolsInstalled([toolId],baseline,runtime,options4)}catch(error2){return[Object.fromEntries([["toolId",toolId],["status","failed"],["errorMessage",errorMessage(error2)],["errorStack",errorStack(error2)]])]}});var providerChoices=[{title:"GitHub Projects and Issues",value:"github"},{title:"Linear",value:"linear"},{title:"Azure DevOps",value:"azure-devops"},{title:"monday.com",value:"monday"}];var assetChoices=[...providerChoices,{title:"GitLab",value:"gitlab"},{title:"Bitbucket",value:"bitbucket"}];var repositoryChoices=[{title:"GitHub",value:"github"},{title:"GitLab",value:"gitlab"},{title:"Azure DevOps",value:"azure-devops"},{title:"Bitbucket",value:"bitbucket"}];var validProjectUrl=(input2)=>{const value5=input2.trim();try{const url2=new URL(value5);return url2.protocol==="http:"||url2.protocol==="https:"?value5:null}catch{return null}};var selectRepoSettings=({prompt,defaults:defaults2,retryCommand})=>gen2(function*selectSettings(){const backlogProvider=yield*prompt.singleSelect({choices:providerChoices,defaultValue:defaults2?.backlogProvider??"github",message:"Select backlog provider"});const assetProviderSlug=yield*prompt.singleSelect({choices:assetChoices,defaultValue:defaults2?.assetProviderSlug??backlogProvider,message:"Select asset provider"});const repositoryManager=yield*prompt.singleSelect({choices:repositoryChoices,defaultValue:defaults2?.repositoryManager??"github",message:"Select repository manager"});const input2=yield*prompt.readLine(`Backlog project URL${defaults2?.backlogProjectUrl?` [${defaults2.backlogProjectUrl}]`:""}: `);const backlogProjectUrl=validProjectUrl(input2||defaults2?.backlogProjectUrl||"");if(backlogProjectUrl===null){return yield*fail6(new CliPromptError({message:`Backlog project URL must be an absolute HTTP(S) URL. Rerun \`${retryCommand}\`.`}))}return{assetProviderSlug,backlogProjectUrl,backlogProvider,repositoryManager}});var ensureCommandMetadata=declareCommandMetadata({examples:[{command:"hi ensure",summary:"Reconfigure current project settings."}],group:"commands",interaction:"required",name:"ensure",options:[],outputModes:["interactive","plain"],summary:"Reconfigure backlog, asset, repository, and backlog project URL settings only."});var mapSettingsError=(error2)=>new CliPromptError({message:error2._tag==="ProjectSettingsMissing"?`${projectSettingsFile} was not found. Run \`hi init\` first.`:error2.message});var runEnsure=({rootDirectory,prompt})=>gen2(function*ensureSettings(){const projectSettings=yield*ProjectSettings;const current=(yield*projectSettings.read(rootDirectory).pipe(mapError3(mapSettingsError))).settings;const selected=yield*selectRepoSettings({defaults:current,prompt,retryCommand:"hi ensure"});const requiredTools=reconcileRepositoryManagerTools({previousRepositoryManager:current.repositoryManager,repositoryManager:selected.repositoryManager,requiredTools:current.requiredTools});yield*projectSettings.write(rootDirectory,{_tag:"ReconfigurationChange",assetProviderSlug:selected.assetProviderSlug,...selected.backlogProjectUrl===undefined?{}:{backlogProjectUrl:selected.backlogProjectUrl},backlogProvider:selected.backlogProvider,repositoryManager:selected.repositoryManager,requiredTools}).pipe(mapError3(mapSettingsError));return{changes:[{action:"configure",state:"completed",subject:projectSettingsFile}],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"success",warnings:[]}});var executeEnsureCommand=(input2)=>captureCommandResult(runEnsure(input2));var ensureCommand=exports_Command.make(ensureCommandMetadata.name,{},()=>scoped2(gen2(function*runEnsureCommand(){const outputMode=yield*SelectedOutputMode;if(outputMode!=="interactive"){return yield*new CliValidationError({message:outputMode==="json"?"`hi ensure` requires interactive input and is unavailable in JSON mode.":"`hi ensure` requires interactive input and is unavailable when output is redirected.",recoveryCommand:"hi ensure"})}const prompt=yield*PromptLive;return yield*executeEnsureCommand({prompt,rootDirectory:process.cwd()})}))).pipe(withCommandMetadata(ensureCommandMetadata));class InvalidMigrationRetry extends TaggedErrorClass()("InvalidMigrationRetry",{message:String5}){}class InvalidMutationRetry extends TaggedErrorClass()("InvalidMutationRetry",{message:String5}){}class InvalidOperatorContext extends TaggedErrorClass()("InvalidOperatorContext",{message:String5}){}var SkillsCliScope=Literals(["project","global"]);var skillsCliFailureFields={agent:String5,message:String5,operation:Literals(["list","install","remove"]),scope:SkillsCliScope};var verifiedInstalledSkillSchema=Struct({agents:ArraySchema(String5),cliCompatibility:Struct({maximumExclusive:String5,minimum:String5}),name:String5,path:String5,revision:String5,scope:SkillsCliScope,source:String5,version:String5});var SkillsCliVerificationFailureReason=Literals(["unsafe-path","missing","unreadable","malformed","identity-mismatch"]);class SkillsCliVerificationFailure extends TaggedErrorClass()("SkillsCliVerificationFailure",{...skillsCliFailureFields,reason:SkillsCliVerificationFailureReason,skillName:String5,skillPath:String5,verifiedSkills:ArraySchema(verifiedInstalledSkillSchema)}){}class SkillsCliBindingFailure extends TaggedErrorClass()("SkillsCliBindingFailure",{...skillsCliFailureFields,reportedAgents:ArraySchema(String5),skillName:String5,verifiedSkills:ArraySchema(verifiedInstalledSkillSchema)}){}class SkillsCliExit extends TaggedErrorClass()("SkillsCliExit",{...skillsCliFailureFields,exitCode:Number6,stderr:String5}){}class SkillsCliMalformedOutput extends TaggedErrorClass()("SkillsCliMalformedOutput",{...skillsCliFailureFields,stdout:String5}){}class SkillsCliTimeout extends TaggedErrorClass()("SkillsCliTimeout",{...skillsCliFailureFields,timeoutMs:Number6}){}class SkillsCliUnavailable extends TaggedErrorClass()("SkillsCliUnavailable",{...skillsCliFailureFields,executable:String5}){}class SkillsCliUnsupportedVersion extends TaggedErrorClass()("SkillsCliUnsupportedVersion",{...skillsCliFailureFields,minimumVersion:String5,version:String5}){}var SkillsCli=Service("@punks/cli/features/operator-skill/SkillsCli");var OperatorSkillOperations=Service("@punks/cli/features/operator-skill/OperatorSkillOperations");var runOperatorSkillApplication=fn2("OperatorSkill.run")(function*runOperatorSkillApplication2(action2,selectAgent){const operations=yield*OperatorSkillOperations;return yield*operations.run(action2,selectAgent)});var isWithinCanonicalPath=(candidate,root)=>candidate===root||candidate.startsWith(root.endsWith("/")?root:`${root}/`)||candidate.startsWith(root.endsWith("\\")?root:`${root}\\`);var installedOperatorSkillCopyIdentity=(copy3)=>JSON.stringify([copy3.scope,copy3.scope==="project-local"?copy3.projectRoot:"",copy3.version,copy3.source,copy3.revision,copy3.compatibility,[...copy3.boundAgents].toSorted()]);var compareText=(left,right)=>left<right?-1:Number(left>right);var compareCopyIdentity=(left,right)=>{const leftIdentity=installedOperatorSkillCopyIdentity(left);const rightIdentity=installedOperatorSkillCopyIdentity(right);return compareText(leftIdentity,rightIdentity)};var sortCopies=(copies)=>copies.toSorted(compareCopyIdentity);var failureIdentity=(failure)=>JSON.stringify([failure.scope,failure.scope==="project-local"?failure.projectRoot:"",failure.reason,failure.message]);var resolveInstalledOperatorSkillState=(input2)=>{const failures=[];const copies=[];for(const inspection of input2.inspections){if(inspection._tag==="DetectionFailed"){failures.push(inspection);continue}if(inspection.scope==="global"){copies.push(...inspection.copies.map((copy3)=>({...copy3,boundAgents:[...copy3.boundAgents].toSorted()})));continue}for(const copy3 of inspection.copies){if(copy3.projectRoot!==inspection.projectRoot){failures.push({_tag:"DetectionFailed",message:`Project-local copy root ${copy3.projectRoot} does not match inspection root ${inspection.projectRoot}`,projectRoot:inspection.projectRoot,reason:"ProjectRootMismatch",scope:"project-local"});continue}copies.push({...copy3,boundAgents:[...copy3.boundAgents].toSorted(),projectRoot:inspection.projectRoot})}}const detected=sortCopies(copies);const incompatible=sortCopies(copies.filter((copy3)=>copy3.compatibility==="incompatible"));if(failures.length>0){return{_tag:"DetectionFailed",detected,failures:failures.toSorted((left,right)=>compareText(failureIdentity(left),failureIdentity(right))),incompatible}}const candidates=detected.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)&&(copy3.scope==="global"||isWithinCanonicalPath(input2.cwd,copy3.projectRoot))).toSorted((left,right)=>Number(left.scope==="global")-Number(right.scope==="global"));const[effective]=candidates;if(effective===undefined){return{_tag:"Absent",detected,incompatible}}const topCandidates=candidates.filter((copy3)=>copy3.scope===effective.scope);if(topCandidates.some((copy3)=>installedOperatorSkillCopyIdentity(copy3)!==installedOperatorSkillCopyIdentity(effective))){return{_tag:"Ambiguous",candidates:topCandidates.toSorted(compareCopyIdentity),incompatible,shadowed:sortCopies(candidates.slice(topCandidates.length))}}return{_tag:"Resolved",effective,incompatible,shadowed:sortCopies(candidates.slice(1))}};var operatorSkillScopeCwd=(scope3,input2)=>scope3==="global"?input2.cwd:input2.projectRoot;var parseSemanticVersion=(value5)=>{const match8=/^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-(?<prerelease>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(value5);const groups=match8?.groups;const prerelease=groups?.prerelease?.split(".");if(groups===undefined||prerelease?.some((identifier2)=>/^\d+$/u.test(identifier2)&&!/^(?:0|[1-9]\d*)$/u.test(identifier2))){return}return{core:[groups.major,groups.minor,groups.patch],prerelease}};var compareIdentifiers=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var compareNumericIdentifiers=(left,right)=>left.length-right.length||compareIdentifiers(left,right);var comparePrerelease=(left,right)=>{if(left===undefined||right===undefined){if(left===right){return 0}return left===undefined?1:-1}const length=Math.max(left.length,right.length);for(let index2=0;index2<length;index2+=1){const leftIdentifier=left[index2];const rightIdentifier=right[index2];if(leftIdentifier===undefined||rightIdentifier===undefined){if(leftIdentifier===rightIdentifier){return 0}return leftIdentifier===undefined?-1:1}if(leftIdentifier===rightIdentifier){continue}const leftIsNumeric=/^\d+$/u.test(leftIdentifier);const rightIsNumeric=/^\d+$/u.test(rightIdentifier);if(leftIsNumeric&&rightIsNumeric){return compareNumericIdentifiers(leftIdentifier,rightIdentifier)}if(leftIsNumeric!==rightIsNumeric){return leftIsNumeric?-1:1}return compareIdentifiers(leftIdentifier,rightIdentifier)}return 0};var compareSemanticVersions=(left,right)=>{const parsedLeft=parseSemanticVersion(left);const parsedRight=parseSemanticVersion(right);if(parsedLeft===undefined||parsedRight===undefined){return}for(let index2=0;index2<parsedLeft.core.length;index2+=1){const compared=compareNumericIdentifiers(parsedLeft.core[index2],parsedRight.core[index2]);if(compared!==0){return compared}}return comparePrerelease(parsedLeft.prerelease,parsedRight.prerelease)};var satisfiesSemanticVersionRange=(version3,minimum,maximumExclusive)=>{const comparedToMinimum=compareSemanticVersions(version3,minimum);const comparedToMaximum=compareSemanticVersions(version3,maximumExclusive);return comparedToMinimum!==undefined&&comparedToMaximum!==undefined&&comparedToMinimum>=0&&comparedToMaximum<0};var authoritativeContentManifest=Object.freeze([Object.freeze({path:"SKILL.md",sha256:"aee7ff55492ba810ca75bfbc8bbf5d4a14695828634c3fb1c6aea0a895589b98"}),Object.freeze({path:"references/commands.md",sha256:"62e07c52acd6add81a8feccbe39eb99521d6a2c9682d97e940bcc39a5e705e1a"}),Object.freeze({path:"references/post-command-flow.md",sha256:"0975f458b8636de0ef0d26e1dbc3c353208acc439fa47ebe2f261181e94815a8"})]);var authoritativeOperatorSkillTarget=Object.freeze({cliCompatibility:Object.freeze({maximumExclusive:"4.0.0",minimum:"3.0.0-beta.0"}),contentManifest:authoritativeContentManifest,revision:"09a6f3c6f9a7ed62a7e4abf0411f8a0f4f993e1d",source:"https://github.com/wearedevpunks/skills/tree/09a6f3c6f9a7ed62a7e4abf0411f8a0f4f993e1d/skills/agnostic/cli/hi-cli",version:"1.1.0"});var immutableRevisionPattern=/^[0-9a-f]{40}$/u;var authoritativeSourceRoot="https://github.com/wearedevpunks/skills";var operatorSkillPath="skills/agnostic/cli/hi-cli";var targetIsIncomplete=(target)=>target.source.trim()===""||target.version.trim()===""||target.revision.trim()===""||target.cliCompatibility.minimum.trim()===""||target.cliCompatibility.maximumExclusive.trim()===""||target.contentManifest.length===0||target.contentManifest.some((entry)=>entry.path.trim()===""||entry.sha256.trim()==="");var validateTarget=(target)=>{if(targetIsIncomplete(target)){return"IncompleteIdentity"}if(!immutableRevisionPattern.test(target.revision)){return"MovingRevision"}const immutableSource=`${authoritativeSourceRoot}/tree/${target.revision}/${operatorSkillPath}`;if(target.source!==immutableSource){return target.source.startsWith(authoritativeSourceRoot)?"SourceRevisionMismatch":"NonAuthoritativeSource"}const version3=compareSemanticVersions(target.version,target.version);const rangeOrder=compareSemanticVersions(target.cliCompatibility.minimum,target.cliCompatibility.maximumExclusive);if(version3===undefined||rangeOrder===undefined||rangeOrder>=0){return"InvalidVersion"}if(target.source!==authoritativeOperatorSkillTarget.source||target.version!==authoritativeOperatorSkillTarget.version||target.revision!==authoritativeOperatorSkillTarget.revision||target.cliCompatibility.minimum!==authoritativeOperatorSkillTarget.cliCompatibility.minimum||target.cliCompatibility.maximumExclusive!==authoritativeOperatorSkillTarget.cliCompatibility.maximumExclusive||JSON.stringify(target.contentManifest)!==JSON.stringify(authoritativeOperatorSkillTarget.contentManifest)){return"NonAuthoritativeIdentity"}return};var resolveOperatorSkillTarget=(input2)=>{if(compareSemanticVersions(input2.activeCliVersion,input2.activeCliVersion)===undefined){return{_tag:"NoCompatibleTarget",activeCliVersion:input2.activeCliVersion}}const compatibleIndexes=[];for(const[candidateIndex,candidate]of input2.candidates.entries()){const invalidReason=validateTarget(candidate);if(invalidReason!==undefined){return{_tag:"InvalidTarget",candidateIndex,reason:invalidReason}}if(satisfiesSemanticVersionRange(input2.activeCliVersion,candidate.cliCompatibility.minimum,candidate.cliCompatibility.maximumExclusive)){compatibleIndexes.push(candidateIndex)}}if(compatibleIndexes.length===0){return{_tag:"NoCompatibleTarget",activeCliVersion:input2.activeCliVersion}}if(compatibleIndexes.length>1){return{_tag:"AmbiguousCompatibleTargets",activeCliVersion:input2.activeCliVersion,candidateIndexes:compatibleIndexes}}return{_tag:"Resolved",target:authoritativeOperatorSkillTarget}};var compatibilityFor=(activeCliVersion,skill)=>satisfiesSemanticVersionRange(activeCliVersion,skill.cliCompatibility.minimum,skill.cliCompatibility.maximumExclusive)?"compatible":"incompatible";var isVerified=(skill)=>("version"in skill);var mapGlobalCopy=(activeCliVersion,skill)=>({boundAgents:[...skill.agents].toSorted(),compatibility:compatibilityFor(activeCliVersion,skill),revision:skill.revision,scope:"global",source:skill.source,version:skill.version});var mapProjectCopy=(activeCliVersion,projectRoot,skill)=>({boundAgents:[...skill.agents].toSorted(),compatibility:compatibilityFor(activeCliVersion,skill),projectRoot,revision:skill.revision,scope:"project-local",source:skill.source,version:skill.version});var inspectListedSkills=(scope3,input2,skills)=>{const operatorSkills=skills.filter((skill)=>skill.name==="hi-cli"&&isVerified(skill));const legacySkills=skills.filter((skill)=>skill.name==="dp-cli");if(scope3==="global"){return{_tag:"Inspected",copies:operatorSkills.map((skill)=>mapGlobalCopy(input2.activeCliVersion,skill)),legacy:legacySkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,scope:scope3})),scope:scope3}}return{_tag:"Inspected",copies:operatorSkills.map((skill)=>mapProjectCopy(input2.activeCliVersion,input2.projectRoot,skill)),legacy:legacySkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,projectRoot:input2.projectRoot,scope:scope3})),projectRoot:input2.projectRoot,scope:scope3}};var failedInspection=(scope3,input2,failure)=>{const verifiedSkills=failure._tag==="SkillsCliVerificationFailure"||failure._tag==="SkillsCliBindingFailure"?failure.verifiedSkills:[];if(scope3==="global"){return{_tag:"InspectionFailed",copies:verifiedSkills.map((skill)=>mapGlobalCopy(input2.activeCliVersion,skill)),failure,legacy:[],scope:scope3}}return{_tag:"InspectionFailed",copies:verifiedSkills.map((skill)=>mapProjectCopy(input2.activeCliVersion,input2.projectRoot,skill)),failure,legacy:[],projectRoot:input2.projectRoot,scope:scope3}};var installedInspections=(inspections)=>inspections.flatMap((inspection)=>{const detected=inspection.scope==="global"?{_tag:"Detected",copies:inspection.copies,scope:"global"}:{_tag:"Detected",copies:inspection.copies,projectRoot:inspection.projectRoot,scope:"project-local"};if(inspection._tag==="Inspected"){return[detected]}const failure=inspection.scope==="global"?{_tag:"DetectionFailed",message:inspection.failure.message,reason:"ListingFailed",scope:"global"}:{_tag:"DetectionFailed",message:inspection.failure.message,projectRoot:inspection.projectRoot,reason:"ListingFailed",scope:"project-local"};return inspection.copies.length===0?[failure]:[detected,failure]});var collectLegacyCopies=(inspections)=>{const copies=[];for(const inspection of inspections){copies.push(...inspection.legacy)}return copies};var inspectOperatorSkillLifecycle=fn2("OperatorSkillLifecycle.status")(function*inspectOperatorSkillLifecycle2(input2){const resolution=resolveOperatorSkillTarget({activeCliVersion:input2.activeCliVersion,candidates:[authoritativeOperatorSkillTarget]});if(resolution._tag!=="Resolved"){return{_tag:"TargetResolutionFailed",resolution}}const skillsCli=yield*SkillsCli;const[globalResult,projectResult]=yield*all2([result2(skillsCli.list({agent:input2.activeAgent,cwd:operatorSkillScopeCwd("global",input2),scope:"global",target:resolution.target})),result2(skillsCli.list({agent:input2.activeAgent,cwd:operatorSkillScopeCwd("project-local",input2),scope:"project",target:resolution.target}))],{concurrency:"unbounded"});const inspections=[isFailure2(globalResult)?failedInspection("global",input2,globalResult.failure):inspectListedSkills("global",input2,globalResult.success),isFailure2(projectResult)?failedInspection("project-local",input2,projectResult.failure):inspectListedSkills("project-local",input2,projectResult.success)];const installed=resolveInstalledOperatorSkillState({activeAgent:input2.activeAgent,cwd:input2.cwd,inspections:installedInspections(inspections)});return{_tag:"Inspected",inspections,installed,legacy:collectLegacyCopies(inspections),target:resolution.target}});var retryFor=(operation,scope3,input2,target)=>Object.freeze({input:Object.freeze({...input2}),operation,scope:scope3,target});var inspectionFor=(status2,scope3)=>status2.inspections.find((inspection)=>inspection.scope===scope3);var copyMatchesTarget=(copy3,target)=>copy3.version===target.version&&copy3.source===target.source&&copy3.revision===target.revision&&copy3.compatibility==="compatible";var copyAppliesToScope=(copy3,input2)=>copy3.boundAgents.includes(input2.activeAgent)&&(copy3.scope==="global"||copy3.projectRoot===input2.projectRoot);var targetCopy=(inspection,input2,target)=>inspection.copies.find((copy3)=>copyMatchesTarget(copy3,target)&&copyAppliesToScope(copy3,input2));var hasCompetingCopyIdentity=(inspection,copy3,input2)=>inspection.copies.some((candidate)=>copyAppliesToScope(candidate,input2)&&installedOperatorSkillCopyIdentity(candidate)!==installedOperatorSkillCopyIdentity(copy3));var verifyOperatorSkillScope=(scope3,input2,target,verification)=>{if(verification._tag==="TargetResolutionFailed"){return{_tag:"Unverified",reason:"TargetResolutionFailed",scope:scope3,verification}}const inspection=inspectionFor(verification,scope3);if(inspection?._tag==="InspectionFailed"){return{_tag:"Unverified",failure:inspection.failure,reason:"InspectionFailed",scope:scope3,verification}}if(inspection!==undefined){const copy3=targetCopy(inspection,input2,target);if(copy3!==undefined){if(hasCompetingCopyIdentity(inspection,copy3,input2)){return{_tag:"Unverified",reason:"CompetingCopyObserved",scope:scope3,verification}}return{_tag:"Verified",copy:copy3,scope:scope3,verification}}}return{_tag:"Unverified",reason:"TargetNotObserved",scope:scope3,verification}};var ensureAndVerifyOperatorSkillScope=fn2("OperatorSkillLifecycle.ensureAndVerifyScope")(function*ensureAndVerifyOperatorSkillScope2(scope3,input2,target){const skillsCli=yield*SkillsCli;const write2=yield*result2(skillsCli.install({agent:input2.activeAgent,cwd:operatorSkillScopeCwd(scope3,input2),scope:scope3==="global"?"global":"project",target}));if(isFailure2(write2)){return{_tag:"Failed",failure:write2.failure,scope:scope3}}const verification=yield*inspectOperatorSkillLifecycle(input2);return verifyOperatorSkillScope(scope3,input2,target,verification)});var mutationActionFor=(operation,input2,target,result4)=>{const retry5=retryFor(operation,result4.scope,input2,target);if(result4._tag==="Failed"){return{_tag:"Failed",failure:result4.failure,operation,phase:"write",retry:retry5,scope:result4.scope}}if(result4._tag==="Unverified"){return{...result4,operation,retry:retry5}}return{...result4,operation}};var inspectionDetectedOperatorSkill=(inspection)=>inspection.copies.length>0||inspection._tag==="InspectionFailed"&&(inspection.failure._tag==="SkillsCliVerificationFailure"||inspection.failure._tag==="SkillsCliBindingFailure")&&inspection.failure.skillName==="hi-cli";var inspectionScopeIsUnknown=(inspection)=>inspection._tag==="InspectionFailed"&&!inspectionDetectedOperatorSkill(inspection);var alreadyVerifiedGlobal=(before,input2)=>{const inspection=inspectionFor(before,"global");if(inspection?._tag!=="Inspected"){return}const copy3=targetCopy(inspection,input2,before.target);if(copy3===undefined||hasCompetingCopyIdentity(inspection,copy3,input2)){return}return{_tag:"AlreadyVerified",copy:copy3,operation:"install",scope:"global",verification:before}};var unknownScopeFailures=(operation,before,input2)=>before.inspections.flatMap((inspection)=>inspectionScopeIsUnknown(inspection)&&(operation==="update"||inspection.scope==="global")?[{_tag:"Failed",failure:inspection.failure,operation,phase:"inspection",retry:retryFor(operation,inspection.scope,input2,before.target),scope:inspection.scope}]:[]);var scopesToMutate=(operation,before)=>{if(operation==="install"){const globalIsUnknown=before.inspections.some((inspection)=>inspection.scope==="global"&&inspectionScopeIsUnknown(inspection));return globalIsUnknown?[]:["global"]}return before.inspections.filter(inspectionDetectedOperatorSkill).map((inspection)=>inspection.scope)};var mutateOperatorSkill=fn2("OperatorSkillLifecycle.mutate")(function*mutateOperatorSkill2(operation,input2){const before=yield*inspectOperatorSkillLifecycle(input2);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,operation,reload:{_tag:"NotRequired"}}}const existingGlobal=operation==="install"?alreadyVerifiedGlobal(before,input2):undefined;const actions=[...unknownScopeFailures(operation,before,input2),...existingGlobal===undefined?[]:[existingGlobal]];let wrote=false;const scopes=existingGlobal===undefined?scopesToMutate(operation,before):[];for(const scope3 of scopes){const ensured=yield*ensureAndVerifyOperatorSkillScope(scope3,input2,before.target);wrote||=ensured._tag!=="Failed";actions.push(mutationActionFor(operation,input2,before.target,ensured))}return{_tag:"Completed",actions,before,operation,reload:wrote?{_tag:"ReloadRequired",skill:"hi-cli"}:{_tag:"NotRequired"},target:before.target}});var installOperatorSkill=fn2("OperatorSkillLifecycle.install")(function*installOperatorSkill2(input2){return yield*mutateOperatorSkill("install",input2)});var updateOperatorSkill=fn2("OperatorSkillLifecycle.update")(function*updateOperatorSkill2(input2){return yield*mutateOperatorSkill("update",input2)});var migrationRetry=(scope3,input2,target,phase,affectedScopes)=>Object.freeze({affectedScopes:Object.freeze([...affectedScopes]),input:Object.freeze({...input2}),operation:"migrate",phase,scope:scope3,target});var affectedScopes=(before,input2)=>["global","project-local"].filter((scope3)=>(scope3==="global"||isWithinCanonicalPath(input2.cwd,input2.projectRoot))&&before.inspections.some((inspection)=>inspection.scope===scope3&&inspection.legacy.some((copy3)=>copy3.boundAgents.includes(input2.activeAgent))));var scopeApplies=(scope3,input2)=>scope3==="global"||isWithinCanonicalPath(input2.cwd,input2.projectRoot);var recoverableScopes=(input2,scopes)=>["global","project-local"].filter((scope3)=>scopes.includes(scope3)&&scopeApplies(scope3,input2));var targetIdentity=(target)=>JSON.stringify([target.source,target.version,target.revision,target.cliCompatibility,target.contentManifest]);var legacyIdentity=(copy3)=>JSON.stringify([copy3.scope,copy3.scope==="project-local"?copy3.projectRoot:"",copy3.path,[...copy3.boundAgents].toSorted()]);var inspectedLegacyCopiesFor=(status2,scope3)=>{if(status2._tag!=="Inspected"){return}const inspection=status2.inspections.find((candidate)=>candidate.scope===scope3);return inspection?._tag==="Inspected"?inspection.legacy:undefined};var legacyCopiesFor=(status2,scope3)=>inspectedLegacyCopiesFor(status2,scope3)??[];var legacyCopiesMatch=(left,right)=>JSON.stringify(left.map(legacyIdentity).toSorted())===JSON.stringify(right.map(legacyIdentity).toSorted());var unrelatedLegacyResiduals=(copies,activeAgent)=>copies.flatMap((copy3)=>{const boundAgents=copy3.boundAgents.filter((agent)=>agent!==activeAgent);return boundAgents.length===0?[]:[{...copy3,boundAgents}]});var replacementAction=(result4,input2,target,scopes,wrote=true)=>{const retry5=migrationRetry(result4.scope,input2,target,"replacement",scopes);if(result4._tag==="Failed"){return{_tag:"ReplacementFailed",failure:result4.failure,retry:retry5,scope:result4.scope}}if(result4._tag==="Unverified"){return{_tag:"ReplacementUnverified",...result4.failure===undefined?{}:{failure:result4.failure},reason:result4.reason,retry:retry5,scope:result4.scope,verification:result4.verification}}return{_tag:"ReplacementVerified",copy:result4.copy,scope:result4.scope,verification:result4.verification,wrote}};var reloadGuidance=(wrote)=>wrote?{_tag:"ReloadRequired",skill:"hi-cli"}:{_tag:"NotRequired"};var verifyBarrierCopy=(scope3,input2,target,verification,expected)=>{const observed=verifyOperatorSkillScope(scope3,input2,target,verification);if(observed._tag!=="Verified"){return observed}if(expected===undefined||installedOperatorSkillCopyIdentity(observed.copy)!==installedOperatorSkillCopyIdentity(expected)){return{_tag:"Unverified",reason:"ReplacementChanged",scope:scope3,verification}}return observed};var legacyRemovalReason=(reason)=>{if(reason==="InspectionFailed"){return"InspectionFailed"}return reason==="ReplacementChanged"?"ReplacementChanged":"ReplacementNotVerified"};var validateAffectedBarriers=(input2)=>(()=>{let blockingLoss;return input2.scopes.flatMap((scope3,scopeIndex)=>{const pending=scopeIndex>input2.afterIndex;const checked=verifyBarrierCopy(scope3,input2.migrationInput,input2.target,input2.verification,input2.barrierCopies.get(scope3));if(checked._tag==="Verified"){if(!pending||blockingLoss===undefined||input2.refusedScopes.has(scope3)){return[]}input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",barrierReason:blockingLoss.reason,barrierScope:blockingLoss.scope,...blockingLoss.failure===undefined?{}:{failure:blockingLoss.failure},reason:"BarrierLost",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]}if(pending&&input2.refusedScopes.has(scope3)){return[]}const failure="failure"in checked&&checked.failure!==undefined?{failure:checked.failure}:{};if(pending){input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",barrierReason:checked.reason,barrierScope:scope3,...failure,reason:"BarrierLost",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]}blockingLoss={reason:checked.reason,scope:scope3,...failure};if(input2.lostBarrierScopes.has(scope3)){return[]}input2.lostBarrierScopes.add(scope3);return[{_tag:"RemovalBarrierLost",afterScope:input2.afterScope,barrierReason:checked.reason,...failure,phase:input2.phase,position:scopeIndex===input2.afterIndex?"current":"prior",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]})})();var validatePeerLegacySnapshots=(input2)=>input2.scopes.flatMap((scope3,scopeIndex)=>{if(scopeIndex===input2.afterIndex){return[]}const observed=inspectedLegacyCopiesFor(input2.verification,scope3);if(observed===undefined){return[]}const activeChanged=!legacyCopiesMatch(input2.activeSnapshots.get(scope3)??[],observed.filter((copy3)=>copy3.boundAgents.includes(input2.migrationInput.activeAgent)));const unrelatedChanged=!legacyCopiesMatch(input2.unrelatedSnapshots.get(scope3)??[],unrelatedLegacyResiduals(observed,input2.migrationInput.activeAgent));if(!activeChanged&&!unrelatedChanged){return[]}const legacyReason=unrelatedChanged?"UnrelatedLegacyChanged":"ActiveLegacyChanged";const retry5=migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes);if(scopeIndex>input2.afterIndex){if(input2.refusedScopes.has(scope3)){return[]}input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",legacyReason,reason:"LegacyChanged",retry:retry5,scope:scope3,verification:input2.verification}]}if(input2.reportedScopes.has(scope3)){return[]}input2.reportedScopes.add(scope3);return[{_tag:"LegacyRemovalUnverified",reason:activeChanged?"LegacyChangedAfterRemoval":"UnrelatedLegacyChanged",retry:retry5,scope:scope3,verification:input2.verification}]});var handleFailedLegacyRemoval=fn2("OperatorSkillLifecycle.handleFailedLegacyRemoval")(function*handleFailedLegacyRemoval2(context4,failure){const{activeLegacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target,unrelatedLegacyCopies}=context4;const actions=[{_tag:"LegacyRemovalFailed",failure,retry:retry5,scope:scope3}];let wrote=false;const verification=yield*inspectOperatorSkillLifecycle(input2);const observedLegacy=inspectedLegacyCopiesFor(verification,scope3);const activeLegacyChanged=observedLegacy!==undefined&&!legacyCopiesMatch(activeLegacyCopies.get(scope3)??[],observedLegacy.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)));const unrelatedLegacyChanged=observedLegacy!==undefined&&!legacyCopiesMatch(unrelatedLegacyCopies.get(scope3)??[],unrelatedLegacyResiduals(observedLegacy,input2.activeAgent));if(activeLegacyChanged||unrelatedLegacyChanged){wrote=true;actions.push({_tag:"LegacyRemovalUnverified",reason:activeLegacyChanged?"LegacyChangedAfterFailure":"UnrelatedLegacyChanged",retry:retry5,scope:scope3,verification})}const peerLegacyActions=validatePeerLegacySnapshots({activeSnapshots:activeLegacyCopies,afterIndex:scopeIndex,migrationInput:input2,refusedScopes,reportedScopes:reportedLegacyScopes,scopes,target,unrelatedSnapshots:unrelatedLegacyCopies,verification});wrote||=peerLegacyActions.length>0;actions.push(...peerLegacyActions);const barrierActions=validateAffectedBarriers({afterIndex:scopeIndex,afterScope:scope3,barrierCopies,lostBarrierScopes,migrationInput:input2,phase:"remove-failed",refusedScopes,scopes,target,verification});wrote||=barrierActions.some((action2)=>action2.barrierReason!=="InspectionFailed"&&action2.barrierReason!=="TargetResolutionFailed");actions.push(...barrierActions);if(observedLegacy!==undefined){activeLegacyCopies.set(scope3,observedLegacy.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)));unrelatedLegacyCopies.set(scope3,unrelatedLegacyResiduals(observedLegacy,input2.activeAgent))}return{actions,wrote}});var handleSuccessfulLegacyRemoval=fn2("OperatorSkillLifecycle.handleSuccessfulLegacyRemoval")(function*handleSuccessfulLegacyRemoval2(context4){const{activeLegacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target,unrelatedLegacyCopies}=context4;const verification=yield*inspectOperatorSkillLifecycle(input2);let currentAction;if(verification._tag==="TargetResolutionFailed"){currentAction={_tag:"LegacyRemovalUnverified",reason:"ReplacementNotVerified",retry:retry5,scope:scope3,verification}}else{const inspection=verification.inspections.find((candidate)=>candidate.scope===scope3);const observedLegacy=inspectedLegacyCopiesFor(verification,scope3);const unrelatedLegacyChanged=observedLegacy!==undefined&&!legacyCopiesMatch(unrelatedLegacyCopies.get(scope3)??[],unrelatedLegacyResiduals(observedLegacy,input2.activeAgent));if(unrelatedLegacyChanged){currentAction={_tag:"LegacyRemovalUnverified",reason:"UnrelatedLegacyChanged",retry:retry5,scope:scope3,verification}}else if(inspection!==undefined&&inspection.legacy.some((copy3)=>copy3.boundAgents.includes(input2.activeAgent))){currentAction={_tag:"LegacyRemovalUnverified",reason:"LegacyStillPresent",retry:retry5,scope:scope3,verification}}else{const replacementCheck=verifyBarrierCopy(scope3,input2,target,verification,barrierCopies.get(scope3));currentAction=replacementCheck._tag==="Verified"?{_tag:"LegacyRemoved",scope:scope3,verification}:{_tag:"LegacyRemovalUnverified",..."failure"in replacementCheck&&replacementCheck.failure!==undefined?{failure:replacementCheck.failure}:{},reason:legacyRemovalReason(replacementCheck.reason),retry:retry5,scope:scope3,verification}}}const actions=[currentAction,...validatePeerLegacySnapshots({activeSnapshots:activeLegacyCopies,afterIndex:scopeIndex,migrationInput:input2,refusedScopes,reportedScopes:reportedLegacyScopes,scopes,target,unrelatedSnapshots:unrelatedLegacyCopies,verification})];const observedCurrentLegacy=inspectedLegacyCopiesFor(verification,scope3);if(observedCurrentLegacy!==undefined){activeLegacyCopies.set(scope3,observedCurrentLegacy.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)))}actions.push(...validateAffectedBarriers({afterIndex:scopeIndex,afterScope:scope3,barrierCopies,lostBarrierScopes,migrationInput:input2,phase:"remove-succeeded",refusedScopes,scopes,target,verification}));return actions});var prepareMigration=(before,input2,recoveryScopes,recoveryPhase)=>{const observedScopes=affectedScopes(before,input2);const recoveryScopeLimit=recoveryScopes===undefined?undefined:recoverableScopes(input2,recoveryScopes);let scopes=observedScopes;if(recoveryScopeLimit!==undefined){scopes=recoveryPhase==="preflight"?observedScopes.filter((scope3)=>recoveryScopeLimit.includes(scope3)):recoveryScopeLimit}const retryScopes=recoveryScopeLimit===undefined?recoverableScopes(input2,[...scopes,...before.inspections.flatMap((inspection)=>inspection._tag==="InspectionFailed"?[inspection.scope]:[])]):recoveryScopeLimit;const preflightFailures=before.inspections.flatMap((inspection)=>inspection._tag==="InspectionFailed"&&scopeApplies(inspection.scope,input2)&&(recoveryScopeLimit===undefined||recoveryScopeLimit.includes(inspection.scope))?[{_tag:"PreflightFailed",failure:inspection.failure,retry:migrationRetry(inspection.scope,input2,before.target,"preflight",retryScopes),scope:inspection.scope}]:[]);return{preflightFailures,scopes}};var ensureReplacementBarriers=fn2("OperatorSkillLifecycle.ensureReplacementBarriers")(function*ensureReplacementBarriers2(scopes,input2,before){const actions=[];let wrote=false;let barrierFailed=false;for(const scope3 of scopes){const existing=verifyOperatorSkillScope(scope3,input2,before.target,before);if(existing._tag==="Verified"){actions.push({_tag:"ReplacementVerified",copy:existing.copy,scope:scope3,verification:existing.verification,wrote:false});continue}const replacement=yield*ensureAndVerifyOperatorSkillScope(scope3,input2,before.target);wrote||=replacement._tag!=="Failed";barrierFailed||=replacement._tag!=="Verified";actions.push(replacementAction(replacement,input2,before.target,scopes))}return{actions,barrierFailed,wrote}});var inspectReplacementBarrier=fn2("OperatorSkillLifecycle.inspectReplacementBarrier")(function*inspectReplacementBarrier2(scopes,input2,target,recoveryScopes){const status2=yield*inspectOperatorSkillLifecycle(input2);const failedInspections=status2._tag==="Inspected"?status2.inspections.filter((inspection)=>inspection._tag==="InspectionFailed"&&scopeApplies(inspection.scope,input2)&&(recoveryScopes===undefined||scopes.includes(inspection.scope))):[];const failedScopes=new Set(failedInspections.map((inspection)=>inspection.scope));const verifications=scopes.flatMap((scope3)=>{if(failedScopes.has(scope3)){return[]}const verification=verifyOperatorSkillScope(scope3,input2,target,status2);return[{scope:scope3,verification}]});const actions=[...failedInspections.map((inspection)=>({_tag:"BarrierInspectionFailed",failure:inspection.failure,retry:migrationRetry(inspection.scope,input2,target,"barrier",scopes),scope:inspection.scope})),...verifications.flatMap(({scope:scope3,verification})=>verification._tag==="Unverified"?[{_tag:"BarrierUnverified",...verification.failure===undefined?{}:{failure:verification.failure},reason:verification.reason,retry:migrationRetry(scope3,input2,target,"barrier",scopes),scope:scope3,verification:verification.verification}]:[])];return{actions,status:status2,verifications}});var migrateLegacyOperatorSkillPolicy=fn2("OperatorSkillLifecycle.migratePolicy")(function*migrateLegacyOperatorSkillPolicy2(input2,recoveryScopes,expectedTarget,recoveryPhase){const before=yield*inspectOperatorSkillLifecycle(input2);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,reload:{_tag:"NotRequired"}}}if(expectedTarget!==undefined&&targetIdentity(expectedTarget)!==targetIdentity(before.target)){return{_tag:"RetryTargetChanged",actions:[],expected:expectedTarget,observed:before.target,reload:{_tag:"NotRequired"}}}const{preflightFailures,scopes}=prepareMigration(before,input2,recoveryScopes,recoveryPhase);if(preflightFailures.length>0){return{_tag:"Refused",actions:preflightFailures,before,reason:"PreflightUnknown",reload:{_tag:"NotRequired"},target:before.target}}if(scopes.length===0){return{_tag:"Completed",actions:[],before,reload:{_tag:"NotRequired"},target:before.target}}const replacement=yield*ensureReplacementBarriers(scopes,input2,before);const actions=[...replacement.actions];let{wrote}=replacement;if(replacement.barrierFailed){return{_tag:"Refused",actions,before,reason:"ReplacementBarrierFailed",reload:reloadGuidance(wrote),target:before.target}}const barrier=yield*inspectReplacementBarrier(scopes,input2,before.target,recoveryScopes);const finalBarrier=barrier.status;const finalVerifications=barrier.verifications;actions.push(...barrier.actions);if(barrier.actions.length>0){return{_tag:"Refused",actions,before,reason:"ReplacementBarrierFailed",reload:reloadGuidance(wrote),target:before.target}}const barrierCopies=new Map(finalVerifications.flatMap(({scope:scope3,verification})=>verification._tag==="Verified"?[[scope3,verification.copy]]:[]));const activeLegacyCopies=new Map(scopes.map((scope3)=>[scope3,legacyCopiesFor(finalBarrier,scope3).filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent))]));const unrelatedLegacyCopies=new Map(scopes.map((scope3)=>[scope3,unrelatedLegacyResiduals(legacyCopiesFor(finalBarrier,scope3),input2.activeAgent)]));const skillsCli=yield*SkillsCli;const refusedScopes=new Set;const lostBarrierScopes=new Set;const reportedLegacyScopes=new Set;for(const scope3 of scopes){if(!(activeLegacyCopies.get(scope3)??[]).some((copy3)=>copy3.boundAgents.some((agent)=>agent!==input2.activeAgent))){continue}refusedScopes.add(scope3);actions.push({_tag:"LegacyRemovalRefused",legacyReason:"SharedResidualUnverifiable",reason:"ResidualBindingsUnverifiable",retry:migrationRetry(scope3,input2,before.target,"removal",scopes),scope:scope3,verification:finalBarrier})}const removalScopes=scopes.filter((scope3)=>(activeLegacyCopies.get(scope3)??[]).length>0);for(const scope3 of removalScopes){const scopeIndex=scopes.indexOf(scope3);if(refusedScopes.has(scope3)){continue}const remove7=yield*result2(skillsCli.remove({agent:input2.activeAgent,cwd:operatorSkillScopeCwd(scope3,input2),name:"dp-cli",scope:scope3==="global"?"global":"project"}));const retry5=migrationRetry(scope3,input2,before.target,"removal",scopes);const context4={activeLegacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target:before.target,unrelatedLegacyCopies};if(isFailure2(remove7)){const failureResult=yield*handleFailedLegacyRemoval(context4,remove7.failure);wrote||=failureResult.wrote;actions.push(...failureResult.actions);continue}wrote=true;actions.push(...yield*handleSuccessfulLegacyRemoval(context4))}return{_tag:"Completed",actions,before,reload:reloadGuidance(wrote),target:before.target}});var migrateLegacyOperatorSkill=fn2("OperatorSkillLifecycle.migrate")(function*migrateLegacyOperatorSkill2(input2){return yield*migrateLegacyOperatorSkillPolicy(input2)});var retryLegacyOperatorSkillMigration=fn2("OperatorSkillLifecycle.retryMigration")(function*retryLegacyOperatorSkillMigration2(retry5,currentInput){return yield*migrateLegacyOperatorSkillPolicy({...retry5.input,activeCliVersion:currentInput.activeCliVersion},retry5.affectedScopes,retry5.target,retry5.phase)});var migrationRetrySchema=Struct({affectedScopes:ArraySchema(Literals(["global","project-local"])),input:Struct({activeAgent:String5,activeCliVersion:String5,cwd:String5,projectRoot:String5}),operation:Literal2("migrate"),phase:Literals(["barrier","preflight","removal","replacement"]),scope:Literals(["global","project-local"]),target:Struct({cliCompatibility:Struct({maximumExclusive:String5,minimum:String5}),contentManifest:ArraySchema(Struct({path:String5,sha256:String5})),revision:String5,source:String5,version:String5})});var mutationRetrySchema=Struct({input:Struct({activeAgent:String5,activeCliVersion:String5,cwd:String5,projectRoot:String5}),operation:Literals(["install","update"]),scope:Literals(["global","project-local"]),target:migrationRetrySchema.fields.target});var encodeMigrationRetry=(retry5)=>Buffer.from(JSON.stringify(retry5),"utf-8").toString("base64url");var decodeMigrationRetry=(token)=>try_3({catch:()=>new InvalidMigrationRetry({message:"Migration retry token is invalid or stale."}),try:()=>decodeUnknownSync2(migrationRetrySchema)(JSON.parse(Buffer.from(token,"base64url").toString("utf-8")))});var encodeMutationRetry=(retry5)=>Buffer.from(JSON.stringify(retry5),"utf-8").toString("base64url");var decodeMutationRetry=(token)=>try_3({catch:()=>new InvalidMutationRetry({message:"Operator mutation retry token is invalid or stale."}),try:()=>decodeUnknownSync2(mutationRetrySchema)(JSON.parse(Buffer.from(token,"base64url").toString("utf-8")))});var targetIdentity2=(target)=>JSON.stringify([target.source,target.version,target.revision,target.cliCompatibility,target.contentManifest]);var retryOperatorSkillMutation=(retry5,action2,currentInput)=>gen2(function*executeMutationRetry(){if(retry5.operation!==action2){return yield*new InvalidMutationRetry({message:`Operator mutation retry is for ${retry5.operation}, not ${action2}.`})}const retryInput={...retry5.input,activeCliVersion:currentInput.activeCliVersion};const before=yield*inspectOperatorSkillLifecycle(retryInput);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,operation:retry5.operation,reload:{_tag:"NotRequired"}}}if(targetIdentity2(before.target)!==targetIdentity2(retry5.target)){return yield*new InvalidMutationRetry({message:"Operator mutation retry target changed; rerun the operator command."})}if(retry5.operation==="install"&&retry5.scope!=="global"){return yield*new InvalidMutationRetry({message:"Operator install retry scope changed; rerun the operator command."})}const inspection=inspectionFor(before,retry5.scope);if(inspection===undefined){return yield*new InvalidMutationRetry({message:"Operator mutation retry scope changed; rerun the operator command."})}if(inspectionScopeIsUnknown(inspection)){return{_tag:"Completed",actions:[{_tag:"Failed",failure:inspection.failure,operation:retry5.operation,phase:"inspection",retry:retry5,scope:retry5.scope}],before,operation:retry5.operation,reload:{_tag:"NotRequired"},target:retry5.target}}const updateIsAuthorized=retry5.operation==="update"&&inspectionDetectedOperatorSkill(inspection);const installIsAuthorized=retry5.operation==="install";if(!updateIsAuthorized&&!installIsAuthorized){return yield*new InvalidMutationRetry({message:"Operator mutation retry state changed; rerun the operator command."})}const result4=yield*ensureAndVerifyOperatorSkillScope(retry5.scope,retryInput,retry5.target);let mutationAction;if(result4._tag==="Failed"){mutationAction={...result4,operation:retry5.operation,phase:"write",retry:retry5}}else if(result4._tag==="Unverified"){mutationAction={...result4,operation:retry5.operation,retry:retry5}}else{mutationAction={...result4,operation:retry5.operation}}return{_tag:"Completed",actions:[mutationAction],before,operation:retry5.operation,reload:result4._tag==="Failed"?{_tag:"NotRequired"}:{_tag:"ReloadRequired",skill:"hi-cli"},target:retry5.target}});var executeOperatorAction=fn2("OperatorSkill.execute")(function*executeOperatorAction2(request3){const{action:action2,input:input2}=request3;if(action2==="status"){const lifecycle2=yield*inspectOperatorSkillLifecycle(input2);return{action:action2,lifecycle:lifecycle2}}if(action2==="install"||action2==="update"){const lifecycle2=request3.mutationRetryToken===undefined?yield*action2==="install"?installOperatorSkill(input2):updateOperatorSkill(input2):yield*decodeMutationRetry(request3.mutationRetryToken).pipe(flatMap4((retry5)=>retryOperatorSkillMutation(retry5,action2,input2)));return{action:action2,lifecycle:lifecycle2}}const lifecycle=request3.migrationRetryToken===undefined?yield*migrateLegacyOperatorSkill(input2):yield*decodeMigrationRetry(request3.migrationRetryToken).pipe(flatMap4((retry5)=>retryLegacyOperatorSkillMigration(retry5,input2)));return{action:action2,lifecycle}});var operatorCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator status",summary:"Inspect effective operator skill state."}],group:"commands",interaction:"none",name:"operator",options:[],outputModes:["interactive","plain","json"],summary:"Manage the Harness operator skill."});var operatorStatusCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator status",summary:"Run operator status."}],group:"operator",interaction:"optional",name:"status",options:[],outputModes:["interactive","plain","json"],summary:"Show immutable hi-cli identity and effective installed state."});var operatorInstallCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator install",summary:"Run operator install."}],group:"operator",interaction:"optional",name:"install",options:[],outputModes:["interactive","plain","json"],summary:"Ensure and verify the global hi-cli operator skill."});var operatorUpdateCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator update",summary:"Run operator update."}],group:"operator",interaction:"optional",name:"update",options:[],outputModes:["interactive","plain","json"],summary:"Update and verify every detected hi-cli scope."});var operatorMigrateCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator migrate",summary:"Run operator migrate."}],group:"operator",interaction:"optional",name:"migrate",options:[],outputModes:["interactive","plain","json"],summary:"Verify replacements before removing legacy dp-cli copies."});var operatorActionMetadata=(action2)=>{switch(action2){case"status":{return operatorStatusCommandMetadata}case"install":{return operatorInstallCommandMetadata}case"update":{return operatorUpdateCommandMetadata}case"migrate":{return operatorMigrateCommandMetadata}default:{return action2}}};var publicOperatorFailure=(value5)=>{if(typeof value5!=="object"||value5===null){return value5}const failure=value5;return Object.fromEntries(["_tag","agent","exitCode","message","operation","reason","reportedAgents","scope","skillName"].filter((key)=>failure[key]!==undefined).map((key)=>[key,failure[key]]))};var operatorFact=(value5)=>JSON.stringify(value5,(key,nestedValue)=>{if(key==="stderr"||key==="stack"||key==="cause"){return}return key==="failure"?publicOperatorFailure(nestedValue):nestedValue});var quoteShellArgument=(value5)=>`'${value5.replaceAll("'",`'"'"'`)}'`;var quotePowerShellLiteral=(value5)=>`'${value5.replaceAll("'","''")}'`;var windowsPowerShellCommand=(statements)=>`powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(statements.join("; "),"utf16le").toString("base64")}`;var mutationRetryCommand=(action2,platform)=>{const retry5=encodeMutationRetry(action2.retry);if(platform==="win32"){return windowsPowerShellCommand([`Set-Location -LiteralPath ${quotePowerShellLiteral(action2.retry.input.cwd)}`,`$env:HI_OPERATOR_MUTATION_RETRY = ${quotePowerShellLiteral(retry5)}`,`$env:HI_OPERATOR_AGENT = ${quotePowerShellLiteral(action2.retry.input.activeAgent)}`,`& hi operator ${action2.retry.operation}`])}return`cd -- ${quoteShellArgument(action2.retry.input.cwd)} && HI_OPERATOR_MUTATION_RETRY=${retry5} HI_OPERATOR_AGENT=${quoteShellArgument(action2.retry.input.activeAgent)} hi operator ${action2.retry.operation}`};var migrationRetryCommand=(action2,platform)=>{const retry5=encodeMigrationRetry(action2.retry);if(platform==="win32"){return windowsPowerShellCommand([`Set-Location -LiteralPath ${quotePowerShellLiteral(action2.retry.input.cwd)}`,`$env:HI_OPERATOR_MIGRATION_RETRY = ${quotePowerShellLiteral(retry5)}`,`$env:HI_OPERATOR_AGENT = ${quotePowerShellLiteral(action2.retry.input.activeAgent)}`,"& hi operator migrate"])}return`cd -- ${quoteShellArgument(action2.retry.input.cwd)} && HI_OPERATOR_MIGRATION_RETRY=${retry5} HI_OPERATOR_AGENT=${quoteShellArgument(action2.retry.input.activeAgent)} hi operator migrate`};var publicTarget=(target)=>({cliCompatibility:target.cliCompatibility,revision:target.revision,source:target.source,version:target.version});var statusFromChangesAndIssues=(changeCount,issueCount)=>{if(issueCount>0){return changeCount>0?"partial":"failed"}return changeCount>0?"success":"no-op"};var operatorStatusOperationResult=(lifecycle)=>{if(lifecycle._tag==="TargetResolutionFailed"){return{changes:[],degradations:[],issues:[{action:"status",code:`operator-target-${lifecycle.resolution._tag}`,kind:"handled-failure",subject:operatorFact(lifecycle.resolution)}],nextActions:[{kind:"retry",subject:"operator:status"}],status:"failed",warnings:[]}}const changes=[{action:"operator-target",state:"completed",subject:operatorFact(publicTarget(lifecycle.target))},...lifecycle.inspections.map((inspection)=>({action:"operator-inspection",state:"completed",subject:operatorFact(inspection)})),{action:"operator-installed-state",state:"completed",subject:operatorFact(lifecycle.installed)},{action:"operator-legacy-copies",state:"completed",subject:operatorFact(lifecycle.legacy)}];let issues=[];if(lifecycle.installed._tag==="DetectionFailed"){issues=lifecycle.installed.failures.map((failure)=>({action:"status",code:"operator-detection-failed",errorMessage:failure.message,kind:"handled-failure",subject:operatorFact(failure)}))}else if(lifecycle.installed._tag==="Ambiguous"){issues=[{action:"status",code:"operator-installed-ambiguous",kind:"conflict",subject:operatorFact(lifecycle.installed.candidates)}]}let status2="success";if(lifecycle.installed._tag==="Ambiguous"){status2="conflict"}else if(lifecycle.installed._tag==="DetectionFailed"){status2="failed"}return{changes,degradations:[],issues,nextActions:issues.length===0?[{kind:"none"}]:[lifecycle.installed._tag==="Ambiguous"?{kind:"resolve",subject:"operator:status"}:{kind:"retry",subject:"operator:status"}],status:status2,warnings:[]}};var publicVerifiedMutationAction=(action2)=>({_tag:action2._tag,copy:action2.copy,operation:action2.operation,scope:action2.scope});var publicFailedMutationAction=(action2)=>({_tag:action2._tag,operation:action2.operation,phase:action2.phase,retry:action2.retry,scope:action2.scope});var publicAlreadyVerifiedMutationAction=(action2)=>({_tag:action2._tag,copy:action2.copy,operation:action2.operation,scope:action2.scope});var publicUnverifiedMutationAction=(action2)=>({_tag:action2._tag,operation:action2.operation,reason:action2.reason,retry:action2.retry,scope:action2.scope});var operatorMutationOperationResult=(lifecycle,platform=process.platform)=>{if(lifecycle._tag==="TargetResolutionFailed"){return{changes:[],degradations:[],issues:[{action:lifecycle.operation,code:`operator-target-${lifecycle.before.resolution._tag}`,kind:"handled-failure",subject:operatorFact(lifecycle.before.resolution)}],nextActions:[{kind:"retry",subject:`operator:${lifecycle.operation}`}],status:"failed",warnings:[]}}const completed=lifecycle.actions.filter((action2)=>action2._tag==="Verified");const failed=lifecycle.actions.filter((action2)=>action2._tag==="Failed");const alreadyVerified=lifecycle.actions.filter((action2)=>action2._tag==="AlreadyVerified");const unverified=lifecycle.actions.filter((action2)=>action2._tag==="Unverified");const retryActions=[...failed,...unverified];const changes=completed.map((action2)=>({action:action2.operation,state:"completed",subject:operatorFact(publicVerifiedMutationAction(action2))}));const noInstalledUpdate=lifecycle.operation==="update"&&lifecycle.actions.length===0;const issues=[...failed.map((action2)=>({action:action2.operation,code:`operator-${action2.operation}-${action2._tag}`,errorMessage:action2.failure.message,kind:"handled-failure",subject:operatorFact(publicFailedMutationAction(action2))})),...unverified.map((action2)=>({action:action2.operation,code:`operator-${action2.operation}-${action2._tag}`,errorMessage:action2.failure?.message,kind:"handled-failure",subject:operatorFact(publicUnverifiedMutationAction(action2))})),...noInstalledUpdate?[{action:"update",code:"operator-update-no-installed-scope",kind:"handled-failure",subject:operatorFact({before:lifecycle.before,target:publicTarget(lifecycle.target)})}]:[]];let nextActions=[{kind:"none"}];if(noInstalledUpdate){nextActions=[{kind:"run",subject:"hi operator install"}]}else if(retryActions.length>0){nextActions=retryActions.map((action2)=>({kind:"run",subject:mutationRetryCommand(action2,platform)}))}return{changes,degradations:[],issues,nextActions,status:statusFromChangesAndIssues(changes.length,issues.length),warnings:[...alreadyVerified.map((action2)=>({code:`operator-${action2.operation}-${action2._tag}`,subject:operatorFact(publicAlreadyVerifiedMutationAction(action2))})),...lifecycle.reload._tag==="ReloadRequired"?[{code:"reload-required",subject:lifecycle.reload.skill}]:[]]}};var migrationContext=(lifecycle)=>{if(lifecycle._tag==="RetryTargetChanged"){return{expected:publicTarget(lifecycle.expected),observed:publicTarget(lifecycle.observed),result:{_tag:lifecycle._tag}}}if(lifecycle._tag==="TargetResolutionFailed"){return{resolution:lifecycle.before.resolution,result:{_tag:lifecycle._tag}}}return{before:{inspections:lifecycle.before.inspections,installed:lifecycle.before.installed,legacy:lifecycle.before.legacy},result:{_tag:lifecycle._tag,...lifecycle._tag==="Refused"?{reason:lifecycle.reason}:{}},target:publicTarget(lifecycle.target)}};var migrationFailure=(action2)=>("failure"in action2)?action2.failure:undefined;var operatorMigrationOperationResult=(lifecycle,platform=process.platform)=>{if(lifecycle._tag==="RetryTargetChanged"){return{changes:[],degradations:[],issues:[{action:"migrate",code:"operator-migrate-RetryTargetChanged",kind:"conflict",subject:operatorFact(migrationContext(lifecycle))}],nextActions:[{kind:"retry",subject:"operator:migrate"}],status:"conflict",warnings:[]}}if(lifecycle._tag==="TargetResolutionFailed"){return{changes:[],degradations:[],issues:[{action:"migrate",code:`operator-target-${lifecycle.before.resolution._tag}`,kind:"handled-failure",subject:operatorFact(migrationContext(lifecycle))}],nextActions:[{kind:"retry",subject:"operator:migrate"}],status:"failed",warnings:[]}}const completed=lifecycle.actions.filter((action2)=>action2._tag==="LegacyRemoved"||action2._tag==="ReplacementVerified"&&action2.wrote);const noOp=lifecycle.actions.filter((action2)=>action2._tag==="ReplacementVerified"&&!action2.wrote);const failed=lifecycle.actions.filter((action2)=>action2._tag!=="LegacyRemoved"&&action2._tag!=="ReplacementVerified");const context4=migrationContext(lifecycle);const changes=completed.map((action2)=>({action:"migrate",state:"completed",subject:operatorFact(action2)}));const issues=failed.map((action2)=>{const failure=migrationFailure(action2);return{action:"migrate",code:`operator-migrate-${action2._tag}`,...failure===undefined?{}:{errorMessage:failure.message},kind:"handled-failure",subject:operatorFact({action:action2,...context4})}});if(lifecycle._tag==="Refused"&&issues.length===0){issues.push({action:"migrate",code:"operator-migrate-Refused",kind:"handled-failure",subject:operatorFact(context4)})}let nextActions=[{kind:"none"}];if(failed.length>0){nextActions=failed.map((action2)=>({kind:"run",subject:migrationRetryCommand(action2,platform)}))}else if(issues.length>0){nextActions=[{kind:"retry",subject:"operator:migrate"}]}return{changes,degradations:[],issues,nextActions,status:statusFromChangesAndIssues(changes.length,issues.length),warnings:[{code:"operator-migrate-context",subject:operatorFact(context4)},...noOp.map((action2)=>({code:"operator-migrate-ReplacementVerified",subject:operatorFact(action2)})),...lifecycle.reload._tag==="ReloadRequired"?[{code:"reload-required",subject:lifecycle.reload.skill}]:[]]}};var executeOperatorCommand=(action2,operation=runOperatorSkillApplication,interaction)=>gen2(function*runOperatorCommand(){const selectAgent=interaction?.mode==="interactive"?interaction.prompt.readLine("Enter the Skills CLI agent name: "):undefined;const result4=yield*operation(action2,selectAgent);if(result4.action==="status"){return operatorStatusOperationResult(result4.lifecycle)}if(result4.action==="migrate"){return operatorMigrationOperationResult(result4.lifecycle)}return operatorMutationOperationResult(result4.lifecycle)}).pipe(catchTag2("InvalidMigrationRetry",(failure)=>fail6(new CliValidationError({message:failure.message,recoveryCommand:"unset HI_OPERATOR_MIGRATION_RETRY; hi operator migrate"}))),catchTag2("InvalidOperatorContext",(failure)=>fail6(new CliValidationError({message:failure.message}))),catchTag2("InvalidMutationRetry",(failure)=>fail6(new CliValidationError({message:failure.message,recoveryCommand:`unset HI_OPERATOR_MUTATION_RETRY; hi operator ${action2}`}))));var makeOperatorAction=(action2,operation=runOperatorSkillApplication)=>{const metadata=operatorActionMetadata(action2);return exports_Command.make(metadata.name,{},()=>gen2(function*runOperatorAction(){const mode=yield*SelectedOutputMode;const prompt=yield*CliPrompt;return yield*captureCommandResult(executeOperatorCommand(action2,operation,{mode,prompt}))})).pipe(withCommandMetadata(metadata))};var operatorRootOperationResult={changes:[],degradations:[],issues:[],nextActions:[{kind:"run",subject:"hi operator status"},{kind:"run",subject:"hi operator install"},{kind:"run",subject:"hi operator update"},{kind:"run",subject:"hi operator migrate"}],status:"no-op",warnings:[{code:"operator-command-summary",subject:"Manage the Harness operator skill."}]};var operatorRootOperation=succeed6(operatorRootOperationResult);var operatorSubcommands=[makeOperatorAction("status"),makeOperatorAction("install"),makeOperatorAction("update"),makeOperatorAction("migrate")];var operatorCommandRoot=exports_Command.make(operatorCommandMetadata.name,{},()=>captureCommandResult(operatorRootOperation)).pipe(withCommandMetadata(operatorCommandMetadata));var operatorCommand=operatorCommandRoot.pipe(exports_Command.withSubcommands(operatorSubcommands));class ReportConfigurationUnavailable extends TaggedErrorClass()("@punks/cli/report-submission/ReportConfigurationUnavailable",{cause:Defect(),message:String5,operation:Literal2("resolve-control-plane-url")}){}class ReportSubmissionResponseInvalid extends TaggedErrorClass()("@punks/cli/report-submission/ReportSubmissionResponseInvalid",{cause:Defect(),message:String5,operation:Literal2("validate-submission-response")}){}class ReportInputInvalid extends TaggedErrorClass()("@punks/cli/report-submission/ReportInputInvalid",{cause:Defect(),field:Literal2("body"),message:String5,operation:Literal2("validate-report-input")}){}class ReportSubmissionOperationFailure extends TaggedErrorClass()("@punks/cli/report-submission/ReportSubmissionOperationFailure",{cause:Defect(),message:String5,operation:Literals(["record-submitted","submit-report"])}){}var ReportSubmissionOperations=Service("@punks/cli/features/report-submission/ReportSubmissionOperations");var nonEmpty=(value5)=>{const trimmed=value5.trim();if(trimmed.length===0){const cause=new Error("Missing body. Pass a non-empty value.");return fail6(new ReportInputInvalid({cause,field:"body",message:cause.message,operation:"validate-report-input"}))}return succeed6(trimmed)};var csvLabels=(value5)=>value5===undefined?[]:value5.split(",").map((label)=>label.trim()).filter((label)=>label.length>0);var buildHarnessReport=fn2("ReportSubmission.build")(function*buildReport({title,body,message,type:type2,severity,area,repoRoot,skillPack,command,expected,actual,steps,labels}){const operations=yield*ReportSubmissionOperations;const validBody=yield*nonEmpty(body??message??[actual,expected,steps].filter(Boolean).join(`
343
+ `};var initializeProjectSettings=fn2("ProjectSettings.initialize")(function*initializeProjectSettings2(fileSystem,rootDirectory,initialization){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const settingsDirectory=fileSystem.joinPath(rootDirectory,".devpunks");const settingsDirectoryExisted=yield*fileSystem.directoryExists(settingsDirectory);const expectedContent=projectSettingsInitializationContent(initialization);const created=yield*fileSystem.createTextFile(settingsPath,expectedContent);if(!created){return yield*new ProjectSettingsAlreadyExists({message:`Project settings already exist at ${settingsPath}.`,path:settingsPath})}const read3=yield*readProjectSettings(fileSystem,rootDirectory).pipe(result2);if(isSuccess2(read3)){return read3.success}yield*gen2(function*rollbackProjectSettingsInitialization(){yield*fileSystem.removeTextFileIfContent(settingsPath,expectedContent);if(!settingsDirectoryExisted){yield*fileSystem.removeEmptyDirectory(settingsDirectory)}}).pipe(result2);return yield*read3.failure});var rollbackProjectSettingsInitialization=fn2("ProjectSettings.rollbackInitialization")(function*rollbackProjectSettingsInitialization2(fileSystem,rootDirectory,rollback){const settingsPath=fileSystem.joinPath(rootDirectory,projectSettingsFile);const settingsDirectory=fileSystem.joinPath(rootDirectory,".devpunks");const removed=yield*fileSystem.removeTextFileIfContent(settingsPath,projectSettingsInitializationContent(rollback.initialization));if(rollback.removeSettingsDirectory){yield*fileSystem.removeEmptyDirectory(settingsDirectory)}return removed});var ProjectSettings=Service("@punks/cli/ProjectSettings");var ProjectSettingsDefault=effect(ProjectSettings,gen2(function*ProjectSettingsDefault2(){const fileSystem=yield*ProjectSettingsFileSystem;return{infer:(rootDirectory)=>inferProjectSettings(fileSystem,rootDirectory),initialize:(rootDirectory,initialization)=>initializeProjectSettings(fileSystem,rootDirectory,initialization),read:(rootDirectory)=>readProjectSettings(fileSystem,rootDirectory),rollbackInitialization:(rootDirectory,rollback)=>rollbackProjectSettingsInitialization(fileSystem,rootDirectory,rollback),write:(rootDirectory,change)=>writeProjectSettings(fileSystem,rootDirectory,change)}}));import{execFileSync}from"node:child_process";import{accessSync,constants as constants2,existsSync as existsSync3,mkdirSync as mkdirSync2,readFileSync as readFileSync4,writeFileSync as writeFileSync2}from"node:fs";import{homedir}from"node:os";import path9 from"node:path";class ToolManagementFailure extends TaggedErrorClass()("@punks/cli/integrations/tool-management/ToolManagementFailure",{cause:Defect(),message:String5,operation:Literals(["ensure-required-tool","infer-repo-settings"])}){}var toolManagementFailure=(operation,message)=>new ToolManagementFailure({cause:new Error(message),message,operation});var repoSettingsFile=".devpunks/settings.json";var repositoryManagerTools2={"azure-devops":["az"],bitbucket:[],github:["gh"],gitlab:["glab"]};var repositoryManagers2=new Set(Object.keys(repositoryManagerTools2));var backlogProviders2=new Set(["azure-devops","github","linear","monday"]);var assetProviders=new Set([...backlogProviders2,...repositoryManagers2]);var requiredToolsForRepositoryManager2=(repositoryManager)=>repositoryManagerTools2[repositoryManager];var reconcileRepositoryManagerTools=({previousRepositoryManager,requiredTools,repositoryManager})=>{const previousManagerTools=new Set(requiredToolsForRepositoryManager2(previousRepositoryManager));return[...new Set([...requiredTools.filter((tool)=>!previousManagerTools.has(tool)),...requiredToolsForRepositoryManager2(repositoryManager)])].toSorted()};var isRepositoryManager=(value5)=>typeof value5==="string"&&repositoryManagers2.has(value5);var isBacklogProvider=(value5)=>typeof value5==="string"&&backlogProviders2.has(value5);var isAssetProvider=(value5)=>typeof value5==="string"&&assetProviders.has(value5);var isStringArray=(value5)=>Array.isArray(value5)&&value5.every((tool)=>typeof tool==="string");var normalizeRepoSettings=(value5)=>{if(typeof value5!=="object"||value5===null){return null}const record3=value5;if(!isBacklogProvider(record3.backlogProvider)||!isAssetProvider(record3.assetProviderSlug)||!isRepositoryManager(record3.repositoryManager)||!isStringArray(record3.requiredTools)){return null}return Object.fromEntries([["backlogProvider",record3.backlogProvider],["assetProviderSlug",record3.assetProviderSlug],...typeof record3.backlogProjectUrl==="string"?[["backlogProjectUrl",record3.backlogProjectUrl]]:[],...typeof record3.baselineVersion==="string"?[["baselineVersion",record3.baselineVersion]]:[],...typeof record3.cliVersion==="string"?[["cliVersion",record3.cliVersion]]:[],["repositoryManager",record3.repositoryManager],["requiredTools",[...new Set([...record3.requiredTools,...requiredToolsForRepositoryManager2(record3.repositoryManager)])].toSorted()]])};var readRepoSettings=(rootDirectory)=>{const settingsPath=path9.join(rootDirectory,repoSettingsFile);if(!existsSync3(settingsPath)){return null}return normalizeRepoSettings(JSON.parse(readFileSync4(settingsPath,"utf-8")))};var commandExistsOnPath=(command,env={},platform=process.platform)=>{const pathValue=env.PATH??env.Path;if(pathValue===undefined||pathValue.length===0){return false}const isWindows=platform==="win32";const pathSeparator=isWindows?";":":";const pathEntries=pathValue.split(pathSeparator).filter((entry)=>entry.length>0);const pathExtensions=isWindows?(env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter((extension)=>extension.length>0):[""];const commandExtensions=isWindows&&path9.extname(command).length===0?pathExtensions:[""];const hasPathSegment=command.includes("/")||command.includes("\\");const candidates=(hasPathSegment?[""]:pathEntries).flatMap((entry)=>commandExtensions.map((extension)=>hasPathSegment?`${command}${extension}`:path9.join(entry,`${command}${extension}`)));return candidates.some((candidate)=>{try{accessSync(candidate,isWindows?constants2.F_OK:constants2.X_OK);return true}catch{return false}})};var makeToolCommandRuntime=(environment)=>({commandExists:(command)=>commandExistsOnPath(command,environment),cwd:homedir(),env:environment,execFile:(command,args2,options4)=>{execFileSync(command,[...args2],{cwd:options4?.cwd,env:environment,stdio:options4?.stdio==="inherit"?["ignore","inherit","inherit"]:"ignore"})},execFileOutput:(command,args2,options4)=>execFileSync(command,[...args2],{cwd:options4?.cwd,encoding:"utf-8",env:environment})});var defaultRuntime=makeToolCommandRuntime({});var defaultToolBootstrapOptions={mode:"repair",stdio:"inherit"};var detectGlobalPackageManager=(runtime)=>{if(runtime.commandExists("bun")){return"bun"}if(runtime.commandExists("pnpm")){return"pnpm"}if(runtime.commandExists("npm")){return"npm"}return null};var globalInstallCommandFor=(packageManager,packageName)=>{switch(packageManager){case"bun":{return["bun","add","-g",packageName]}case"pnpm":{return["pnpm","add","-g",packageName]}case"npm":{return["npm","install","-g",packageName]}default:{return packageManager}}};var parseVersionParts=(value5)=>{const match8=value5.match(/\d+(?:\.\d+){0,2}/u);if(match8===null){return null}const[matchedVersion]=match8;return matchedVersion===undefined?null:matchedVersion.split(".").map((part)=>Number.parseInt(part,10))};var compareVersions=(actual,minimum)=>{const length=Math.max(actual.length,minimum.length);for(let index2=0;index2<length;index2+=1){const actualPart=actual[index2]??0;const minimumPart=minimum[index2]??0;if(actualPart>minimumPart){return 1}if(actualPart<minimumPart){return-1}}return 0};var isMinimumVersionSatisfied=(tool,runtime,cwd)=>{if(tool.minimumVersion===undefined||tool.versionCommand===undefined){return true}const[command,...args2]=tool.versionCommand;if(command===undefined||runtime.execFileOutput===undefined){return true}const actual=parseVersionParts(runtime.execFileOutput(command,args2,{cwd}));const minimum=parseVersionParts(tool.minimumVersion);if(actual===null||minimum===null){throw toolManagementFailure("ensure-required-tool",`Cannot verify required tool version from \`${tool.versionCommand.join(" ")}\`.`)}return compareVersions(actual,minimum)>=0};var commandCandidateValue=(candidate,env)=>{if(typeof candidate==="string"){return candidate}const value5=env[candidate.env];return value5===undefined||value5.length===0?null:value5};var shouldSkipEnsureCommands=(tool,runtime)=>tool.skipEnsureCommandsIfAnyCommandExists?.some((candidate)=>{const command=commandCandidateValue(candidate,runtime.env??{});return command!==null&&runtime.commandExists(command)})??false;var manualProviderCliTools=Object.fromEntries([...new Set(Object.values(repositoryManagerTools2).flat())].map((toolId)=>[toolId,{ensureCommands:[],manual:true,requiredBins:[]}]));var installTool=({cwd,installTarget,runtime,stdio,toolId,versionContract})=>{const packageManager=detectGlobalPackageManager(runtime);if(packageManager===null){throw toolManagementFailure("ensure-required-tool","Cannot install required tools because no supported global package manager was found on PATH. Install Bun, pnpm, or npm first.")}if(installTarget===undefined){throw toolManagementFailure("ensure-required-tool",`Required tool \`${toolId}\` cannot be installed automatically.`)}const[command,...args2]=globalInstallCommandFor(packageManager,installTarget);runtime.execFile(command,args2,{cwd,stdio});if(!runtime.commandExists(toolId)){throw toolManagementFailure("ensure-required-tool",`Tried to install required tool \`${toolId}\`, but the binary is still not available on PATH afterwards.`)}if(!isMinimumVersionSatisfied(versionContract,runtime,cwd)){throw toolManagementFailure("ensure-required-tool",`Tried to install required tool \`${toolId}\`, but the installed version does not satisfy ${versionContract.minimumVersion}.`)}};var ensureToolsInstalled=(toolIds,baseline=bundledBaseline,runtime=defaultRuntime,options4=defaultToolBootstrapOptions)=>{const statuses=[];const toolCatalogById=Object.fromEntries(baseline.tools.map((tool)=>[tool.id,tool]));const cwd=runtime.cwd??homedir();for(const toolId of toolIds){const tool=toolCatalogById[toolId]===undefined?manualProviderCliTools[toolId]:{...toolCatalogById[toolId],manual:false};if(tool===undefined){throw toolManagementFailure("ensure-required-tool",`Unknown required tool \`${toolId}\` in baseline.`)}const missingPrerequisites=tool.requiredBins.filter((command)=>!runtime.commandExists(command));if(missingPrerequisites.length>0){throw toolManagementFailure("ensure-required-tool",`Cannot install required tool \`${toolId}\` because ${missingPrerequisites.join(", ")} is not available on PATH.`)}const versionContract=tool;const alreadyPresent=runtime.commandExists(toolId)&&isMinimumVersionSatisfied(versionContract,runtime,cwd);const refreshLatest=options4.mode==="refresh-latest"&&!tool.manual;if(!alreadyPresent&&tool.manual){throw toolManagementFailure("ensure-required-tool",`Required external tool \`${toolId}\` is not available on PATH. Install it before running scaffold/update workflows.`)}if(!alreadyPresent||refreshLatest){const installTarget=refreshLatest?tool.latestInstallTarget:tool.packageName;installTool({cwd,installTarget,runtime,stdio:options4.stdio,toolId,versionContract})}const ensureCommandContract=tool;if(!shouldSkipEnsureCommands(ensureCommandContract,runtime)){for(const[command,...args2]of tool.ensureCommands){runtime.execFile(command,args2,{cwd,stdio:options4.stdio})}}statuses.push({status:alreadyPresent&&!refreshLatest?"already-present":"installed",toolId})}return statuses};var errorMessage=(cause)=>cause instanceof Error?cause.message:String(cause);var errorStack=(cause)=>cause instanceof Error?cause.stack??cause.message:String(cause);var ensureToolsInstalledBestEffort=(toolIds,baseline=bundledBaseline,runtime=defaultRuntime,options4=defaultToolBootstrapOptions)=>toolIds.flatMap((toolId)=>{try{return ensureToolsInstalled([toolId],baseline,runtime,options4)}catch(error2){return[Object.fromEntries([["toolId",toolId],["status","failed"],["errorMessage",errorMessage(error2)],["errorStack",errorStack(error2)]])]}});var providerChoices=[{title:"GitHub Projects and Issues",value:"github"},{title:"Linear",value:"linear"},{title:"Azure DevOps",value:"azure-devops"},{title:"monday.com",value:"monday"}];var assetChoices=[...providerChoices,{title:"GitLab",value:"gitlab"},{title:"Bitbucket",value:"bitbucket"}];var repositoryChoices=[{title:"GitHub",value:"github"},{title:"GitLab",value:"gitlab"},{title:"Azure DevOps",value:"azure-devops"},{title:"Bitbucket",value:"bitbucket"}];var validProjectUrl=(input2)=>{const value5=input2.trim();try{const url2=new URL(value5);return url2.protocol==="http:"||url2.protocol==="https:"?value5:null}catch{return null}};var selectRepoSettings=({prompt,defaults:defaults2,retryCommand})=>gen2(function*selectSettings(){const backlogProvider=yield*prompt.singleSelect({choices:providerChoices,defaultValue:defaults2?.backlogProvider??"github",message:"Select backlog provider"});const assetProviderSlug=yield*prompt.singleSelect({choices:assetChoices,defaultValue:defaults2?.assetProviderSlug??backlogProvider,message:"Select asset provider"});const repositoryManager=yield*prompt.singleSelect({choices:repositoryChoices,defaultValue:defaults2?.repositoryManager??"github",message:"Select repository manager"});const input2=yield*prompt.readLine(`Backlog project URL${defaults2?.backlogProjectUrl?` [${defaults2.backlogProjectUrl}]`:""}: `);const backlogProjectUrl=validProjectUrl(input2||defaults2?.backlogProjectUrl||"");if(backlogProjectUrl===null){return yield*fail6(new CliPromptError({message:`Backlog project URL must be an absolute HTTP(S) URL. Rerun \`${retryCommand}\`.`}))}return{assetProviderSlug,backlogProjectUrl,backlogProvider,repositoryManager}});var ensureCommandMetadata=declareCommandMetadata({examples:[{command:"hi ensure",summary:"Reconfigure current project settings."}],group:"commands",interaction:"required",name:"ensure",options:[],outputModes:["interactive","plain"],summary:"Reconfigure backlog, asset, repository, and backlog project URL settings only."});var mapSettingsError=(error2)=>new CliPromptError({message:error2._tag==="ProjectSettingsMissing"?`${projectSettingsFile} was not found. Run \`hi init\` first.`:error2.message});var runEnsure=({rootDirectory,prompt})=>gen2(function*ensureSettings(){const projectSettings=yield*ProjectSettings;const current=(yield*projectSettings.read(rootDirectory).pipe(mapError3(mapSettingsError))).settings;const selected=yield*selectRepoSettings({defaults:current,prompt,retryCommand:"hi ensure"});const requiredTools=reconcileRepositoryManagerTools({previousRepositoryManager:current.repositoryManager,repositoryManager:selected.repositoryManager,requiredTools:current.requiredTools});yield*projectSettings.write(rootDirectory,{_tag:"ReconfigurationChange",assetProviderSlug:selected.assetProviderSlug,...selected.backlogProjectUrl===undefined?{}:{backlogProjectUrl:selected.backlogProjectUrl},backlogProvider:selected.backlogProvider,repositoryManager:selected.repositoryManager,requiredTools}).pipe(mapError3(mapSettingsError));return{changes:[{action:"configure",state:"completed",subject:projectSettingsFile}],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"success",warnings:[]}});var executeEnsureCommand=(input2)=>captureCommandResult(runEnsure(input2));var ensureCommand=exports_Command.make(ensureCommandMetadata.name,{},()=>scoped2(gen2(function*runEnsureCommand(){const outputMode=yield*SelectedOutputMode;if(outputMode!=="interactive"){return yield*new CliValidationError({message:outputMode==="json"?"`hi ensure` requires interactive input and is unavailable in JSON mode.":"`hi ensure` requires interactive input and is unavailable when output is redirected.",recoveryCommand:"hi ensure"})}const prompt=yield*PromptLive;return yield*executeEnsureCommand({prompt,rootDirectory:process.cwd()})}))).pipe(withCommandMetadata(ensureCommandMetadata));class InvalidMigrationRetry extends TaggedErrorClass()("InvalidMigrationRetry",{message:String5}){}class InvalidMutationRetry extends TaggedErrorClass()("InvalidMutationRetry",{message:String5}){}class InvalidOperatorContext extends TaggedErrorClass()("InvalidOperatorContext",{message:String5}){}var SkillsCliScope=Literals(["project","global"]);var skillsCliFailureFields={agent:String5,message:String5,operation:Literals(["list","install","remove"]),scope:SkillsCliScope};var verifiedInstalledSkillSchema=Struct({agents:ArraySchema(String5),cliCompatibility:Struct({maximumExclusive:String5,minimum:String5}),name:String5,path:String5,revision:String5,scope:SkillsCliScope,source:String5,version:String5});var SkillsCliVerificationFailureReason=Literals(["unsafe-path","missing","unreadable","malformed","identity-mismatch"]);class SkillsCliVerificationFailure extends TaggedErrorClass()("SkillsCliVerificationFailure",{...skillsCliFailureFields,reason:SkillsCliVerificationFailureReason,skillName:String5,skillPath:String5,verifiedSkills:ArraySchema(verifiedInstalledSkillSchema)}){}class SkillsCliBindingFailure extends TaggedErrorClass()("SkillsCliBindingFailure",{...skillsCliFailureFields,reportedAgents:ArraySchema(String5),skillName:String5,verifiedSkills:ArraySchema(verifiedInstalledSkillSchema)}){}class SkillsCliExit extends TaggedErrorClass()("SkillsCliExit",{...skillsCliFailureFields,exitCode:Number6,stderr:String5}){}class SkillsCliMalformedOutput extends TaggedErrorClass()("SkillsCliMalformedOutput",{...skillsCliFailureFields,stdout:String5}){}class SkillsCliTimeout extends TaggedErrorClass()("SkillsCliTimeout",{...skillsCliFailureFields,timeoutMs:Number6}){}class SkillsCliUnavailable extends TaggedErrorClass()("SkillsCliUnavailable",{...skillsCliFailureFields,executable:String5}){}class SkillsCliUnsupportedVersion extends TaggedErrorClass()("SkillsCliUnsupportedVersion",{...skillsCliFailureFields,minimumVersion:String5,version:String5}){}var SkillsCli=Service("@punks/cli/features/operator-skill/SkillsCli");var OperatorSkillOperations=Service("@punks/cli/features/operator-skill/OperatorSkillOperations");var runOperatorSkillApplication=fn2("OperatorSkill.run")(function*runOperatorSkillApplication2(action2,selectAgent){const operations=yield*OperatorSkillOperations;return yield*operations.run(action2,selectAgent)});var isWithinCanonicalPath=(candidate,root)=>candidate===root||candidate.startsWith(root.endsWith("/")?root:`${root}/`)||candidate.startsWith(root.endsWith("\\")?root:`${root}\\`);var installedOperatorSkillCopyIdentity=(copy3)=>("version"in copy3)?JSON.stringify([copy3.scope,copy3.scope==="project-local"?copy3.projectRoot:"","verified",copy3.version,copy3.source,copy3.revision,copy3.compatibility,[...copy3.boundAgents].toSorted()]):JSON.stringify([copy3.scope,copy3.scope==="project-local"?copy3.projectRoot:"",copy3.verification,copy3.path,[...copy3.boundAgents].toSorted()]);var compareText=(left,right)=>left<right?-1:Number(left>right);var compareCopyIdentity=(left,right)=>{const leftIdentity=installedOperatorSkillCopyIdentity(left);const rightIdentity=installedOperatorSkillCopyIdentity(right);return compareText(leftIdentity,rightIdentity)};var sortCopies=(copies)=>copies.toSorted(compareCopyIdentity);var failureIdentity=(failure)=>JSON.stringify([failure.scope,failure.scope==="project-local"?failure.projectRoot:"",failure.reason,failure.message]);var resolveInstalledOperatorSkillState=(input2)=>{const failures=[];const copies=[];for(const inspection of input2.inspections){if(inspection._tag==="DetectionFailed"){failures.push(inspection);continue}if(inspection.scope==="global"){copies.push(...inspection.copies.map((copy3)=>({...copy3,boundAgents:[...copy3.boundAgents].toSorted()})));continue}for(const copy3 of inspection.copies){if(copy3.projectRoot!==inspection.projectRoot){failures.push({_tag:"DetectionFailed",message:`Project-local copy root ${copy3.projectRoot} does not match inspection root ${inspection.projectRoot}`,projectRoot:inspection.projectRoot,reason:"ProjectRootMismatch",scope:"project-local"});continue}copies.push({...copy3,boundAgents:[...copy3.boundAgents].toSorted(),projectRoot:inspection.projectRoot})}}const detected=sortCopies(copies);const incompatible=sortCopies(copies.filter((copy3)=>("compatibility"in copy3)&&copy3.compatibility==="incompatible"));if(failures.length>0){return{_tag:"DetectionFailed",detected,failures:failures.toSorted((left,right)=>compareText(failureIdentity(left),failureIdentity(right))),incompatible}}const candidates=detected.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)&&(copy3.scope==="global"||isWithinCanonicalPath(input2.cwd,copy3.projectRoot))).toSorted((left,right)=>Number(left.scope==="global")-Number(right.scope==="global"));const[effective]=candidates;if(effective===undefined){return{_tag:"Absent",detected,incompatible}}const topCandidates=candidates.filter((copy3)=>copy3.scope===effective.scope);if(topCandidates.some((copy3)=>installedOperatorSkillCopyIdentity(copy3)!==installedOperatorSkillCopyIdentity(effective))){return{_tag:"Ambiguous",candidates:topCandidates.toSorted(compareCopyIdentity),incompatible,shadowed:sortCopies(candidates.slice(topCandidates.length))}}if(!("version"in effective)){return{_tag:"Outdated",effective,incompatible,shadowed:sortCopies(candidates.slice(1))}}return{_tag:"Resolved",effective,incompatible,shadowed:sortCopies(candidates.slice(1))}};var operatorSkillScopeCwd=(scope3,input2)=>scope3==="global"?input2.cwd:input2.projectRoot;var parseSemanticVersion=(value5)=>{const match8=/^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-(?<prerelease>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(value5);const groups=match8?.groups;const prerelease=groups?.prerelease?.split(".");if(groups===undefined||prerelease?.some((identifier2)=>/^\d+$/u.test(identifier2)&&!/^(?:0|[1-9]\d*)$/u.test(identifier2))){return}return{core:[groups.major,groups.minor,groups.patch],prerelease}};var compareIdentifiers=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var compareNumericIdentifiers=(left,right)=>left.length-right.length||compareIdentifiers(left,right);var comparePrerelease=(left,right)=>{if(left===undefined||right===undefined){if(left===right){return 0}return left===undefined?1:-1}const length=Math.max(left.length,right.length);for(let index2=0;index2<length;index2+=1){const leftIdentifier=left[index2];const rightIdentifier=right[index2];if(leftIdentifier===undefined||rightIdentifier===undefined){if(leftIdentifier===rightIdentifier){return 0}return leftIdentifier===undefined?-1:1}if(leftIdentifier===rightIdentifier){continue}const leftIsNumeric=/^\d+$/u.test(leftIdentifier);const rightIsNumeric=/^\d+$/u.test(rightIdentifier);if(leftIsNumeric&&rightIsNumeric){return compareNumericIdentifiers(leftIdentifier,rightIdentifier)}if(leftIsNumeric!==rightIsNumeric){return leftIsNumeric?-1:1}return compareIdentifiers(leftIdentifier,rightIdentifier)}return 0};var compareSemanticVersions=(left,right)=>{const parsedLeft=parseSemanticVersion(left);const parsedRight=parseSemanticVersion(right);if(parsedLeft===undefined||parsedRight===undefined){return}for(let index2=0;index2<parsedLeft.core.length;index2+=1){const compared=compareNumericIdentifiers(parsedLeft.core[index2],parsedRight.core[index2]);if(compared!==0){return compared}}return comparePrerelease(parsedLeft.prerelease,parsedRight.prerelease)};var satisfiesSemanticVersionRange=(version3,minimum,maximumExclusive)=>{const comparedToMinimum=compareSemanticVersions(version3,minimum);const comparedToMaximum=compareSemanticVersions(version3,maximumExclusive);return comparedToMinimum!==undefined&&comparedToMaximum!==undefined&&comparedToMinimum>=0&&comparedToMaximum<0};var authoritativeContentManifest=Object.freeze([Object.freeze({path:"SKILL.md",sha256:"aee7ff55492ba810ca75bfbc8bbf5d4a14695828634c3fb1c6aea0a895589b98"}),Object.freeze({path:"references/commands.md",sha256:"62e07c52acd6add81a8feccbe39eb99521d6a2c9682d97e940bcc39a5e705e1a"}),Object.freeze({path:"references/post-command-flow.md",sha256:"0975f458b8636de0ef0d26e1dbc3c353208acc439fa47ebe2f261181e94815a8"})]);var authoritativeOperatorSkillTarget=Object.freeze({cliCompatibility:Object.freeze({maximumExclusive:"4.0.0",minimum:"3.0.0-beta.0"}),contentManifest:authoritativeContentManifest,revision:"09a6f3c6f9a7ed62a7e4abf0411f8a0f4f993e1d",source:"https://github.com/wearedevpunks/skills/tree/09a6f3c6f9a7ed62a7e4abf0411f8a0f4f993e1d/skills/agnostic/cli/hi-cli",version:"1.1.0"});var immutableRevisionPattern=/^[0-9a-f]{40}$/u;var authoritativeSourceRoot="https://github.com/wearedevpunks/skills";var operatorSkillPath="skills/agnostic/cli/hi-cli";var targetIsIncomplete=(target)=>target.source.trim()===""||target.version.trim()===""||target.revision.trim()===""||target.cliCompatibility.minimum.trim()===""||target.cliCompatibility.maximumExclusive.trim()===""||target.contentManifest.length===0||target.contentManifest.some((entry)=>entry.path.trim()===""||entry.sha256.trim()==="");var validateTarget=(target)=>{if(targetIsIncomplete(target)){return"IncompleteIdentity"}if(!immutableRevisionPattern.test(target.revision)){return"MovingRevision"}const immutableSource=`${authoritativeSourceRoot}/tree/${target.revision}/${operatorSkillPath}`;if(target.source!==immutableSource){return target.source.startsWith(authoritativeSourceRoot)?"SourceRevisionMismatch":"NonAuthoritativeSource"}const version3=compareSemanticVersions(target.version,target.version);const rangeOrder=compareSemanticVersions(target.cliCompatibility.minimum,target.cliCompatibility.maximumExclusive);if(version3===undefined||rangeOrder===undefined||rangeOrder>=0){return"InvalidVersion"}if(target.source!==authoritativeOperatorSkillTarget.source||target.version!==authoritativeOperatorSkillTarget.version||target.revision!==authoritativeOperatorSkillTarget.revision||target.cliCompatibility.minimum!==authoritativeOperatorSkillTarget.cliCompatibility.minimum||target.cliCompatibility.maximumExclusive!==authoritativeOperatorSkillTarget.cliCompatibility.maximumExclusive||JSON.stringify(target.contentManifest)!==JSON.stringify(authoritativeOperatorSkillTarget.contentManifest)){return"NonAuthoritativeIdentity"}return};var resolveOperatorSkillTarget=(input2)=>{if(compareSemanticVersions(input2.activeCliVersion,input2.activeCliVersion)===undefined){return{_tag:"NoCompatibleTarget",activeCliVersion:input2.activeCliVersion}}const compatibleIndexes=[];for(const[candidateIndex,candidate]of input2.candidates.entries()){const invalidReason=validateTarget(candidate);if(invalidReason!==undefined){return{_tag:"InvalidTarget",candidateIndex,reason:invalidReason}}if(satisfiesSemanticVersionRange(input2.activeCliVersion,candidate.cliCompatibility.minimum,candidate.cliCompatibility.maximumExclusive)){compatibleIndexes.push(candidateIndex)}}if(compatibleIndexes.length===0){return{_tag:"NoCompatibleTarget",activeCliVersion:input2.activeCliVersion}}if(compatibleIndexes.length>1){return{_tag:"AmbiguousCompatibleTargets",activeCliVersion:input2.activeCliVersion,candidateIndexes:compatibleIndexes}}return{_tag:"Resolved",target:authoritativeOperatorSkillTarget}};var compatibilityFor=(activeCliVersion,skill)=>satisfiesSemanticVersionRange(activeCliVersion,skill.cliCompatibility.minimum,skill.cliCompatibility.maximumExclusive)?"compatible":"incompatible";var isVerified=(skill)=>("version"in skill);var mapGlobalCopy=(activeCliVersion,skill)=>({boundAgents:[...skill.agents].toSorted(),compatibility:compatibilityFor(activeCliVersion,skill),revision:skill.revision,scope:"global",source:skill.source,version:skill.version});var mapProjectCopy=(activeCliVersion,projectRoot,skill)=>({boundAgents:[...skill.agents].toSorted(),compatibility:compatibilityFor(activeCliVersion,skill),projectRoot,revision:skill.revision,scope:"project-local",source:skill.source,version:skill.version});var inspectListedSkills=(scope3,input2,skills)=>{const outdatedOperatorSkills=skills.filter((skill)=>skill.name==="hi-cli"&&("verification"in skill)&&skill.verification==="outdated");const operatorSkills=skills.filter((skill)=>skill.name==="hi-cli"&&isVerified(skill));const legacySkills=skills.filter((skill)=>skill.name==="dp-cli");if(scope3==="global"){return{_tag:"Inspected",copies:[...operatorSkills.map((skill)=>mapGlobalCopy(input2.activeCliVersion,skill)),...outdatedOperatorSkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,scope:"global",verification:"outdated"}))],legacy:legacySkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,scope:scope3})),scope:scope3}}return{_tag:"Inspected",copies:[...operatorSkills.map((skill)=>mapProjectCopy(input2.activeCliVersion,input2.projectRoot,skill)),...outdatedOperatorSkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,projectRoot:input2.projectRoot,scope:"project-local",verification:"outdated"}))],legacy:legacySkills.map((skill)=>({boundAgents:[...skill.agents].toSorted(),path:skill.path,projectRoot:input2.projectRoot,scope:scope3})),projectRoot:input2.projectRoot,scope:scope3}};var failedInspection=(scope3,input2,failure)=>{const verifiedSkills=failure._tag==="SkillsCliVerificationFailure"||failure._tag==="SkillsCliBindingFailure"?failure.verifiedSkills:[];if(scope3==="global"){return{_tag:"InspectionFailed",copies:verifiedSkills.map((skill)=>mapGlobalCopy(input2.activeCliVersion,skill)),failure,legacy:[],scope:scope3}}return{_tag:"InspectionFailed",copies:verifiedSkills.map((skill)=>mapProjectCopy(input2.activeCliVersion,input2.projectRoot,skill)),failure,legacy:[],projectRoot:input2.projectRoot,scope:scope3}};var installedInspections=(inspections)=>inspections.flatMap((inspection)=>{const detected=inspection.scope==="global"?{_tag:"Detected",copies:inspection.copies,scope:"global"}:{_tag:"Detected",copies:inspection.copies,projectRoot:inspection.projectRoot,scope:"project-local"};if(inspection._tag==="Inspected"){return[detected]}const failure=inspection.scope==="global"?{_tag:"DetectionFailed",message:inspection.failure.message,reason:"ListingFailed",scope:"global"}:{_tag:"DetectionFailed",message:inspection.failure.message,projectRoot:inspection.projectRoot,reason:"ListingFailed",scope:"project-local"};return inspection.copies.length===0?[failure]:[detected,failure]});var collectLegacyCopies=(inspections)=>{const copies=[];for(const inspection of inspections){copies.push(...inspection.legacy)}return copies};var inspectOperatorSkillLifecycle=fn2("OperatorSkillLifecycle.status")(function*inspectOperatorSkillLifecycle2(input2){const resolution=resolveOperatorSkillTarget({activeCliVersion:input2.activeCliVersion,candidates:[authoritativeOperatorSkillTarget]});if(resolution._tag!=="Resolved"){return{_tag:"TargetResolutionFailed",resolution}}const skillsCli=yield*SkillsCli;const[globalResult,projectResult]=yield*all2([result2(skillsCli.list({agent:input2.activeAgent,cwd:operatorSkillScopeCwd("global",input2),scope:"global",target:resolution.target})),result2(skillsCli.list({agent:input2.activeAgent,cwd:operatorSkillScopeCwd("project-local",input2),scope:"project",target:resolution.target}))],{concurrency:"unbounded"});const inspections=[isFailure2(globalResult)?failedInspection("global",input2,globalResult.failure):inspectListedSkills("global",input2,globalResult.success),isFailure2(projectResult)?failedInspection("project-local",input2,projectResult.failure):inspectListedSkills("project-local",input2,projectResult.success)];const installed=resolveInstalledOperatorSkillState({activeAgent:input2.activeAgent,cwd:input2.cwd,inspections:installedInspections(inspections)});return{_tag:"Inspected",inspections,installed,legacy:collectLegacyCopies(inspections),target:resolution.target}});var retryFor=(operation,scope3,input2,target)=>Object.freeze({input:Object.freeze({...input2}),operation,scope:scope3,target});var inspectionFor=(status2,scope3)=>status2.inspections.find((inspection)=>inspection.scope===scope3);var copyMatchesTarget=(copy3,target)=>("version"in copy3)&&copy3.version===target.version&&copy3.source===target.source&&copy3.revision===target.revision&&copy3.compatibility==="compatible";var copyAppliesToScope=(copy3,input2)=>copy3.boundAgents.includes(input2.activeAgent)&&(copy3.scope==="global"||copy3.projectRoot===input2.projectRoot);var targetCopy=(inspection,input2,target)=>inspection.copies.find((copy3)=>copyMatchesTarget(copy3,target)&&copyAppliesToScope(copy3,input2));var hasCompetingCopyIdentity=(inspection,copy3,input2)=>inspection.copies.some((candidate)=>copyAppliesToScope(candidate,input2)&&installedOperatorSkillCopyIdentity(candidate)!==installedOperatorSkillCopyIdentity(copy3));var verifyOperatorSkillScope=(scope3,input2,target,verification)=>{if(verification._tag==="TargetResolutionFailed"){return{_tag:"Unverified",reason:"TargetResolutionFailed",scope:scope3,verification}}const inspection=inspectionFor(verification,scope3);if(inspection?._tag==="InspectionFailed"){return{_tag:"Unverified",failure:inspection.failure,reason:"InspectionFailed",scope:scope3,verification}}if(inspection!==undefined){const copy3=targetCopy(inspection,input2,target);if(copy3!==undefined){if(hasCompetingCopyIdentity(inspection,copy3,input2)){return{_tag:"Unverified",reason:"CompetingCopyObserved",scope:scope3,verification}}return{_tag:"Verified",copy:copy3,scope:scope3,verification}}}return{_tag:"Unverified",reason:"TargetNotObserved",scope:scope3,verification}};var ensureAndVerifyOperatorSkillScope=fn2("OperatorSkillLifecycle.ensureAndVerifyScope")(function*ensureAndVerifyOperatorSkillScope2(scope3,input2,target){const skillsCli=yield*SkillsCli;const write2=yield*result2(skillsCli.install({agent:input2.activeAgent,cwd:operatorSkillScopeCwd(scope3,input2),scope:scope3==="global"?"global":"project",target}));if(isFailure2(write2)){return{_tag:"Failed",failure:write2.failure,scope:scope3}}const verification=yield*inspectOperatorSkillLifecycle(input2);return verifyOperatorSkillScope(scope3,input2,target,verification)});var mutationActionFor=(operation,input2,target,result4)=>{const retry5=retryFor(operation,result4.scope,input2,target);if(result4._tag==="Failed"){return{_tag:"Failed",failure:result4.failure,operation,phase:"write",retry:retry5,scope:result4.scope}}if(result4._tag==="Unverified"){return{...result4,operation,retry:retry5}}return{...result4,operation}};var inspectionDetectedOperatorSkill=(inspection)=>inspection.copies.length>0||inspection._tag==="InspectionFailed"&&(inspection.failure._tag==="SkillsCliVerificationFailure"||inspection.failure._tag==="SkillsCliBindingFailure")&&inspection.failure.skillName==="hi-cli";var inspectionScopeIsUnknown=(inspection)=>inspection._tag==="InspectionFailed"&&!inspectionDetectedOperatorSkill(inspection);var alreadyVerifiedGlobal=(before,input2)=>{const inspection=inspectionFor(before,"global");if(inspection?._tag!=="Inspected"){return}const copy3=targetCopy(inspection,input2,before.target);if(copy3===undefined||hasCompetingCopyIdentity(inspection,copy3,input2)){return}return{_tag:"AlreadyVerified",copy:copy3,operation:"install",scope:"global",verification:before}};var unknownScopeFailures=(operation,before,input2)=>before.inspections.flatMap((inspection)=>inspectionScopeIsUnknown(inspection)&&(operation==="update"||inspection.scope==="global")?[{_tag:"Failed",failure:inspection.failure,operation,phase:"inspection",retry:retryFor(operation,inspection.scope,input2,before.target),scope:inspection.scope}]:[]);var scopesToMutate=(operation,before)=>{if(operation==="install"){const globalIsUnknown=before.inspections.some((inspection)=>inspection.scope==="global"&&inspectionScopeIsUnknown(inspection));return globalIsUnknown?[]:["global"]}return before.inspections.filter(inspectionDetectedOperatorSkill).map((inspection)=>inspection.scope)};var mutateOperatorSkill=fn2("OperatorSkillLifecycle.mutate")(function*mutateOperatorSkill2(operation,input2){const before=yield*inspectOperatorSkillLifecycle(input2);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,operation,reload:{_tag:"NotRequired"}}}const existingGlobal=operation==="install"?alreadyVerifiedGlobal(before,input2):undefined;const actions=[...unknownScopeFailures(operation,before,input2),...existingGlobal===undefined?[]:[existingGlobal]];let wrote=false;const scopes=existingGlobal===undefined?scopesToMutate(operation,before):[];for(const scope3 of scopes){const ensured=yield*ensureAndVerifyOperatorSkillScope(scope3,input2,before.target);wrote||=ensured._tag!=="Failed";actions.push(mutationActionFor(operation,input2,before.target,ensured))}return{_tag:"Completed",actions,before,operation,reload:wrote?{_tag:"ReloadRequired",skill:"hi-cli"}:{_tag:"NotRequired"},target:before.target}});var installOperatorSkill=fn2("OperatorSkillLifecycle.install")(function*installOperatorSkill2(input2){return yield*mutateOperatorSkill("install",input2)});var updateOperatorSkill=fn2("OperatorSkillLifecycle.update")(function*updateOperatorSkill2(input2){return yield*mutateOperatorSkill("update",input2)});var migrationRetry=(scope3,input2,target,phase,affectedScopes)=>Object.freeze({affectedScopes:Object.freeze([...affectedScopes]),input:Object.freeze({...input2}),operation:"migrate",phase,scope:scope3,target});var affectedScopes=(before,input2)=>["global","project-local"].filter((scope3)=>(scope3==="global"||isWithinCanonicalPath(input2.cwd,input2.projectRoot))&&before.inspections.some((inspection)=>inspection.scope===scope3&&inspection.legacy.some((copy3)=>copy3.boundAgents.includes(input2.activeAgent))));var scopeApplies=(scope3,input2)=>scope3==="global"||isWithinCanonicalPath(input2.cwd,input2.projectRoot);var recoverableScopes=(input2,scopes)=>["global","project-local"].filter((scope3)=>scopes.includes(scope3)&&scopeApplies(scope3,input2));var targetIdentity=(target)=>JSON.stringify([target.source,target.version,target.revision,target.cliCompatibility,target.contentManifest]);var legacyIdentity=(copy3)=>JSON.stringify([copy3.scope,copy3.scope==="project-local"?copy3.projectRoot:"",copy3.path,[...copy3.boundAgents].toSorted()]);var inspectedLegacyCopiesFor=(status2,scope3)=>{if(status2._tag!=="Inspected"){return}const inspection=status2.inspections.find((candidate)=>candidate.scope===scope3);return inspection?._tag==="Inspected"?inspection.legacy:undefined};var legacyCopiesFor=(status2,scope3)=>inspectedLegacyCopiesFor(status2,scope3)??[];var legacyCopiesMatch=(left,right)=>JSON.stringify(left.map(legacyIdentity).toSorted())===JSON.stringify(right.map(legacyIdentity).toSorted());var unrelatedLegacyResiduals=(copies,activeAgent)=>copies.flatMap((copy3)=>{const boundAgents=copy3.boundAgents.filter((agent)=>agent!==activeAgent);return boundAgents.length===0?[]:[{...copy3,boundAgents}]});var replacementAction=(result4,input2,target,scopes,wrote=true)=>{const retry5=migrationRetry(result4.scope,input2,target,"replacement",scopes);if(result4._tag==="Failed"){return{_tag:"ReplacementFailed",failure:result4.failure,retry:retry5,scope:result4.scope}}if(result4._tag==="Unverified"){return{_tag:"ReplacementUnverified",...result4.failure===undefined?{}:{failure:result4.failure},reason:result4.reason,retry:retry5,scope:result4.scope,verification:result4.verification}}return{_tag:"ReplacementVerified",copy:result4.copy,scope:result4.scope,verification:result4.verification,wrote}};var reloadGuidance=(wrote)=>wrote?{_tag:"ReloadRequired",skill:"hi-cli"}:{_tag:"NotRequired"};var verifyBarrierCopy=(scope3,input2,target,verification,expected)=>{const observed=verifyOperatorSkillScope(scope3,input2,target,verification);if(observed._tag!=="Verified"){return observed}if(expected===undefined||installedOperatorSkillCopyIdentity(observed.copy)!==installedOperatorSkillCopyIdentity(expected)){return{_tag:"Unverified",reason:"ReplacementChanged",scope:scope3,verification}}return observed};var legacyRemovalReason=(reason)=>{if(reason==="InspectionFailed"){return"InspectionFailed"}return reason==="ReplacementChanged"?"ReplacementChanged":"ReplacementNotVerified"};var validateAffectedBarriers=(input2)=>(()=>{let blockingLoss;return input2.scopes.flatMap((scope3,scopeIndex)=>{const pending=scopeIndex>input2.afterIndex;const checked=verifyBarrierCopy(scope3,input2.migrationInput,input2.target,input2.verification,input2.barrierCopies.get(scope3));if(checked._tag==="Verified"){if(!pending||blockingLoss===undefined||input2.refusedScopes.has(scope3)){return[]}input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",barrierReason:blockingLoss.reason,barrierScope:blockingLoss.scope,...blockingLoss.failure===undefined?{}:{failure:blockingLoss.failure},reason:"BarrierLost",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]}if(pending&&input2.refusedScopes.has(scope3)){return[]}const failure="failure"in checked&&checked.failure!==undefined?{failure:checked.failure}:{};if(pending){input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",barrierReason:checked.reason,barrierScope:scope3,...failure,reason:"BarrierLost",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]}blockingLoss={reason:checked.reason,scope:scope3,...failure};if(input2.lostBarrierScopes.has(scope3)){return[]}input2.lostBarrierScopes.add(scope3);return[{_tag:"RemovalBarrierLost",afterScope:input2.afterScope,barrierReason:checked.reason,...failure,phase:input2.phase,position:scopeIndex===input2.afterIndex?"current":"prior",retry:migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes),scope:scope3,verification:input2.verification}]})})();var validatePeerLegacySnapshots=(input2)=>input2.scopes.flatMap((scope3,scopeIndex)=>{if(scopeIndex===input2.afterIndex){return[]}const observed=inspectedLegacyCopiesFor(input2.verification,scope3);if(observed===undefined){return[]}const activeChanged=!legacyCopiesMatch(input2.activeSnapshots.get(scope3)??[],observed.filter((copy3)=>copy3.boundAgents.includes(input2.migrationInput.activeAgent)));const unrelatedChanged=!legacyCopiesMatch(input2.unrelatedSnapshots.get(scope3)??[],unrelatedLegacyResiduals(observed,input2.migrationInput.activeAgent));if(!activeChanged&&!unrelatedChanged){return[]}const legacyReason=unrelatedChanged?"UnrelatedLegacyChanged":"ActiveLegacyChanged";const retry5=migrationRetry(scope3,input2.migrationInput,input2.target,"removal",input2.scopes);if(scopeIndex>input2.afterIndex){if(input2.refusedScopes.has(scope3)){return[]}input2.refusedScopes.add(scope3);return[{_tag:"LegacyRemovalRefused",legacyReason,reason:"LegacyChanged",retry:retry5,scope:scope3,verification:input2.verification}]}if(input2.reportedScopes.has(scope3)){return[]}input2.reportedScopes.add(scope3);return[{_tag:"LegacyRemovalUnverified",reason:activeChanged?"LegacyChangedAfterRemoval":"UnrelatedLegacyChanged",retry:retry5,scope:scope3,verification:input2.verification}]});var handleFailedLegacyRemoval=fn2("OperatorSkillLifecycle.handleFailedLegacyRemoval")(function*handleFailedLegacyRemoval2(context4,failure){const{activeLegacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target,unrelatedLegacyCopies}=context4;const actions=[{_tag:"LegacyRemovalFailed",failure,retry:retry5,scope:scope3}];let wrote=false;const verification=yield*inspectOperatorSkillLifecycle(input2);const observedLegacy=inspectedLegacyCopiesFor(verification,scope3);const activeLegacyChanged=observedLegacy!==undefined&&!legacyCopiesMatch(activeLegacyCopies.get(scope3)??[],observedLegacy.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)));const unrelatedLegacyChanged=observedLegacy!==undefined&&!legacyCopiesMatch(unrelatedLegacyCopies.get(scope3)??[],unrelatedLegacyResiduals(observedLegacy,input2.activeAgent));if(activeLegacyChanged||unrelatedLegacyChanged){wrote=true;actions.push({_tag:"LegacyRemovalUnverified",reason:activeLegacyChanged?"LegacyChangedAfterFailure":"UnrelatedLegacyChanged",retry:retry5,scope:scope3,verification})}const peerLegacyActions=validatePeerLegacySnapshots({activeSnapshots:activeLegacyCopies,afterIndex:scopeIndex,migrationInput:input2,refusedScopes,reportedScopes:reportedLegacyScopes,scopes,target,unrelatedSnapshots:unrelatedLegacyCopies,verification});wrote||=peerLegacyActions.length>0;actions.push(...peerLegacyActions);const barrierActions=validateAffectedBarriers({afterIndex:scopeIndex,afterScope:scope3,barrierCopies,lostBarrierScopes,migrationInput:input2,phase:"remove-failed",refusedScopes,scopes,target,verification});wrote||=barrierActions.some((action2)=>action2.barrierReason!=="InspectionFailed"&&action2.barrierReason!=="TargetResolutionFailed");actions.push(...barrierActions);if(observedLegacy!==undefined){activeLegacyCopies.set(scope3,observedLegacy.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)));unrelatedLegacyCopies.set(scope3,unrelatedLegacyResiduals(observedLegacy,input2.activeAgent))}return{actions,wrote}});var handleSuccessfulLegacyRemoval=fn2("OperatorSkillLifecycle.handleSuccessfulLegacyRemoval")(function*handleSuccessfulLegacyRemoval2(context4){const{activeLegacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target,unrelatedLegacyCopies}=context4;const verification=yield*inspectOperatorSkillLifecycle(input2);let currentAction;if(verification._tag==="TargetResolutionFailed"){currentAction={_tag:"LegacyRemovalUnverified",reason:"ReplacementNotVerified",retry:retry5,scope:scope3,verification}}else{const inspection=verification.inspections.find((candidate)=>candidate.scope===scope3);const observedLegacy=inspectedLegacyCopiesFor(verification,scope3);const unrelatedLegacyChanged=observedLegacy!==undefined&&!legacyCopiesMatch(unrelatedLegacyCopies.get(scope3)??[],unrelatedLegacyResiduals(observedLegacy,input2.activeAgent));if(unrelatedLegacyChanged){currentAction={_tag:"LegacyRemovalUnverified",reason:"UnrelatedLegacyChanged",retry:retry5,scope:scope3,verification}}else if(inspection!==undefined&&inspection.legacy.some((copy3)=>copy3.boundAgents.includes(input2.activeAgent))){currentAction={_tag:"LegacyRemovalUnverified",reason:"LegacyStillPresent",retry:retry5,scope:scope3,verification}}else{const replacementCheck=verifyBarrierCopy(scope3,input2,target,verification,barrierCopies.get(scope3));currentAction=replacementCheck._tag==="Verified"?{_tag:"LegacyRemoved",scope:scope3,verification}:{_tag:"LegacyRemovalUnverified",..."failure"in replacementCheck&&replacementCheck.failure!==undefined?{failure:replacementCheck.failure}:{},reason:legacyRemovalReason(replacementCheck.reason),retry:retry5,scope:scope3,verification}}}const actions=[currentAction,...validatePeerLegacySnapshots({activeSnapshots:activeLegacyCopies,afterIndex:scopeIndex,migrationInput:input2,refusedScopes,reportedScopes:reportedLegacyScopes,scopes,target,unrelatedSnapshots:unrelatedLegacyCopies,verification})];const observedCurrentLegacy=inspectedLegacyCopiesFor(verification,scope3);if(observedCurrentLegacy!==undefined){activeLegacyCopies.set(scope3,observedCurrentLegacy.filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent)))}actions.push(...validateAffectedBarriers({afterIndex:scopeIndex,afterScope:scope3,barrierCopies,lostBarrierScopes,migrationInput:input2,phase:"remove-succeeded",refusedScopes,scopes,target,verification}));return actions});var prepareMigration=(before,input2,recoveryScopes,recoveryPhase)=>{const observedScopes=affectedScopes(before,input2);const recoveryScopeLimit=recoveryScopes===undefined?undefined:recoverableScopes(input2,recoveryScopes);let scopes=observedScopes;if(recoveryScopeLimit!==undefined){scopes=recoveryPhase==="preflight"?observedScopes.filter((scope3)=>recoveryScopeLimit.includes(scope3)):recoveryScopeLimit}const retryScopes=recoveryScopeLimit===undefined?recoverableScopes(input2,[...scopes,...before.inspections.flatMap((inspection)=>inspection._tag==="InspectionFailed"?[inspection.scope]:[])]):recoveryScopeLimit;const preflightFailures=before.inspections.flatMap((inspection)=>inspection._tag==="InspectionFailed"&&scopeApplies(inspection.scope,input2)&&(recoveryScopeLimit===undefined||recoveryScopeLimit.includes(inspection.scope))?[{_tag:"PreflightFailed",failure:inspection.failure,retry:migrationRetry(inspection.scope,input2,before.target,"preflight",retryScopes),scope:inspection.scope}]:[]);return{preflightFailures,scopes}};var ensureReplacementBarriers=fn2("OperatorSkillLifecycle.ensureReplacementBarriers")(function*ensureReplacementBarriers2(scopes,input2,before){const actions=[];let wrote=false;let barrierFailed=false;for(const scope3 of scopes){const existing=verifyOperatorSkillScope(scope3,input2,before.target,before);if(existing._tag==="Verified"){actions.push({_tag:"ReplacementVerified",copy:existing.copy,scope:scope3,verification:existing.verification,wrote:false});continue}const replacement=yield*ensureAndVerifyOperatorSkillScope(scope3,input2,before.target);wrote||=replacement._tag!=="Failed";barrierFailed||=replacement._tag!=="Verified";actions.push(replacementAction(replacement,input2,before.target,scopes))}return{actions,barrierFailed,wrote}});var inspectReplacementBarrier=fn2("OperatorSkillLifecycle.inspectReplacementBarrier")(function*inspectReplacementBarrier2(scopes,input2,target,recoveryScopes){const status2=yield*inspectOperatorSkillLifecycle(input2);const failedInspections=status2._tag==="Inspected"?status2.inspections.filter((inspection)=>inspection._tag==="InspectionFailed"&&scopeApplies(inspection.scope,input2)&&(recoveryScopes===undefined||scopes.includes(inspection.scope))):[];const failedScopes=new Set(failedInspections.map((inspection)=>inspection.scope));const verifications=scopes.flatMap((scope3)=>{if(failedScopes.has(scope3)){return[]}const verification=verifyOperatorSkillScope(scope3,input2,target,status2);return[{scope:scope3,verification}]});const actions=[...failedInspections.map((inspection)=>({_tag:"BarrierInspectionFailed",failure:inspection.failure,retry:migrationRetry(inspection.scope,input2,target,"barrier",scopes),scope:inspection.scope})),...verifications.flatMap(({scope:scope3,verification})=>verification._tag==="Unverified"?[{_tag:"BarrierUnverified",...verification.failure===undefined?{}:{failure:verification.failure},reason:verification.reason,retry:migrationRetry(scope3,input2,target,"barrier",scopes),scope:scope3,verification:verification.verification}]:[])];return{actions,status:status2,verifications}});var migrateLegacyOperatorSkillPolicy=fn2("OperatorSkillLifecycle.migratePolicy")(function*migrateLegacyOperatorSkillPolicy2(input2,recoveryScopes,expectedTarget,recoveryPhase){const before=yield*inspectOperatorSkillLifecycle(input2);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,reload:{_tag:"NotRequired"}}}if(expectedTarget!==undefined&&targetIdentity(expectedTarget)!==targetIdentity(before.target)){return{_tag:"RetryTargetChanged",actions:[],expected:expectedTarget,observed:before.target,reload:{_tag:"NotRequired"}}}const{preflightFailures,scopes}=prepareMigration(before,input2,recoveryScopes,recoveryPhase);if(preflightFailures.length>0){return{_tag:"Refused",actions:preflightFailures,before,reason:"PreflightUnknown",reload:{_tag:"NotRequired"},target:before.target}}if(scopes.length===0){return{_tag:"Completed",actions:[],before,reload:{_tag:"NotRequired"},target:before.target}}const replacement=yield*ensureReplacementBarriers(scopes,input2,before);const actions=[...replacement.actions];let{wrote}=replacement;if(replacement.barrierFailed){return{_tag:"Refused",actions,before,reason:"ReplacementBarrierFailed",reload:reloadGuidance(wrote),target:before.target}}const barrier=yield*inspectReplacementBarrier(scopes,input2,before.target,recoveryScopes);const finalBarrier=barrier.status;const finalVerifications=barrier.verifications;actions.push(...barrier.actions);if(barrier.actions.length>0){return{_tag:"Refused",actions,before,reason:"ReplacementBarrierFailed",reload:reloadGuidance(wrote),target:before.target}}const barrierCopies=new Map(finalVerifications.flatMap(({scope:scope3,verification})=>verification._tag==="Verified"?[[scope3,verification.copy]]:[]));const activeLegacyCopies=new Map(scopes.map((scope3)=>[scope3,legacyCopiesFor(finalBarrier,scope3).filter((copy3)=>copy3.boundAgents.includes(input2.activeAgent))]));const unrelatedLegacyCopies=new Map(scopes.map((scope3)=>[scope3,unrelatedLegacyResiduals(legacyCopiesFor(finalBarrier,scope3),input2.activeAgent)]));const skillsCli=yield*SkillsCli;const refusedScopes=new Set;const lostBarrierScopes=new Set;const reportedLegacyScopes=new Set;for(const scope3 of scopes){if(!(activeLegacyCopies.get(scope3)??[]).some((copy3)=>copy3.boundAgents.some((agent)=>agent!==input2.activeAgent))){continue}refusedScopes.add(scope3);actions.push({_tag:"LegacyRemovalRefused",legacyReason:"SharedResidualUnverifiable",reason:"ResidualBindingsUnverifiable",retry:migrationRetry(scope3,input2,before.target,"removal",scopes),scope:scope3,verification:finalBarrier})}const removalScopes=scopes.filter((scope3)=>(activeLegacyCopies.get(scope3)??[]).length>0);for(const scope3 of removalScopes){const scopeIndex=scopes.indexOf(scope3);if(refusedScopes.has(scope3)){continue}const remove7=yield*result2(skillsCli.remove({agent:input2.activeAgent,cwd:operatorSkillScopeCwd(scope3,input2),name:"dp-cli",scope:scope3==="global"?"global":"project"}));const retry5=migrationRetry(scope3,input2,before.target,"removal",scopes);const context4={activeLegacyCopies,barrierCopies,input:input2,lostBarrierScopes,refusedScopes,reportedLegacyScopes,retry:retry5,scope:scope3,scopeIndex,scopes,target:before.target,unrelatedLegacyCopies};if(isFailure2(remove7)){const failureResult=yield*handleFailedLegacyRemoval(context4,remove7.failure);wrote||=failureResult.wrote;actions.push(...failureResult.actions);continue}wrote=true;actions.push(...yield*handleSuccessfulLegacyRemoval(context4))}return{_tag:"Completed",actions,before,reload:reloadGuidance(wrote),target:before.target}});var migrateLegacyOperatorSkill=fn2("OperatorSkillLifecycle.migrate")(function*migrateLegacyOperatorSkill2(input2){return yield*migrateLegacyOperatorSkillPolicy(input2)});var retryLegacyOperatorSkillMigration=fn2("OperatorSkillLifecycle.retryMigration")(function*retryLegacyOperatorSkillMigration2(retry5,currentInput){return yield*migrateLegacyOperatorSkillPolicy({...retry5.input,activeCliVersion:currentInput.activeCliVersion},retry5.affectedScopes,retry5.target,retry5.phase)});var migrationRetrySchema=Struct({affectedScopes:ArraySchema(Literals(["global","project-local"])),input:Struct({activeAgent:String5,activeCliVersion:String5,cwd:String5,projectRoot:String5}),operation:Literal2("migrate"),phase:Literals(["barrier","preflight","removal","replacement"]),scope:Literals(["global","project-local"]),target:Struct({cliCompatibility:Struct({maximumExclusive:String5,minimum:String5}),contentManifest:ArraySchema(Struct({path:String5,sha256:String5})),revision:String5,source:String5,version:String5})});var mutationRetrySchema=Struct({input:Struct({activeAgent:String5,activeCliVersion:String5,cwd:String5,projectRoot:String5}),operation:Literals(["install","update"]),scope:Literals(["global","project-local"]),target:migrationRetrySchema.fields.target});var encodeMigrationRetry=(retry5)=>Buffer.from(JSON.stringify(retry5),"utf-8").toString("base64url");var decodeMigrationRetry=(token)=>try_3({catch:()=>new InvalidMigrationRetry({message:"Migration retry token is invalid or stale."}),try:()=>decodeUnknownSync2(migrationRetrySchema)(JSON.parse(Buffer.from(token,"base64url").toString("utf-8")))});var encodeMutationRetry=(retry5)=>Buffer.from(JSON.stringify(retry5),"utf-8").toString("base64url");var decodeMutationRetry=(token)=>try_3({catch:()=>new InvalidMutationRetry({message:"Operator mutation retry token is invalid or stale."}),try:()=>decodeUnknownSync2(mutationRetrySchema)(JSON.parse(Buffer.from(token,"base64url").toString("utf-8")))});var targetIdentity2=(target)=>JSON.stringify([target.source,target.version,target.revision,target.cliCompatibility,target.contentManifest]);var retryOperatorSkillMutation=(retry5,action2,currentInput)=>gen2(function*executeMutationRetry(){if(retry5.operation!==action2){return yield*new InvalidMutationRetry({message:`Operator mutation retry is for ${retry5.operation}, not ${action2}.`})}const retryInput={...retry5.input,activeCliVersion:currentInput.activeCliVersion};const before=yield*inspectOperatorSkillLifecycle(retryInput);if(before._tag==="TargetResolutionFailed"){return{_tag:"TargetResolutionFailed",actions:[],before,operation:retry5.operation,reload:{_tag:"NotRequired"}}}if(targetIdentity2(before.target)!==targetIdentity2(retry5.target)){return yield*new InvalidMutationRetry({message:"Operator mutation retry target changed; rerun the operator command."})}if(retry5.operation==="install"&&retry5.scope!=="global"){return yield*new InvalidMutationRetry({message:"Operator install retry scope changed; rerun the operator command."})}const inspection=inspectionFor(before,retry5.scope);if(inspection===undefined){return yield*new InvalidMutationRetry({message:"Operator mutation retry scope changed; rerun the operator command."})}if(inspectionScopeIsUnknown(inspection)){return{_tag:"Completed",actions:[{_tag:"Failed",failure:inspection.failure,operation:retry5.operation,phase:"inspection",retry:retry5,scope:retry5.scope}],before,operation:retry5.operation,reload:{_tag:"NotRequired"},target:retry5.target}}const updateIsAuthorized=retry5.operation==="update"&&inspectionDetectedOperatorSkill(inspection);const installIsAuthorized=retry5.operation==="install";if(!updateIsAuthorized&&!installIsAuthorized){return yield*new InvalidMutationRetry({message:"Operator mutation retry state changed; rerun the operator command."})}const result4=yield*ensureAndVerifyOperatorSkillScope(retry5.scope,retryInput,retry5.target);let mutationAction;if(result4._tag==="Failed"){mutationAction={...result4,operation:retry5.operation,phase:"write",retry:retry5}}else if(result4._tag==="Unverified"){mutationAction={...result4,operation:retry5.operation,retry:retry5}}else{mutationAction={...result4,operation:retry5.operation}}return{_tag:"Completed",actions:[mutationAction],before,operation:retry5.operation,reload:result4._tag==="Failed"?{_tag:"NotRequired"}:{_tag:"ReloadRequired",skill:"hi-cli"},target:retry5.target}});var executeOperatorAction=fn2("OperatorSkill.execute")(function*executeOperatorAction2(request3){const{action:action2,input:input2}=request3;if(action2==="status"){const lifecycle2=yield*inspectOperatorSkillLifecycle(input2);return{action:action2,lifecycle:lifecycle2}}if(action2==="install"||action2==="update"){const lifecycle2=request3.mutationRetryToken===undefined?yield*action2==="install"?installOperatorSkill(input2):updateOperatorSkill(input2):yield*decodeMutationRetry(request3.mutationRetryToken).pipe(flatMap4((retry5)=>retryOperatorSkillMutation(retry5,action2,input2)));return{action:action2,lifecycle:lifecycle2}}const lifecycle=request3.migrationRetryToken===undefined?yield*migrateLegacyOperatorSkill(input2):yield*decodeMigrationRetry(request3.migrationRetryToken).pipe(flatMap4((retry5)=>retryLegacyOperatorSkillMigration(retry5,input2)));return{action:action2,lifecycle}});var operatorCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator status",summary:"Inspect effective operator skill state."}],group:"commands",interaction:"none",name:"operator",options:[],outputModes:["interactive","plain","json"],summary:"Manage the Harness operator skill."});var operatorStatusCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator status",summary:"Run operator status."}],group:"operator",interaction:"optional",name:"status",options:[],outputModes:["interactive","plain","json"],summary:"Show immutable hi-cli identity and effective installed state."});var operatorInstallCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator install",summary:"Run operator install."}],group:"operator",interaction:"optional",name:"install",options:[],outputModes:["interactive","plain","json"],summary:"Ensure and verify the global hi-cli operator skill."});var operatorUpdateCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator update",summary:"Run operator update."}],group:"operator",interaction:"optional",name:"update",options:[],outputModes:["interactive","plain","json"],summary:"Update and verify every detected hi-cli scope."});var operatorMigrateCommandMetadata=declareCommandMetadata({examples:[{command:"hi operator migrate",summary:"Run operator migrate."}],group:"operator",interaction:"optional",name:"migrate",options:[],outputModes:["interactive","plain","json"],summary:"Verify replacements before removing legacy dp-cli copies."});var operatorActionMetadata=(action2)=>{switch(action2){case"status":{return operatorStatusCommandMetadata}case"install":{return operatorInstallCommandMetadata}case"update":{return operatorUpdateCommandMetadata}case"migrate":{return operatorMigrateCommandMetadata}default:{return action2}}};var publicOperatorFailure=(value5)=>{if(typeof value5!=="object"||value5===null){return value5}const failure=value5;return Object.fromEntries(["_tag","agent","exitCode","message","operation","reason","reportedAgents","scope","skillName"].filter((key)=>failure[key]!==undefined).map((key)=>[key,failure[key]]))};var operatorFact=(value5)=>JSON.stringify(value5,(key,nestedValue)=>{if(key==="stderr"||key==="stack"||key==="cause"){return}return key==="failure"?publicOperatorFailure(nestedValue):nestedValue});var quoteShellArgument=(value5)=>`'${value5.replaceAll("'",`'"'"'`)}'`;var quotePowerShellLiteral=(value5)=>`'${value5.replaceAll("'","''")}'`;var windowsPowerShellCommand=(statements)=>`powershell.exe -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(statements.join("; "),"utf16le").toString("base64")}`;var mutationRetryCommand=(action2,platform)=>{const retry5=encodeMutationRetry(action2.retry);if(platform==="win32"){return windowsPowerShellCommand([`Set-Location -LiteralPath ${quotePowerShellLiteral(action2.retry.input.cwd)}`,`$env:HI_OPERATOR_MUTATION_RETRY = ${quotePowerShellLiteral(retry5)}`,`$env:HI_OPERATOR_AGENT = ${quotePowerShellLiteral(action2.retry.input.activeAgent)}`,`& hi operator ${action2.retry.operation}`])}return`cd -- ${quoteShellArgument(action2.retry.input.cwd)} && HI_OPERATOR_MUTATION_RETRY=${retry5} HI_OPERATOR_AGENT=${quoteShellArgument(action2.retry.input.activeAgent)} hi operator ${action2.retry.operation}`};var migrationRetryCommand=(action2,platform)=>{const retry5=encodeMigrationRetry(action2.retry);if(platform==="win32"){return windowsPowerShellCommand([`Set-Location -LiteralPath ${quotePowerShellLiteral(action2.retry.input.cwd)}`,`$env:HI_OPERATOR_MIGRATION_RETRY = ${quotePowerShellLiteral(retry5)}`,`$env:HI_OPERATOR_AGENT = ${quotePowerShellLiteral(action2.retry.input.activeAgent)}`,"& hi operator migrate"])}return`cd -- ${quoteShellArgument(action2.retry.input.cwd)} && HI_OPERATOR_MIGRATION_RETRY=${retry5} HI_OPERATOR_AGENT=${quoteShellArgument(action2.retry.input.activeAgent)} hi operator migrate`};var publicTarget=(target)=>({cliCompatibility:target.cliCompatibility,revision:target.revision,source:target.source,version:target.version});var statusFromChangesAndIssues=(changeCount,issueCount)=>{if(issueCount>0){return changeCount>0?"partial":"failed"}return changeCount>0?"success":"no-op"};var operatorStatusOperationResult=(lifecycle)=>{if(lifecycle._tag==="TargetResolutionFailed"){return{changes:[],degradations:[],issues:[{action:"status",code:`operator-target-${lifecycle.resolution._tag}`,kind:"handled-failure",subject:operatorFact(lifecycle.resolution)}],nextActions:[{kind:"retry",subject:"operator:status"}],status:"failed",warnings:[]}}const changes=[{action:"operator-target",state:"completed",subject:operatorFact(publicTarget(lifecycle.target))},...lifecycle.inspections.map((inspection)=>({action:"operator-inspection",state:"completed",subject:operatorFact(inspection)})),{action:"operator-installed-state",state:"completed",subject:operatorFact(lifecycle.installed)},{action:"operator-legacy-copies",state:"completed",subject:operatorFact(lifecycle.legacy)}];let issues=[];if(lifecycle.installed._tag==="DetectionFailed"){issues=lifecycle.installed.failures.map((failure)=>({action:"status",code:"operator-detection-failed",errorMessage:failure.message,kind:"handled-failure",subject:operatorFact(failure)}))}else if(lifecycle.installed._tag==="Ambiguous"){issues=[{action:"status",code:"operator-installed-ambiguous",kind:"conflict",subject:operatorFact(lifecycle.installed.candidates)}]}let status2="success";if(lifecycle.installed._tag==="Ambiguous"){status2="conflict"}else if(lifecycle.installed._tag==="DetectionFailed"){status2="failed"}let nextActions;if(lifecycle.installed._tag==="Outdated"){nextActions=[{kind:"run",subject:"hi operator update"}]}else if(issues.length===0){nextActions=[{kind:"none"}]}else{nextActions=[lifecycle.installed._tag==="Ambiguous"?{kind:"resolve",subject:"operator:status"}:{kind:"retry",subject:"operator:status"}]}return{changes,degradations:[],issues,nextActions,status:status2,warnings:lifecycle.installed._tag==="Outdated"?[{code:"operator-installed-outdated",subject:operatorFact(lifecycle.installed.effective)}]:[]}};var publicVerifiedMutationAction=(action2)=>({_tag:action2._tag,copy:action2.copy,operation:action2.operation,scope:action2.scope});var publicFailedMutationAction=(action2)=>({_tag:action2._tag,operation:action2.operation,phase:action2.phase,retry:action2.retry,scope:action2.scope});var publicAlreadyVerifiedMutationAction=(action2)=>({_tag:action2._tag,copy:action2.copy,operation:action2.operation,scope:action2.scope});var publicUnverifiedMutationAction=(action2)=>({_tag:action2._tag,operation:action2.operation,reason:action2.reason,retry:action2.retry,scope:action2.scope});var operatorMutationOperationResult=(lifecycle,platform=process.platform)=>{if(lifecycle._tag==="TargetResolutionFailed"){return{changes:[],degradations:[],issues:[{action:lifecycle.operation,code:`operator-target-${lifecycle.before.resolution._tag}`,kind:"handled-failure",subject:operatorFact(lifecycle.before.resolution)}],nextActions:[{kind:"retry",subject:`operator:${lifecycle.operation}`}],status:"failed",warnings:[]}}const completed=lifecycle.actions.filter((action2)=>action2._tag==="Verified");const failed=lifecycle.actions.filter((action2)=>action2._tag==="Failed");const alreadyVerified=lifecycle.actions.filter((action2)=>action2._tag==="AlreadyVerified");const unverified=lifecycle.actions.filter((action2)=>action2._tag==="Unverified");const retryActions=[...failed,...unverified];const changes=completed.map((action2)=>({action:action2.operation,state:"completed",subject:operatorFact(publicVerifiedMutationAction(action2))}));const noInstalledUpdate=lifecycle.operation==="update"&&lifecycle.actions.length===0;const issues=[...failed.map((action2)=>({action:action2.operation,code:`operator-${action2.operation}-${action2._tag}`,errorMessage:action2.failure.message,kind:"handled-failure",subject:operatorFact(publicFailedMutationAction(action2))})),...unverified.map((action2)=>({action:action2.operation,code:`operator-${action2.operation}-${action2._tag}`,errorMessage:action2.failure?.message,kind:"handled-failure",subject:operatorFact(publicUnverifiedMutationAction(action2))})),...noInstalledUpdate?[{action:"update",code:"operator-update-no-installed-scope",kind:"handled-failure",subject:operatorFact({before:lifecycle.before,target:publicTarget(lifecycle.target)})}]:[]];let nextActions=[{kind:"none"}];if(noInstalledUpdate){nextActions=[{kind:"run",subject:"hi operator install"}]}else if(retryActions.length>0){nextActions=retryActions.map((action2)=>({kind:"run",subject:mutationRetryCommand(action2,platform)}))}return{changes,degradations:[],issues,nextActions,status:statusFromChangesAndIssues(changes.length,issues.length),warnings:[...alreadyVerified.map((action2)=>({code:`operator-${action2.operation}-${action2._tag}`,subject:operatorFact(publicAlreadyVerifiedMutationAction(action2))})),...lifecycle.reload._tag==="ReloadRequired"?[{code:"reload-required",subject:lifecycle.reload.skill}]:[]]}};var migrationContext=(lifecycle)=>{if(lifecycle._tag==="RetryTargetChanged"){return{expected:publicTarget(lifecycle.expected),observed:publicTarget(lifecycle.observed),result:{_tag:lifecycle._tag}}}if(lifecycle._tag==="TargetResolutionFailed"){return{resolution:lifecycle.before.resolution,result:{_tag:lifecycle._tag}}}return{before:{inspections:lifecycle.before.inspections,installed:lifecycle.before.installed,legacy:lifecycle.before.legacy},result:{_tag:lifecycle._tag,...lifecycle._tag==="Refused"?{reason:lifecycle.reason}:{}},target:publicTarget(lifecycle.target)}};var migrationFailure=(action2)=>("failure"in action2)?action2.failure:undefined;var operatorMigrationOperationResult=(lifecycle,platform=process.platform)=>{if(lifecycle._tag==="RetryTargetChanged"){return{changes:[],degradations:[],issues:[{action:"migrate",code:"operator-migrate-RetryTargetChanged",kind:"conflict",subject:operatorFact(migrationContext(lifecycle))}],nextActions:[{kind:"retry",subject:"operator:migrate"}],status:"conflict",warnings:[]}}if(lifecycle._tag==="TargetResolutionFailed"){return{changes:[],degradations:[],issues:[{action:"migrate",code:`operator-target-${lifecycle.before.resolution._tag}`,kind:"handled-failure",subject:operatorFact(migrationContext(lifecycle))}],nextActions:[{kind:"retry",subject:"operator:migrate"}],status:"failed",warnings:[]}}const completed=lifecycle.actions.filter((action2)=>action2._tag==="LegacyRemoved"||action2._tag==="ReplacementVerified"&&action2.wrote);const noOp=lifecycle.actions.filter((action2)=>action2._tag==="ReplacementVerified"&&!action2.wrote);const failed=lifecycle.actions.filter((action2)=>action2._tag!=="LegacyRemoved"&&action2._tag!=="ReplacementVerified");const context4=migrationContext(lifecycle);const changes=completed.map((action2)=>({action:"migrate",state:"completed",subject:operatorFact(action2)}));const issues=failed.map((action2)=>{const failure=migrationFailure(action2);return{action:"migrate",code:`operator-migrate-${action2._tag}`,...failure===undefined?{}:{errorMessage:failure.message},kind:"handled-failure",subject:operatorFact({action:action2,...context4})}});if(lifecycle._tag==="Refused"&&issues.length===0){issues.push({action:"migrate",code:"operator-migrate-Refused",kind:"handled-failure",subject:operatorFact(context4)})}let nextActions=[{kind:"none"}];if(failed.length>0){nextActions=failed.map((action2)=>({kind:"run",subject:migrationRetryCommand(action2,platform)}))}else if(issues.length>0){nextActions=[{kind:"retry",subject:"operator:migrate"}]}return{changes,degradations:[],issues,nextActions,status:statusFromChangesAndIssues(changes.length,issues.length),warnings:[{code:"operator-migrate-context",subject:operatorFact(context4)},...noOp.map((action2)=>({code:"operator-migrate-ReplacementVerified",subject:operatorFact(action2)})),...lifecycle.reload._tag==="ReloadRequired"?[{code:"reload-required",subject:lifecycle.reload.skill}]:[]]}};var executeOperatorCommand=(action2,operation=runOperatorSkillApplication,interaction)=>gen2(function*runOperatorCommand(){const selectAgent=interaction?.mode==="interactive"?interaction.prompt.readLine("Enter the Skills CLI agent name: "):undefined;const result4=yield*operation(action2,selectAgent);if(result4.action==="status"){return operatorStatusOperationResult(result4.lifecycle)}if(result4.action==="migrate"){return operatorMigrationOperationResult(result4.lifecycle)}return operatorMutationOperationResult(result4.lifecycle)}).pipe(catchTag2("InvalidMigrationRetry",(failure)=>fail6(new CliValidationError({message:failure.message,recoveryCommand:"unset HI_OPERATOR_MIGRATION_RETRY; hi operator migrate"}))),catchTag2("InvalidOperatorContext",(failure)=>fail6(new CliValidationError({message:failure.message}))),catchTag2("InvalidMutationRetry",(failure)=>fail6(new CliValidationError({message:failure.message,recoveryCommand:`unset HI_OPERATOR_MUTATION_RETRY; hi operator ${action2}`}))));var makeOperatorAction=(action2,operation=runOperatorSkillApplication)=>{const metadata=operatorActionMetadata(action2);return exports_Command.make(metadata.name,{},()=>gen2(function*runOperatorAction(){const mode=yield*SelectedOutputMode;const prompt=yield*CliPrompt;return yield*captureCommandResult(executeOperatorCommand(action2,operation,{mode,prompt}))})).pipe(withCommandMetadata(metadata))};var operatorRootOperationResult={changes:[],degradations:[],issues:[],nextActions:[{kind:"run",subject:"hi operator status"},{kind:"run",subject:"hi operator install"},{kind:"run",subject:"hi operator update"},{kind:"run",subject:"hi operator migrate"}],status:"no-op",warnings:[{code:"operator-command-summary",subject:"Manage the Harness operator skill."}]};var operatorRootOperation=succeed6(operatorRootOperationResult);var operatorSubcommands=[makeOperatorAction("status"),makeOperatorAction("install"),makeOperatorAction("update"),makeOperatorAction("migrate")];var operatorCommandRoot=exports_Command.make(operatorCommandMetadata.name,{},()=>captureCommandResult(operatorRootOperation)).pipe(withCommandMetadata(operatorCommandMetadata));var operatorCommand=operatorCommandRoot.pipe(exports_Command.withSubcommands(operatorSubcommands));class ReportConfigurationUnavailable extends TaggedErrorClass()("@punks/cli/report-submission/ReportConfigurationUnavailable",{cause:Defect(),message:String5,operation:Literal2("resolve-control-plane-url")}){}class ReportSubmissionResponseInvalid extends TaggedErrorClass()("@punks/cli/report-submission/ReportSubmissionResponseInvalid",{cause:Defect(),message:String5,operation:Literal2("validate-submission-response")}){}class ReportInputInvalid extends TaggedErrorClass()("@punks/cli/report-submission/ReportInputInvalid",{cause:Defect(),field:Literal2("body"),message:String5,operation:Literal2("validate-report-input")}){}class ReportSubmissionOperationFailure extends TaggedErrorClass()("@punks/cli/report-submission/ReportSubmissionOperationFailure",{cause:Defect(),message:String5,operation:Literals(["record-submitted","submit-report"])}){}var ReportSubmissionOperations=Service("@punks/cli/features/report-submission/ReportSubmissionOperations");var nonEmpty=(value5)=>{const trimmed=value5.trim();if(trimmed.length===0){const cause=new Error("Missing body. Pass a non-empty value.");return fail6(new ReportInputInvalid({cause,field:"body",message:cause.message,operation:"validate-report-input"}))}return succeed6(trimmed)};var csvLabels=(value5)=>value5===undefined?[]:value5.split(",").map((label)=>label.trim()).filter((label)=>label.length>0);var buildHarnessReport=fn2("ReportSubmission.build")(function*buildReport({title,body,message,type:type2,severity,area,repoRoot,skillPack,command,expected,actual,steps,labels}){const operations=yield*ReportSubmissionOperations;const validBody=yield*nonEmpty(body??message??[actual,expected,steps].filter(Boolean).join(`
344
344
 
345
- `));const repository=operations.observeRepository(repoRoot);return{...title===undefined?{}:{title},body:validBody,type:type2,severity,createdAt:new Date().toISOString(),cliVersion:operations.cliVersion,area,...skillPack===undefined?{}:{skillPack},...command===undefined?{}:{command},...expected===undefined?{}:{expected},...actual===undefined?{}:{actual},...steps===undefined?{}:{steps},...labels===undefined?{}:{labels},...repository===undefined?{}:{repository}}});var runReportSubmissionApplication=fn2("ReportSubmission.run")(function*runReportSubmissionApplication2(input2){const operations=yield*ReportSubmissionOperations;const report=yield*buildHarnessReport({...input2,labels:csvLabels(input2.extraLabels)});const baseUrl2=yield*operations.resolveControlPlaneUrl();if(baseUrl2===undefined){const cause=new Error("Harness report API URL is not configured.");return yield*new ReportConfigurationUnavailable({cause,message:cause.message,operation:"resolve-control-plane-url"})}const submitted=yield*operations.submit(baseUrl2,report);yield*operations.recordSubmitted(input2.repoRoot);return submitted});var reportCommandMetadata=declareCommandMetadata({examples:[{command:"hi report --message '...'",summary:"Submit a Harness report."}],group:"commands",interaction:"none",name:"report",options:[{name:"message",summary:"Raw report text for Harness triage."},{name:"title",summary:"Deprecated: optional title hint. The API generates the final title."},{name:"body",summary:"Deprecated: optional body hint. The API generates the final body."},{name:"type",summary:"Report type."},{name:"severity",summary:"Report severity."},{name:"area",summary:"Harness area."},{name:"repo-root",summary:"Repository root used for safe git context."},{name:"skill-pack",summary:"Affected skill pack, for example `hi-cli` or `docs-ingest-phase`."},{name:"command",summary:"Affected CLI command, for example `hi report` or `hi init`."},{name:"expected",summary:"Expected behavior."},{name:"actual",summary:"Actual behavior."},{name:"steps",summary:"Reproduction steps or evidence summary."},{name:"labels",summary:"Comma-separated extra GitHub labels."},{name:"json",summary:"Print JSON output."}],outputModes:["interactive","plain","json"],summary:"Submit reusable Harness friction to GitHub-backed maintainer triage."});var messageOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"message")).pipe(withOptionMetadata(reportCommandMetadata,"message")));var titleOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"title")).pipe(withOptionMetadata(reportCommandMetadata,"title")));var bodyOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"body")).pipe(withOptionMetadata(reportCommandMetadata,"body")));var typeOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"type"),["bug","docs","workflow","tooling","other"]).pipe(exports_Flag.withDefault("other"),withOptionMetadata(reportCommandMetadata,"type"));var severityOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"severity"),["low","medium","high"]).pipe(exports_Flag.withDefault("medium"),withOptionMetadata(reportCommandMetadata,"severity"));var areaOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"area"),["cli","wiki","skill","docs","workflow","backoffice","other"]).pipe(exports_Flag.withDefault("other"),withOptionMetadata(reportCommandMetadata,"area"));var repoRootOption=exports_Flag.string(metadataOptionName(reportCommandMetadata,"repo-root")).pipe(exports_Flag.withDefault(process.cwd()),withOptionMetadata(reportCommandMetadata,"repo-root"));var skillPackOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"skill-pack")).pipe(withOptionMetadata(reportCommandMetadata,"skill-pack")));var commandOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"command")).pipe(withOptionMetadata(reportCommandMetadata,"command")));var expectedOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"expected")).pipe(withOptionMetadata(reportCommandMetadata,"expected")));var actualOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"actual")).pipe(withOptionMetadata(reportCommandMetadata,"actual")));var stepsOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"steps")).pipe(withOptionMetadata(reportCommandMetadata,"steps")));var labelsOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"labels")).pipe(withOptionMetadata(reportCommandMetadata,"labels")));var jsonOption2=exports_Flag.boolean(metadataOptionName(reportCommandMetadata,"json")).pipe(withOptionMetadata(reportCommandMetadata,"json"));var optionalValue=(value5)=>isNone2(value5)||value5.value.trim().length===0?undefined:value5.value.trim();var reportExpectedFailure=(failure)=>{if(failure._tag==="@punks/cli/report-submission/ReportInputInvalid"){return new CliValidationError({message:"Report content is required.",recoveryCommand:"hi report --help"})}if(failure._tag==="@punks/cli/report-submission/ReportConfigurationUnavailable"){return new CliValidationError({message:"Harness report API URL is not configured.",recoveryCommand:"hi report"})}if(failure._tag==="@punks/cli/report-submission/ReportSubmissionResponseInvalid"){return new CliValidationError({message:"Harness report submission did not return a GitHub issue URL.",recoveryCommand:"hi report"})}return new CliValidationError({message:failure.operation==="record-submitted"?"Harness report submission could not be recorded locally.":"Harness report submission failed.",recoveryCommand:"hi report"})};var reportOperationResult=(submitted)=>{const{githubUrl}=submitted;const subject=githubUrl??submitted.reportId;return{changes:submitted.deduplicated===true?[]:[{action:`submit:${submitted.status}`,state:"completed",subject}],degradations:[],facts:{deduplicated:submitted.deduplicated===true,...githubUrl===undefined?{}:{githubUrl},kind:"report-submission",reportId:submitted.reportId,status:submitted.status,title:submitted.title??null},issues:[],nextActions:githubUrl===undefined?[]:[{kind:"review",subject:githubUrl}],status:submitted.deduplicated===true?"no-op":"success",warnings:submitted.deduplicated===true?[{code:"report-deduplicated",subject},{code:"report-status",subject:submitted.status}]:[]}};var executeReportCommand=(input2,operation=runReportSubmissionApplication)=>gen2(function*submitReport(){const submitted=yield*operation(input2).pipe(mapError3(reportExpectedFailure));return{...submitted,operation:reportOperationResult(submitted)}});var makeReportCommand=(operation=runReportSubmissionApplication)=>exports_Command.make(reportCommandMetadata.name,{actual:actualOption,area:areaOption,body:bodyOption,command:commandOption,expected:expectedOption,json:jsonOption2,labels:labelsOption,message:messageOption,repoRoot:repoRootOption,severity:severityOption,skillPack:skillPackOption,steps:stepsOption,title:titleOption,type:typeOption},({message,title,body,type:type2,severity,area,repoRoot,skillPack,command,expected,actual,steps,labels})=>captureCommandResult(executeReportCommand({actual:optionalValue(actual),area,body:optionalValue(body),command:optionalValue(command),expected:optionalValue(expected),extraLabels:optionalValue(labels),message:optionalValue(message),repoRoot,severity,skillPack:optionalValue(skillPack),steps:optionalValue(steps),title:optionalValue(title),type:type2},operation))).pipe(withCommandMetadata(reportCommandMetadata));var reportCommand=makeReportCommand();import path10 from"node:path";var RepositoryScaffoldingInteraction=Service("@punks/cli/features/repository-scaffolding/RepositoryScaffoldingInteraction");class RepositoryScaffoldingOperationFailure extends TaggedErrorClass()("@punks/cli/repository-scaffolding/RepositoryScaffoldingOperationFailure",{cause:Defect(),message:String5,operation:Literals(["initialize-repository","setup-repository"])}){}var RepositoryScaffoldingOperations=Service("@punks/cli/features/repository-scaffolding/RepositoryScaffoldingOperations");var runRepositoryScaffoldingApplication=fn2("RepositoryScaffolding.run")(function*runRepositoryScaffoldingApplication2(input2){const interaction=yield*RepositoryScaffoldingInteraction;const operations=yield*RepositoryScaffoldingOperations;return yield*operations.run(input2,interaction)});var outputSummary="Output directory for scaffolded files. Defaults to the current working directory.";var baselineSummary="Scaffold baseline to use: stable, bundled, or an exact version. Defaults to stable.";var refreshBaselineSummary="Refetch the stable baseline instead of reusing the local cache.";var initCommandMetadata=declareCommandMetadata({examples:[{command:"hi init",summary:"Initialize the current repository."}],group:"commands",interaction:"required",name:"init",options:[{name:"output",summary:outputSummary},{name:"baseline",summary:baselineSummary},{name:"refresh-baseline",summary:refreshBaselineSummary}],outputModes:["interactive","plain"],summary:"Seed docs onboarding, requirements/backlog/spec skills, and wiki structure. Agents: activate $hi-cli, then $docs-onboarding."});var scaffoldCommandMetadata=declareCommandMetadata({examples:[{command:"hi scaffold",summary:"Scaffold the current repository."}],group:"commands",interaction:"optional",name:"scaffold",options:[{name:"input",summary:"Repository root to scan. Defaults to the current working directory."},{name:"output",summary:outputSummary},{name:"json",summary:"Print the full machine-readable scaffold payload to stdout after completion."},{name:"repo-shape",summary:"Override repo shape detection. Use 'monorepo' or 'single' when auto-detection is not the desired scaffold mode."},{name:"baseline",summary:baselineSummary},{name:"refresh-baseline",summary:refreshBaselineSummary},{name:"yes",summary:"Run non-interactively and accept the resolved default scaffold selection."}],outputModes:["interactive","plain","json"],summary:"Repo-aware AI setup. Agents: activate $hi-cli, then reconcile .devpunks output with the real repo layout."});var silentNonInteractiveScaffoldingInteraction={confirmSelection:()=>die3("Non-interactive scaffold mode cannot confirm interactively"),emit:()=>void_3,keepPrefilledSelection:()=>die3("Non-interactive scaffold mode cannot edit the prefilled selection interactively"),selectPacks:()=>die3("Non-interactive scaffold mode cannot select packs interactively"),selectRepoSettings:()=>die3("Non-interactive scaffold mode cannot select repository settings interactively"),selectWikiFramework:()=>die3("Non-interactive scaffold mode cannot select a wiki framework interactively")};var outputOption=(metadata)=>exports_Flag.optional(exports_Flag.string(metadataOptionName(metadata,"output")).pipe(exports_Flag.withAlias("o"),withOptionMetadata(metadata,"output")));var inputOption2=exports_Flag.optional(exports_Flag.string(metadataOptionName(scaffoldCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(scaffoldCommandMetadata,"input")));var jsonOption3=exports_Flag.boolean(metadataOptionName(scaffoldCommandMetadata,"json")).pipe(withOptionMetadata(scaffoldCommandMetadata,"json"));var repoShapeOption=exports_Flag.optional(exports_Flag.choice(metadataOptionName(scaffoldCommandMetadata,"repo-shape"),["auto","monorepo","single"]).pipe(withOptionMetadata(scaffoldCommandMetadata,"repo-shape")));var baselineOption2=(metadata)=>exports_Flag.optional(exports_Flag.string(metadataOptionName(metadata,"baseline")).pipe(withOptionMetadata(metadata,"baseline")));var refreshBaselineOption2=(metadata)=>exports_Flag.boolean(metadataOptionName(metadata,"refresh-baseline")).pipe(withOptionMetadata(metadata,"refresh-baseline"));var yesOption=exports_Flag.boolean(metadataOptionName(scaffoldCommandMetadata,"yes")).pipe(withOptionMetadata(scaffoldCommandMetadata,"yes"));var scaffoldOperationResult=(input2,result4)=>{const failedTools=result4.toolBootstrapStatuses.filter((tool)=>tool.status==="failed");const projectionPartial=result4.projectionStatus==="partial";const issues=[...projectionPartial?[{action:"project",code:"scaffold-projection-partial",errorMessage:"Scaffold projection completed partially.",kind:"handled-failure",subject:result4.outputDirectory}]:[],...failedTools.map((tool)=>({action:"bootstrap-required-tool",code:`scaffold-required-tool-${tool.toolId}-failed`,errorMessage:tool.errorMessage,kind:"handled-failure",subject:tool.toolId}))];return{changes:[{action:input2.kind==="init"?"initialize":"setup",state:"completed",subject:result4.outputDirectory},...result4.toolBootstrapStatuses.filter((tool)=>tool.status!=="failed").map((tool)=>({action:tool.status==="installed"?"install-required-tool":"verify-required-tool",state:"completed",subject:tool.toolId}))],degradations:[],issues,nextActions:issues.length===0?[{kind:"none"}]:[...failedTools.length===0?[]:[{kind:"run",subject:"hi tools ensure"}],...projectionPartial?[{kind:"review",subject:result4.outputDirectory}]:[]],status:issues.length===0?"success":"partial",warnings:[]}};var executeScaffoldCommand=(input2,operation=runRepositoryScaffoldingApplication)=>scoped2(gen2(function*executeScaffold(){const result4=yield*operation(input2);const operationResult=scaffoldOperationResult(input2,result4);return input2.kind==="setup"&&input2.emitJson?{jsonPayload:result4.machinePayload,operation:operationResult}:operationResult}));var makeInitCommand=(operation=runRepositoryScaffoldingApplication)=>exports_Command.make(initCommandMetadata.name,{baseline:baselineOption2(initCommandMetadata),output:outputOption(initCommandMetadata),refreshBaseline:refreshBaselineOption2(initCommandMetadata)},({output:output2,baseline,refreshBaseline})=>gen2(function*runInitCommand(){const outputMode=yield*SelectedOutputMode;if(outputMode!=="interactive"){return yield*new CliValidationError({message:outputMode==="json"?"`hi init` requires interactive input and is unavailable in JSON mode.":"`hi init` requires interactive input and is unavailable when output is redirected.",recoveryCommand:"hi init"})}return yield*captureCommandResult(executeScaffoldCommand({baseline:getOrUndefined(baseline),kind:"init",outputDirectory:path10.resolve(process.cwd(),getOrElse(output2,()=>".")),refreshBaseline},operation))})).pipe(withCommandMetadata(initCommandMetadata));var makeScaffoldCommand=(operation=runRepositoryScaffoldingApplication)=>exports_Command.make(scaffoldCommandMetadata.name,{baseline:baselineOption2(scaffoldCommandMetadata),input:inputOption2,json:jsonOption3,output:outputOption(scaffoldCommandMetadata),refreshBaseline:refreshBaselineOption2(scaffoldCommandMetadata),repoShape:repoShapeOption,yes:yesOption},({input:input2,output:output2,json:json3,repoShape,baseline,refreshBaseline,yes})=>gen2(function*runScaffoldCommand(){const selectedOutputMode=yield*SelectedOutputMode;const emitJson=json3||selectedOutputMode==="json";return yield*captureCommandResult(executeScaffoldCommand({assumeYes:yes||selectedOutputMode!=="interactive",baseline:getOrUndefined(baseline),emitJson,kind:"setup",...isSome2(output2)?{outputDirectory:path10.resolve(process.cwd(),output2.value)}:{},refreshBaseline,repoShape:getOrElse(repoShape,()=>"auto"),scanDirectory:path10.resolve(process.cwd(),getOrElse(input2,()=>".")),toolStdio:selectedOutputMode==="interactive"?"inherit":"ignore"},operation).pipe(selectedOutputMode==="interactive"?(effect2)=>effect2:provideService2(RepositoryScaffoldingInteraction,silentNonInteractiveScaffoldingInteraction)))})).pipe(withCommandMetadata(scaffoldCommandMetadata));var initCommand=makeInitCommand();var scaffoldCommand=makeScaffoldCommand();var skillsCommandMetadata=declareCommandMetadata({examples:[{command:"hi skills rename",summary:"Migrate legacy operator skills."}],group:"commands",interaction:"none",name:"skills",options:[],outputModes:["interactive","plain","json"],summary:"Deprecated operator-skill compatibility commands."});var skillsRenameCommandMetadata=declareCommandMetadata({examples:[{command:"hi skills rename",summary:"Delegate to operator migration."}],group:"skills",interaction:"none",name:"rename",options:[],outputModes:["interactive","plain","json"],summary:"Deprecated alias for `hi operator migrate`."});var skillsRenameOperationResult=(operation)=>({...operation,warnings:[...operation.warnings,{code:"skills-rename-deprecated",subject:"hi operator migrate"}]});var skillsRenameCommand=exports_Command.make(skillsRenameCommandMetadata.name,{},()=>captureCommandResult(executeOperatorCommand("migrate").pipe(map7(skillsRenameOperationResult)))).pipe(withCommandMetadata(skillsRenameCommandMetadata));var skillsCommandRoot=exports_Command.make(skillsCommandMetadata.name,{},()=>captureCommandResult(succeed6({changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[{code:"skills-command-deprecated",subject:"hi operator"}]}))).pipe(withCommandMetadata(skillsCommandMetadata));var skillsCommand=skillsCommandRoot.pipe(exports_Command.withSubcommands([skillsRenameCommand]));import path11 from"node:path";class ToolEnsureOperationFailure extends TaggedErrorClass()("@punks/cli/tool-ensure/ToolEnsureOperationFailure",{cause:Defect(),message:String5,operation:Literal2("ensure-tools")}){}var ToolEnsureOperations=Service("@punks/cli/features/tool-ensure/ToolEnsureOperations");var baselineToolIds=["agent-browser","opensrc","portless","skills"];var requiredToolsForSkills=(skillIds,baseline)=>[...new Set([...baselineToolIds,...baseline.skills.filter((skill)=>skillIds.includes(skill.id)).flatMap((skill)=>skill.requiresTools)])].toSorted();var ensureTools=({baseline,rootDirectory,capabilities,runtime,stdio="inherit"})=>{const settings=capabilities.readSettings(rootDirectory);const toolIds=settings?.requiredTools??requiredToolsForSkills([],baseline);const statuses=capabilities.ensureTools(toolIds,baseline,runtime,{mode:"refresh-latest",stdio});return{hasFailures:statuses.some((status2)=>status2.status==="failed"),rootDirectory,statuses,toolIds}};var runToolEnsureApplication=fn2("ToolEnsure.run")(function*runToolEnsureApplication2(input2){const operations=yield*ToolEnsureOperations;return yield*operations.run(input2)});var toolsCommandMetadata=declareCommandMetadata({examples:[{command:"hi tools ensure",summary:"Ensure required tools are installed."}],group:"commands",interaction:"none",name:"tools",options:[],outputModes:["interactive","plain","json"],summary:"Manage external Harness tool requirements."});var toolsEnsureCommandMetadata=declareCommandMetadata({examples:[{command:"hi tools ensure",summary:"Refresh the selected managed toolchain."}],group:"tools",interaction:"none",name:"ensure",options:[{name:"input",summary:"Scaffolded repository root to inspect. Defaults to the current working directory."},{name:"baseline",summary:"Trusted scaffold baseline: stable, bundled, or an exact version. Defaults to stable."},{name:"refresh-baseline",summary:"Refetch the stable baseline instead of reusing the local cache."}],outputModes:["interactive","plain","json"],summary:"Refresh auto-managed required tools to trusted latest targets; validate manual platform tools without upgrading them."});var toolsRootOperation=succeed6({changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[]});var toolEnsureStatus=(changeCount,issueCount)=>{if(issueCount>0){return changeCount>0?"partial":"failed"}return changeCount>0?"success":"no-op"};var inputOption3=exports_Flag.optional(exports_Flag.string(metadataOptionName(toolsEnsureCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(toolsEnsureCommandMetadata,"input")));var baselineOption3=exports_Flag.optional(exports_Flag.string(metadataOptionName(toolsEnsureCommandMetadata,"baseline")).pipe(withOptionMetadata(toolsEnsureCommandMetadata,"baseline")));var refreshBaselineOption3=exports_Flag.boolean(metadataOptionName(toolsEnsureCommandMetadata,"refresh-baseline")).pipe(withOptionMetadata(toolsEnsureCommandMetadata,"refresh-baseline"));var toolEnsureOperationResult=(result4)=>{const changes=result4.statuses.filter((status2)=>status2.status==="installed").map((status2)=>({action:"install",state:"completed",subject:status2.toolId}));const issues=result4.statuses.filter((status2)=>status2.status==="failed").map((status2)=>({action:"install",code:"tool-install-failed",errorMessage:status2.errorMessage,kind:"handled-failure",subject:status2.toolId}));return{changes,degradations:[],issues,nextActions:issues.length>0?[{kind:"retry",subject:"required-tools"}]:[{kind:"none"}],status:toolEnsureStatus(changes.length,issues.length),warnings:[]}};var executeToolsEnsureCommand=(input2,operation=runToolEnsureApplication)=>gen2(function*ensureRequiredTools(){const result4=yield*operation(input2);return toolEnsureOperationResult(result4)});var toolsEnsureCommand=exports_Command.make(toolsEnsureCommandMetadata.name,{baseline:baselineOption3,input:inputOption3,refreshBaseline:refreshBaselineOption3},({input:input2,baseline,refreshBaseline})=>gen2(function*ensureTools2(){const outputMode=yield*SelectedOutputMode;return yield*captureCommandResult(executeToolsEnsureCommand({baseline:getOrUndefined(baseline),refreshBaseline,rootDirectory:path11.resolve(process.cwd(),getOrElse(input2,()=>".")),stdio:outputMode==="interactive"?"inherit":"ignore"}))})).pipe(withCommandMetadata(toolsEnsureCommandMetadata));var toolsCommandRoot=exports_Command.make(toolsCommandMetadata.name,{},()=>captureCommandResult(toolsRootOperation)).pipe(withCommandMetadata(toolsCommandMetadata));var toolsCommand=toolsCommandRoot.pipe(exports_Command.withSubcommands([toolsEnsureCommand]));import path12 from"node:path";var updateCommandMetadata=declareCommandMetadata({examples:[{command:"hi update --check",summary:"Preview managed scaffold updates."}],group:"commands",interaction:"optional",name:"update",options:[{name:"input",summary:"Scaffolded repository root to update. Defaults to the current working directory."},{name:"check",summary:"Preview managed scaffold updates, write nothing, and exit nonzero when updates are available."},{name:"write",summary:"Apply managed scaffold updates without asking for confirmation."},{name:"yes",summary:"Apply managed scaffold updates without asking for confirmation."},{name:"json",summary:"Print the machine-readable update payload to stdout."},{name:"baseline",summary:"Scaffold baseline to use: stable, bundled, or an exact version. Defaults to stable."},{name:"refresh-baseline",summary:"Refetch the stable baseline instead of reusing the local cache."}],outputModes:["interactive","plain","json"],summary:"Refresh managed scaffold assets from the recorded .devpunks scaffold manifest."});var inputOption4=exports_Flag.optional(exports_Flag.string(metadataOptionName(updateCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(updateCommandMetadata,"input")));var checkOption=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"check")).pipe(withOptionMetadata(updateCommandMetadata,"check"));var writeOption=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"write")).pipe(withOptionMetadata(updateCommandMetadata,"write"));var yesOption2=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"yes")).pipe(withOptionMetadata(updateCommandMetadata,"yes"));var jsonOption4=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"json")).pipe(withOptionMetadata(updateCommandMetadata,"json"));var baselineOption4=exports_Flag.optional(exports_Flag.string(metadataOptionName(updateCommandMetadata,"baseline")).pipe(withOptionMetadata(updateCommandMetadata,"baseline")));var refreshBaselineOption4=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"refresh-baseline")).pipe(withOptionMetadata(updateCommandMetadata,"refresh-baseline"));var silentNonInteractiveUpdateInteraction={confirmApply:()=>succeed6(false),emit:()=>void_3};var executeUpdateCommand=(input2,operation=runScaffoldUpdateApplication)=>scoped2(gen2(function*executeUpdate(){const result4=yield*operation(input2);return input2.emitJson?{jsonPayload:publicUpdateResult(result4),operation:result4.operation}:result4}));var makeUpdateCommand=(operation=runScaffoldUpdateApplication)=>exports_Command.make(updateCommandMetadata.name,{baseline:baselineOption4,check:checkOption,input:inputOption4,json:jsonOption4,refreshBaseline:refreshBaselineOption4,write:writeOption,yes:yesOption2},({input:input2,check:check3,write:write2,yes,json:json3,baseline,refreshBaseline})=>gen2(function*runUpdateCommand(){const selectedOutputMode=yield*SelectedOutputMode;return yield*captureCommandResult(executeUpdateCommand({baseline:getOrUndefined(baseline),check:check3,emitJson:json3||selectedOutputMode==="json",refreshBaseline,rootDirectory:path12.resolve(process.cwd(),getOrElse(input2,()=>".")),toolStdio:selectedOutputMode==="interactive"?"inherit":"ignore",write:write2,yes},operation).pipe(selectedOutputMode==="interactive"?(effect2)=>effect2:provideService2(UpdateInteraction,silentNonInteractiveUpdateInteraction)))})).pipe(withCommandMetadata(updateCommandMetadata));var updateCommand=makeUpdateCommand();import{spawnSync}from"node:child_process";import{existsSync as existsSync4,realpathSync}from"node:fs";var parseSemver=(value5)=>{const match8=value5.match(/^v?(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-(?<prerelease>[0-9A-Za-z.-]+))?$/u);if(match8===null){return null}return{major:Number.parseInt(match8[1],10),minor:Number.parseInt(match8[2],10),patch:Number.parseInt(match8[3],10),prerelease:match8[4]??null}};var isNumericPrereleaseIdentifier=(value5)=>/^(?<zero>0|[1-9]\d*)$/u.test(value5);var comparePrerelease2=(candidate,current)=>{const candidateParts=candidate.split(".");const currentParts=current.split(".");const maxLength=Math.max(candidateParts.length,currentParts.length);for(let index2=0;index2<maxLength;index2+=1){const candidatePart=candidateParts[index2];const currentPart=currentParts[index2];if(candidatePart===undefined){return-1}if(currentPart===undefined){return 1}if(candidatePart===currentPart){continue}const candidateIsNumeric=isNumericPrereleaseIdentifier(candidatePart);const currentIsNumeric=isNumericPrereleaseIdentifier(currentPart);if(candidateIsNumeric&&currentIsNumeric){return Number.parseInt(candidatePart,10)>Number.parseInt(currentPart,10)?1:-1}if(candidateIsNumeric!==currentIsNumeric){return candidateIsNumeric?-1:1}return candidatePart>currentPart?1:-1}return 0};var isNewerVersion=(candidate,current)=>{const parsedCandidate=parseSemver(candidate);const parsedCurrent=parseSemver(current);if(parsedCandidate===null||parsedCurrent===null){return false}if(parsedCandidate.major!==parsedCurrent.major){return parsedCandidate.major>parsedCurrent.major}if(parsedCandidate.minor!==parsedCurrent.minor){return parsedCandidate.minor>parsedCurrent.minor}if(parsedCandidate.patch!==parsedCurrent.patch){return parsedCandidate.patch>parsedCurrent.patch}if(parsedCandidate.prerelease!==null&&parsedCurrent.prerelease!==null){return comparePrerelease2(parsedCandidate.prerelease,parsedCurrent.prerelease)>0}return parsedCurrent.prerelease!==null&&parsedCandidate.prerelease===null};var readTaggedVersion=async({packageName,registry="https://registry.npmjs.org",tag:tag4,timeoutMs})=>{if(typeof fetch!=="function"){return null}const controller=new AbortController;const timeout3=setTimeout(()=>controller.abort(),timeoutMs);try{const response=await fetch(`${registry.replace(/\/+$/u,"")}/${encodeURIComponent(packageName)}/${encodeURIComponent(tag4)}`,{headers:{accept:"application/json"},signal:controller.signal});if(!response.ok){return null}const payload=await response.json();return typeof payload.version==="string"?payload.version:null}catch{return null}finally{clearTimeout(timeout3)}};var checkSelfUpdate=async({currentVersion,packageName,registry,tag:tag4="latest",timeoutMs=750})=>{const latestVersion=await readTaggedVersion({packageName,...registry===undefined?{}:{registry},tag:tag4,timeoutMs});if(latestVersion===null){return null}return{currentVersion,latestVersion,packageName,tag:tag4,updateAvailable:isNewerVersion(latestVersion,currentVersion)}};var looksLikePath=(value5)=>value5.includes("/")||value5.includes("\\")||existsSync4(value5);var defaultEntrypointCandidates=()=>[process.argv[1]??"",process.execPath].filter((value5)=>value5.length>0);var packageManagerForRuntimePath=(runtimePath)=>{const normalizedEntrypoint=runtimePath.toLowerCase();if(normalizedEntrypoint.includes("/.bun/")||normalizedEntrypoint.includes("\\.bun\\")||normalizedEntrypoint.includes("/install/global/node_modules/@punks/cli/")||normalizedEntrypoint.includes("\\install\\global\\node_modules\\@punks\\cli\\")){return"bun"}if(normalizedEntrypoint.includes("/pnpm/")||normalizedEntrypoint.includes("\\pnpm\\")||normalizedEntrypoint.includes("/.pnpm/")){return"pnpm"}if(normalizedEntrypoint.includes("/yarn/")||normalizedEntrypoint.includes("\\yarn\\")||normalizedEntrypoint.includes("/.yarn/")){return"yarn"}if(normalizedEntrypoint.includes("/node_modules/@punks/cli/")||normalizedEntrypoint.includes("\\node_modules\\@punks\\cli\\")){return"npm"}return null};var detectCliInstallPackageManager=({entrypoint,userAgent}={})=>{const entrypointCandidates=entrypoint===undefined?defaultEntrypointCandidates():[entrypoint];const runtimePaths=entrypointCandidates.flatMap((candidate)=>{if(candidate.length===0||!looksLikePath(candidate)){return[]}try{return[candidate,realpathSync(candidate)]}catch{return[candidate]}});for(const runtimePath of runtimePaths){const packageManager=packageManagerForRuntimePath(runtimePath);if(packageManager!==null){return packageManager}}if(runtimePaths.length>0){return null}if(userAgent?.startsWith("bun/")===true){return"bun"}if(userAgent?.startsWith("pnpm/")===true){return"pnpm"}if(userAgent?.startsWith("yarn/")===true){return"yarn"}if(userAgent?.startsWith("npm/")===true){return"npm"}return null};var globalInstallCommandForPackageManager=({packageManager,packageName,tag:tag4})=>{const specifier=`${packageName}@${tag4}`;switch(packageManager){case"bun":{return["bun","add","-g",specifier,"--minimum-release-age=0"]}case"pnpm":{return["pnpm","add","-g",specifier]}case"npm":{return["npm","install","-g",specifier,"--min-release-age=0"]}case"yarn":{return["yarn","global","add",specifier]}default:{return packageManager}}};var minimumReleaseAgeEnvironmentForPackageManager=(packageManager)=>{switch(packageManager){case"pnpm":{return{npm_config_minimum_release_age:"0"}}case"yarn":{return{YARN_NPM_MINIMAL_AGE_GATE:"0"}}case"bun":case"npm":{return{}}default:{return packageManager}}};var runCliInstallCommand=({baseEnvironment={},command,environment})=>{const result4=spawnSync(command[0],command.slice(1),{env:{...baseEnvironment,...environment},stdio:"inherit"});return result4.status===0};var autoUpdateCliIfStale=async({currentVersion,packageName,tag:tag4="latest",timeoutMs=750,entrypoint,runtime={}})=>{const check3=await checkSelfUpdate({currentVersion,packageName,...runtime.npmRegistry===undefined?{}:{registry:runtime.npmRegistry},tag:tag4,timeoutMs});if(check3===null){return{check:check3,status:"unavailable"}}if(!check3.updateAvailable){return{check:check3,status:"current"}}const packageManager=detectCliInstallPackageManager({...entrypoint===undefined?{}:{entrypoint},...runtime.npmUserAgent===undefined?{}:{userAgent:runtime.npmUserAgent}});if(packageManager===null){return{check:check3,command:null,packageManager,status:"manager-not-detected"}}const command=globalInstallCommandForPackageManager({packageManager,packageName,tag:tag4});const environment=minimumReleaseAgeEnvironmentForPackageManager(packageManager);return{check:check3,command,environment,packageManager,status:"available"}};var upgradeCli=async({currentVersion,packageName,tag:tag4="latest",timeoutMs=5000,entrypoint,force=false,runtime={}})=>{const check3=await checkSelfUpdate({currentVersion,packageName,...runtime.npmRegistry===undefined?{}:{registry:runtime.npmRegistry},tag:tag4,timeoutMs});if(check3===null){return{check:check3,status:"unavailable"}}if(!check3.updateAvailable&&!force){return{check:check3,status:"current"}}const packageManager=detectCliInstallPackageManager({...entrypoint===undefined?{}:{entrypoint},...runtime.npmUserAgent===undefined?{}:{userAgent:runtime.npmUserAgent}});if(packageManager===null){return{check:check3,command:null,packageManager,status:"manager-not-detected"}}const command=globalInstallCommandForPackageManager({packageManager,packageName,tag:tag4});const environment=minimumReleaseAgeEnvironmentForPackageManager(packageManager);if(runCliInstallCommand({...runtime.commandEnvironment===undefined?{}:{baseEnvironment:runtime.commandEnvironment},command,environment})){return{check:check3,command,environment,packageManager,status:"upgraded"}}return{check:check3,command,packageManager,status:"failed"}};import{tmpdir as tmpdir3}from"node:os";import path13 from"node:path";var CliControlPlaneConfig=Service("@punks/cli/CliControlPlaneConfig");var CliReleaseConfig=Service("@punks/cli/CliReleaseConfig");var CliRuntimeConfig=Service("@punks/cli/CliRuntimeConfig");var controlPlaneEnvironment=makeEnvironmentConfig(Struct({CI:optional(String5),DP_CONTROL_PLANE_URL:optional(URLFromString),DP_DISABLE_BUNDLED_CONTROL_PLANE_URL:optional(Literals(["0","1"])),DP_TELEMETRY_SOURCE:optional(String5),NODE_ENV:optional(String5),VITEST:optional(String5)}));var releaseEnvironment=makeEnvironmentConfig(Struct({DP_BASELINE:optional(NonEmptyString),DP_BASELINE_REFRESH:optional(Literals(["0","1"])),DP_BASELINE_URL:optional(URLFromString),DP_UPDATE_TAG:optional(NonEmptyString),GH_TOKEN:optional(EnvironmentSecret),GITHUB_TOKEN:optional(EnvironmentSecret),HOME:optional(NonEmptyString),XDG_CACHE_HOME:optional(NonEmptyString)}));var runtimeEnvironment=makeEnvironmentConfig(Struct({CI:optional(String5),COLORFGBG:optional(String5),DP_SCRIPT_RUNTIME:optional(NonEmptyString),FORCE_COLOR:optional(String5),HI_NO_SKILL_UPDATE_CHECK:optional(Literals(["0","1"])),HI_NO_UPDATE_CHECK:optional(Literals(["0","1"])),HI_STARTUP_CHECK_CLI:optional(Literals(["0","1"])),HI_STARTUP_CHECK_INTERVAL_MS:optional(NumberFromString.check(isInt(),isGreaterThanOrEqualTo3(0))),HI_STARTUP_CHECK_SKILL:optional(Literals(["0","1"])),HI_STARTUP_CHECK_WORKER:optional(Literals(["0","1"])),HI_THEME:optional(Literals(["dark","light"])),HI_UPDATE_TAG:optional(NonEmptyString),NO_COLOR:optional(String5),NPM_CONFIG_REGISTRY:optional(URLFromString),npm_config_registry:optional(URLFromString),npm_config_user_agent:optional(String5)}));var stripTrailingSlashes=(value5)=>value5.toString().replace(/\/+$/u,"");var commandEnvironmentKeys=["AGENT_BROWSER_EXECUTABLE_PATH","ALL_PROXY","APPDATA","BUN_INSTALL","CI","COLORTERM","COMSPEC","CLAUDE_CODE","CLAUDE_PROJECT_DIR","CODEX_HOME","CODEX_THREAD_ID","DISPLAY","DP_SCRIPT_RUNTIME","DP_NO_CLIPBOARD","FORCE_COLOR","GH_CONFIG_DIR","HI_NO_SKILL_UPDATE_CHECK","HI_NO_UPDATE_CHECK","HI_OPERATOR_AGENT","HI_OPERATOR_MIGRATION_RETRY","HI_OPERATOR_MUTATION_RETRY","HI_STARTUP_CHECK_CLI","HI_STARTUP_CHECK_INTERVAL_MS","HI_STARTUP_CHECK_SKILL","HI_STARTUP_CHECK_WORKER","HI_THEME","HI_UPDATE_TAG","HOME","HTTP_PROXY","HTTPS_PROXY","LANG","LC_ALL","LOCALAPPDATA","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_ENV","NO_COLOR","NO_PROXY","NPM_CONFIG_REGISTRY","PATH","PATHEXT","Path","SHELL","SSL_CERT_DIR","SSL_CERT_FILE","SYSTEMROOT","TEMP","TERM","TMP","TMPDIR","USERPROFILE","VITEST","WAYLAND_DISPLAY","WINDIR","XAUTHORITY","XDG_CACHE_HOME","XDG_CONFIG_HOME","XDG_RUNTIME_DIR","all_proxy","http_proxy","https_proxy","no_proxy","npm_config_registry","npm_config_user_agent"];var commandEnvironment=(input2)=>Object.fromEntries(commandEnvironmentKeys.flatMap((key)=>input2[key]===undefined?[]:[[key,input2[key]]]));var loadCliRuntimeConfiguration=(provider,input2)=>decodeEnvironment({config:runtimeEnvironment,name:"CLI runtime",provider}).pipe(map7((environment)=>{const ciPresent=input2.CI!==undefined||environment.CI!==undefined;const forceColor=input2.FORCE_COLOR??environment.FORCE_COLOR;const noColorPresent=input2.NO_COLOR!==undefined||environment.NO_COLOR!==undefined;return{commandEnvironment:commandEnvironment(input2),forceColor:forceColor!==undefined&&forceColor!=="0",noColor:noColorPresent,npmRegistry:(environment.npm_config_registry?.toString()??environment.NPM_CONFIG_REGISTRY?.toString()??"https://registry.npmjs.org").replace(/\/+$/u,""),...environment.npm_config_user_agent===undefined?{}:{npmUserAgent:environment.npm_config_user_agent},scriptRuntimePath:environment.DP_SCRIPT_RUNTIME??"node",skillUpdateChecksEnabled:environment.HI_NO_SKILL_UPDATE_CHECK!=="1"&&!ciPresent,startupCheckCli:environment.HI_STARTUP_CHECK_CLI==="1",startupCheckIntervalMs:environment.HI_STARTUP_CHECK_INTERVAL_MS??12*60*60*1000,startupCheckSkill:environment.HI_STARTUP_CHECK_SKILL==="1",startupWorker:environment.HI_STARTUP_CHECK_WORKER==="1",updateChecksEnabled:environment.HI_NO_UPDATE_CHECK!=="1"&&!ciPresent,updateTag:environment.HI_UPDATE_TAG??"latest",...environment.HI_THEME===undefined?{}:{terminalTheme:environment.HI_THEME},...environment.COLORFGBG===undefined?{}:{colorForegroundBackground:environment.COLORFGBG}}}));var makeCliConfigLayer=(provider,input2={})=>mergeAll2(effect(CliControlPlaneConfig,decodeEnvironment({config:controlPlaneEnvironment,name:"CLI control plane",provider}).pipe(map7((environment)=>{let telemetrySource;const ciPresent=input2.CI!==undefined||environment.CI!==undefined;const vitestPresent=input2.VITEST!==undefined||environment.VITEST!==undefined;if(ciPresent){telemetrySource="ci"}else if(environment.DP_TELEMETRY_SOURCE==="debug"){telemetrySource="debug"}else if(environment.NODE_ENV==="test"||vitestPresent){telemetrySource="test"}return{disableBundledUrl:environment.DP_DISABLE_BUNDLED_CONTROL_PLANE_URL==="1",...environment.DP_CONTROL_PLANE_URL===undefined?{}:{baseUrl:stripTrailingSlashes(environment.DP_CONTROL_PLANE_URL)},...telemetrySource===undefined?{}:{telemetrySource}}}))),effect(CliReleaseConfig,decodeEnvironment({config:releaseEnvironment,name:"CLI release",provider}).pipe(map7((environment)=>{const githubToken=environment.GH_TOKEN??environment.GITHUB_TOKEN;return{cacheDirectory:environment.XDG_CACHE_HOME??path13.join(environment.HOME??tmpdir3(),".cache"),refreshBaseline:environment.DP_BASELINE_REFRESH==="1",updateTag:environment.DP_UPDATE_TAG??"latest",...environment.DP_BASELINE===undefined?{}:{baseline:environment.DP_BASELINE},...environment.DP_BASELINE_URL===undefined?{}:{baselineUrl:stripTrailingSlashes(environment.DP_BASELINE_URL)},...githubToken===undefined?{}:{githubToken}}}))),effect(CliRuntimeConfig,loadCliRuntimeConfiguration(provider,input2)));var upgradeCommandMetadata=declareCommandMetadata({examples:[{command:"hi upgrade",summary:"Upgrade the installed CLI."}],group:"commands",interaction:"none",name:"upgrade",options:[{name:"tag",summary:"npm dist-tag to install, for example `latest`, `next`, or `beta`."},{name:"force",summary:"Reinstall the selected dist-tag even when the current version is fresh."},{name:"json",summary:"Print JSON output."}],outputModes:["interactive","plain","json"],summary:"Upgrade this CLI through the package manager used for its global install."});var tagOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(upgradeCommandMetadata,"tag")).pipe(withOptionMetadata(upgradeCommandMetadata,"tag")));var forceOption=exports_Flag.boolean(metadataOptionName(upgradeCommandMetadata,"force")).pipe(withOptionMetadata(upgradeCommandMetadata,"force"));var jsonOption5=exports_Flag.boolean(metadataOptionName(upgradeCommandMetadata,"json")).pipe(withOptionMetadata(upgradeCommandMetadata,"json"));var posixSafeComponent=/^[A-Za-z0-9_@%+=:,./-]+$/u;var windowsUnsafeComponent=/[\r\n"%]/u;var quotePosixComponent=(value5)=>posixSafeComponent.test(value5)?value5:`'${value5.replaceAll("'",`'"'"'`)}'`;var quoteWindowsComponent=(value5)=>{if(windowsUnsafeComponent.test(value5)){return}const trailingBackslashes=value5.match(/\\+$/u)?.[0]??"";return`"${value5}${trailingBackslashes}"`};var formatUpgradeRecoveryCommand=({command,environment,platform})=>{if(command.length===0||command.some((component)=>component.includes("\x00"))){return}const environmentEntries=Object.entries(environment);if(environmentEntries.some(([key,value5])=>key.length===0||key.includes("=")||value5.includes("\x00"))){return}if(platform==="win32"){const commandComponents=command.map(quoteWindowsComponent);const assignments=[];for(const[key,value5]of environmentEntries){if(windowsUnsafeComponent.test(key)||windowsUnsafeComponent.test(value5)){return}assignments.push(`set "${key}=${value5}"&&`)}if(commandComponents.some((component)=>component===undefined)){return}return`cmd.exe /d /v:off /s /c "${[...assignments,...commandComponents].join(" ")}"`}return[...environmentEntries.length===0?[]:["env"],...environmentEntries.map(([key,value5])=>quotePosixComponent(`${key}=${value5}`)),...command.map(quotePosixComponent)].join(" ")};var upgradeOperationResult=(result4)=>{switch(result4.status){case"upgraded":{return{changes:[{action:"upgrade",state:"completed",subject:result4.check.packageName}],degradations:[],facts:{command:result4.command,currentVersion:result4.check.currentVersion,environment:result4.environment,kind:"cli-upgrade",latestVersion:result4.check.latestVersion,packageManager:result4.packageManager,packageName:result4.check.packageName,status:result4.status,tag:result4.check.tag},issues:[],nextActions:[{kind:"none"}],status:"success",warnings:[]}}case"current":{return result4.check===null?undefined:{changes:[],degradations:[],facts:{command:null,currentVersion:result4.check.currentVersion,environment:{},kind:"cli-upgrade",latestVersion:result4.check.latestVersion,packageManager:null,packageName:result4.check.packageName,status:result4.status,tag:result4.check.tag},issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[]}}default:{return}}};var upgradeExpectedFailure=(result4,platform=process.platform)=>{const recoveryCommand=(()=>{if(!("command"in result4)||result4.command===null){return result4.check===null?undefined:formatUpgradeRecoveryCommand({command:["npm","install","-g",`${result4.check.packageName}@${result4.check.tag}`],environment:{},platform})}return formatUpgradeRecoveryCommand({command:result4.command,environment:"environment"in result4?result4.environment:{},platform})})();switch(result4.status){case"current":{return result4.check===null?new CliValidationError({message:"Could not read the npm registry version for this CLI."}):undefined}case"unavailable":{return new CliValidationError({message:"Could not read the npm registry version for this CLI."})}case"manager-not-detected":{return new CliValidationError({message:"Could not detect how this CLI was installed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"available":{return new CliValidationError({message:"Upgrade command was not executed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"failed":{return new CliValidationError({message:"CLI upgrade failed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"upgraded":{return}default:{return result4}}};var makeUpgradeCommand=(operation=upgradeCli)=>exports_Command.make(upgradeCommandMetadata.name,{force:forceOption,json:jsonOption5,tag:tagOption},({tag:tag4,force,json:_json})=>captureCommandResult(gen2(function*executeUpgradeCommand(){const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const result4=yield*tryPromise2({catch:()=>new CliValidationError({message:"CLI upgrade failed."}),try:()=>operation({currentVersion:version2,force,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:getOrElse(tag4,()=>release.updateTag)})});const failure=upgradeExpectedFailure(result4);if(failure!==undefined){return yield*fail6(failure)}return upgradeOperationResult(result4)}))).pipe(withCommandMetadata(upgradeCommandMetadata));var upgradeCommand=makeUpgradeCommand();var registration=(command,commandMetadata,children=[])=>({children,command,metadata:commandMetadata});var operatorChildren=[registration(operatorSubcommands[0],operatorStatusCommandMetadata),registration(operatorSubcommands[1],operatorInstallCommandMetadata),registration(operatorSubcommands[2],operatorUpdateCommandMetadata),registration(operatorSubcommands[3],operatorMigrateCommandMetadata)];var rootRegistrations=[registration(checkCommand,checkCommandMetadata),registration(ensureCommand,ensureCommandMetadata),registration(initCommand,initCommandMetadata),registration(operatorCommandRoot,operatorCommandMetadata,operatorChildren),registration(reportCommand,reportCommandMetadata),registration(scaffoldCommand,scaffoldCommandMetadata),registration(skillsCommandRoot,skillsCommandMetadata,[registration(skillsRenameCommand,skillsRenameCommandMetadata)]),registration(toolsCommandRoot,toolsCommandMetadata,[registration(toolsEnsureCommand,toolsEnsureCommandMetadata)]),registration(updateCommand,updateCommandMetadata),registration(upgradeCommand,upgradeCommandMetadata)];var flatten4=(registrations)=>registrations.flatMap(({children,metadata:commandMetadata})=>[commandMetadata,...flatten4(children)]);var resolveRegistrations=(nodes,parentPath=[])=>nodes.map((node)=>{if(node.command.name!==node.metadata.name){throw new CommandMetadataError(`Executable command '${node.command.name}' does not match metadata name '${node.metadata.name}'.`)}const[first,...rest]=parentPath;const path14=first===undefined?[node.metadata.name]:[first,...rest,node.metadata.name];return{children:resolveRegistrations(node.children,path14),command:node.command,metadata:commandMetadataFromDeclaration(path14,node.metadata)}});var buildRegisteredCommand=(node)=>{const children=node.children.map((child)=>buildRegisteredCommand(child));return children.length===0?node.command:exports_Command.withSubcommands(node.command,children)};var buildCommandRegistry=(rootCommand,registrations)=>{const executableCommands=registrations.map((node)=>buildRegisteredCommand(node));const resolvedRegistrations=resolveRegistrations(registrations);const reference=createCommandMetadataRegistry(flatten4(resolvedRegistrations));const discovery=reference.map(({path:commandPath,summary})=>({path:[...commandPath],summary}));return{command:exports_Command.withSubcommands(rootCommand,executableCommands),commands:reference,discovery,reference,registrations:resolvedRegistrations}};var rootCommand=exports_Command.make("hi",{},()=>void_3).pipe(exports_Command.withDescription("Harness Intelligence CLI. Agents: activate $hi-cli before acting on generated output."));var commandRegistry=buildCommandRegistry(rootCommand,rootRegistrations);import{execFileSync as execFileSync2}from"node:child_process";import{homedir as homedir2}from"node:os";import path19 from"node:path";import{existsSync as existsSync5,readFileSync as readFileSync5,readdirSync as readdirSync3}from"node:fs";import path14 from"node:path";class CliDetectionError extends TaggedErrorClass()("CliDetectionError",{cause:optional(Defect()),message:String5}){}var ignoredDirectoryNames=new Set([".git",".agents",".claude",".codex",".cursor",".devpunks",".devpunks-cache",".next",".opencode",".source",".turbo","coverage","dist","docs","examples","build","node_modules","opensrc","scripts","skills","test-fixtures","tmp","worktrees",".venv","venv","__pycache__"]);var detectionOrder=["nextjs","react","tanstack-query","elysia","trpc","drizzle","better-auth","effect","turborepo"];var languageDetectionOrder=["python","typescript"];var sourceLanguageExtensions=[{language:"python",pattern:/\.py$/u},{language:"typescript",pattern:/\.(?:ts|tsx)$/u}];var conventionalWorkspaceRoots=["apps","packages","services","libs"];var wikiRootPaths=new Set(["app/wiki","apps/wiki","wiki"]);var isRecord4=(value5)=>typeof value5==="object"&&value5!==null;var dependencyRecordSchema=Record(String5,String5);var packageJsonSchema=fromJsonString2(Struct({dependencies:optional(dependencyRecordSchema),devDependencies:optional(dependencyRecordSchema),name:optional(String5),optionalDependencies:optional(dependencyRecordSchema),peerDependencies:optional(dependencyRecordSchema),workspaces:optional(Unknown2)}));var parsePackageJsonRecord=decodeUnknownSync2(packageJsonSchema);var decodeWorkspacePackages=decodeUnknownSync2(ArraySchema(String5));var collectPackageNames=(pkg)=>{const names=new Set;const addEntries=(record3)=>{if(!record3){return}for(const name2 of Object.keys(record3)){names.add(name2)}};addEntries(pkg.dependencies);addEntries(pkg.devDependencies);addEntries(pkg.peerDependencies);addEntries(pkg.optionalDependencies);return[...names].toSorted()};var normalizeRelativePath=(relativePath)=>relativePath.split(path14.sep).join("/");var isWikiRelativePath=(relativePath)=>{const normalized=normalizeRelativePath(relativePath);return[...wikiRootPaths].some((wikiRoot)=>normalized===wikiRoot||normalized.startsWith(`${wikiRoot}/`))};var isWikiManifest=(manifest)=>isWikiRelativePath(manifest.relativePath);var packDetectionManifests=(manifests)=>manifests.filter((manifest)=>!isWikiManifest(manifest));var recursiveFindFiles=(cwd,filename)=>{const results=[];const visit2=(directory3)=>{for(const entry of readdirSync3(directory3,{withFileTypes:true})){if(ignoredDirectoryNames.has(entry.name)){continue}const absolutePath=path14.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}if(entry.isFile()&&entry.name===filename){results.push(absolutePath)}}};if(existsSync5(cwd)){visit2(cwd)}return results.toSorted()};var discoverConventionalWorkspacePackageJsonPaths=(cwd)=>conventionalWorkspaceRoots.flatMap((rootDirectoryName)=>{const rootDirectory=path14.join(cwd,rootDirectoryName);if(!existsSync5(rootDirectory)){return[]}return readdirSync3(rootDirectory,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path14.join(rootDirectory,entry.name,"package.json")).filter((manifestPath)=>existsSync5(manifestPath))});var discoverTopLevelPackageJsonPaths=(cwd)=>readdirSync3(cwd,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path14.join(cwd,entry.name,"package.json")).filter((manifestPath)=>existsSync5(manifestPath));var readPackageJsonWorkspacePatterns=(pkg)=>{const{workspaces}=pkg;if(isArray(workspaces)){return decodeWorkspacePackages(workspaces)}if(isRecord4(workspaces)&&isArray(workspaces.packages)){return decodeWorkspacePackages(workspaces.packages)}return[]};var readPnpmWorkspacePatterns=(cwd)=>{const workspacePath=path14.join(cwd,"pnpm-workspace.yaml");if(!existsSync5(workspacePath)){return[]}const patterns=[];let inPackagesSection=false;for(const rawLine of readFileSync5(workspacePath,"utf-8").split(/\r?\n/u)){const line=rawLine.trim();if(line==="packages:"){inPackagesSection=true;continue}if(!inPackagesSection){continue}if(line.startsWith("- ")){const pattern=line.slice(2).trim().replaceAll(/^['"]|['"]$/gu,"");if(pattern.length>0){patterns.push(pattern)}continue}if(line.length>0&&!line.startsWith("#")){break}}return patterns};var expandWorkspacePattern=(cwd,pattern)=>{if(pattern.endsWith("/*")){const baseDirectory=path14.join(cwd,pattern.slice(0,-2));if(!existsSync5(baseDirectory)){return[]}return readdirSync3(baseDirectory,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path14.join(baseDirectory,entry.name,"package.json")).filter((manifestPath2)=>existsSync5(manifestPath2)).toSorted()}if(pattern.includes("*")){return[]}const manifestPath=path14.join(cwd,pattern,"package.json");return existsSync5(manifestPath)?[manifestPath]:[]};var discoverPackageJsonPaths=(cwd)=>{const rootPackageJsonPath=path14.join(cwd,"package.json");const recursivePackageJsonPaths=recursiveFindFiles(cwd,"package.json");if(!existsSync5(rootPackageJsonPath)){return recursivePackageJsonPaths}const rootPackageJson=parsePackageJsonRecord(readFileSync5(rootPackageJsonPath,"utf-8"));const workspacePatterns=new Set([...readPackageJsonWorkspacePatterns(rootPackageJson),...readPnpmWorkspacePatterns(cwd)]);const workspacePackageJsonPaths=[...workspacePatterns].flatMap((pattern)=>expandWorkspacePattern(cwd,pattern));const conventionalWorkspacePackageJsonPaths=discoverConventionalWorkspacePackageJsonPaths(cwd);const topLevelPackageJsonPaths=discoverTopLevelPackageJsonPaths(cwd);return[...recursivePackageJsonPaths,...workspacePackageJsonPaths,...conventionalWorkspacePackageJsonPaths,...topLevelPackageJsonPaths].filter((value5,index2,values3)=>values3.indexOf(value5)===index2).toSorted()};var detectTechnologies=(manifests)=>{const packageNames=new Set(packDetectionManifests(manifests).flatMap((manifest)=>manifest.dependencies));const detected=new Set;const hasPackage=(packageName)=>packageNames.has(packageName);const hasPackagePrefix=(prefix)=>[...packageNames].some((packageName)=>packageName.startsWith(prefix));if(hasPackage("next")){detected.add("nextjs");detected.add("react")}if(hasPackage("react")||hasPackage("react-dom")){detected.add("react")}if(hasPackage("@tanstack/react-query")||hasPackage("@tanstack/query-core")||hasPackage("@tanstack/react-query-devtools")||hasPackage("@tanstack/react-query-persist-client")||hasPackage("@tanstack/query-persist-client-core")){detected.add("tanstack-query")}if(hasPackage("elysia")){detected.add("elysia")}if(hasPackagePrefix("@trpc/")){detected.add("trpc")}if(hasPackage("drizzle-orm")||hasPackage("drizzle-kit")){detected.add("drizzle")}if(hasPackage("better-auth")){detected.add("better-auth")}if(hasPackage("effect")||hasPackagePrefix("@effect/")){detected.add("effect")}if(hasPackage("turbo")){detected.add("turborepo")}return detectionOrder.filter((technology)=>detected.has(technology))};var hasPackageTrigger=(packageNames,trigger)=>trigger.endsWith("/")?[...packageNames].some((packageName)=>packageName.startsWith(trigger)):packageNames.has(trigger);var isSourceDirectoryPath=(cwd,directory3)=>path14.relative(cwd,directory3)!=="";var detectSourceLanguages=(cwd)=>{const detected=new Set;const visit2=(directory3)=>{for(const entry of readdirSync3(directory3,{withFileTypes:true})){if(ignoredDirectoryNames.has(entry.name)){continue}const absolutePath=path14.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}const relativePath=path14.relative(cwd,absolutePath);if(entry.isFile()&&isSourceDirectoryPath(cwd,directory3)&&!isWikiRelativePath(relativePath)){for(const{language,pattern}of sourceLanguageExtensions){if(pattern.test(entry.name)&&!entry.name.endsWith(".d.ts")){detected.add(language)}}}}};if(existsSync5(cwd)){visit2(cwd)}return languageDetectionOrder.filter((language)=>detected.has(language))};var detectLanguages=(cwd,manifests)=>{const packageNames=new Set(packDetectionManifests(manifests).flatMap((manifest)=>manifest.dependencies));const detected=new Set(detectSourceLanguages(cwd));if(hasPackageTrigger(packageNames,"typescript")){detected.add("typescript")}return languageDetectionOrder.filter((language)=>detected.has(language))};var detectMonorepoSignals=(cwd,manifests)=>{const signals=[];for(const workspacePath of recursiveFindFiles(cwd,"pnpm-workspace.yaml")){signals.push({path:workspacePath,type:"pnpm-workspace"})}for(const turboConfigPath of recursiveFindFiles(cwd,"turbo.json")){signals.push({path:turboConfigPath,type:"turbo-config"})}for(const manifest of manifests){const pkg=parsePackageJsonRecord(readFileSync5(manifest.path,"utf-8"));const{workspaces}=pkg;const hasWorkspaces=isArray(workspaces)||isRecord4(workspaces)&&isArray(workspaces.packages);if(hasWorkspaces){signals.push({path:manifest.path,type:"package-json-workspaces"})}}const workspaceManifests=manifests.filter((manifest)=>{const pkg=parsePackageJsonRecord(readFileSync5(manifest.path,"utf-8"));const{workspaces}=pkg;return!(isArray(workspaces)||isRecord4(workspaces)&&isArray(workspaces.packages))});if(workspaceManifests.length>1){signals.push({path:cwd,type:"workspace-packages"})}return signals.filter((signal,index2,allSignals)=>allSignals.findIndex((candidate)=>candidate.type===signal.type&&candidate.path===signal.path)===index2)};var detectRepository=(cwd)=>try_3({catch:(cause)=>new CliDetectionError({cause,message:"Failed to detect repository shape."}),try:()=>{const manifestPaths=discoverPackageJsonPaths(cwd);const manifests=manifestPaths.map((manifestPath)=>{const pkg=parsePackageJsonRecord(readFileSync5(manifestPath,"utf-8"));return{dependencies:collectPackageNames(pkg),packageName:pkg.name??null,path:manifestPath,relativePath:path14.relative(cwd,manifestPath)||"package.json"}});const detectedLanguages=detectLanguages(cwd,manifests);const detectedTechnologies=detectTechnologies(manifests);const monorepoSignals=detectMonorepoSignals(cwd,manifests);return{cwd,detectedLanguages,detectedTechnologies,manifests,monorepo:monorepoSignals.length>0,monorepoSignals}}});var manifestPaths=(result4)=>result4.manifests.map((manifest)=>path14.relative(result4.cwd,manifest.path)||"package.json");var applyRepoShapeMode=(result4,repoShapeMode)=>repoShapeMode==="auto"?result4:{...result4,monorepo:repoShapeMode==="monorepo"};var shouldUseClipboard=(environment)=>environment.VITEST!=="true"&&environment.NODE_ENV!=="test"&&environment.DP_NO_CLIPBOARD!=="1";import{existsSync as existsSync6,mkdirSync as mkdirSync3,readFileSync as readFileSync6,rmSync,writeFileSync as writeFileSync3}from"node:fs";import path15 from"node:path";var nodeFilesystem={exists:existsSync6,read:(filePath)=>readFileSync6(filePath,"utf-8"),remove:(filePath,options4)=>rmSync(filePath,{force:true,recursive:options4?.recursive??false}),write:(filePath,content)=>{mkdirSync3(path15.dirname(filePath),{recursive:true});writeFileSync3(filePath,content,"utf-8")}};var ScaffoldCapabilities=Service("@punks/cli/scaffold/ScaffoldCapabilities");import{existsSync as existsSync7,readFileSync as readFileSync7,writeFileSync as writeFileSync4}from"node:fs";import path16 from"node:path";var harnessDirectories=new Set([".agents",".claude",".codex",".cursor",".opencode"]);var normalizeGitignorePattern=(line)=>{const trimmed=line.trim();if(trimmed===""||trimmed.startsWith("#")||trimmed.startsWith("!")){return null}return trimmed.replace(/^\//u,"").replace(/\/\*\*?$/u,"").replace(/\/$/u,"")};var isHarnessDirectoryIgnore=(line)=>{const normalized=normalizeGitignorePattern(line);return normalized!==null&&harnessDirectories.has(normalized)};var removeHarnessDirectoriesFromGitignore=(rootDirectory)=>{const gitignorePath=path16.join(rootDirectory,".gitignore");if(!existsSync7(gitignorePath)){return{gitignorePath,removedPatterns:[]}}const original=readFileSync7(gitignorePath,"utf-8");const hadFinalNewline=original.endsWith(`
345
+ `));const repository=operations.observeRepository(repoRoot);return{...title===undefined?{}:{title},body:validBody,type:type2,severity,createdAt:new Date().toISOString(),cliVersion:operations.cliVersion,area,...skillPack===undefined?{}:{skillPack},...command===undefined?{}:{command},...expected===undefined?{}:{expected},...actual===undefined?{}:{actual},...steps===undefined?{}:{steps},...labels===undefined?{}:{labels},...repository===undefined?{}:{repository}}});var runReportSubmissionApplication=fn2("ReportSubmission.run")(function*runReportSubmissionApplication2(input2){const operations=yield*ReportSubmissionOperations;const report=yield*buildHarnessReport({...input2,labels:csvLabels(input2.extraLabels)});const baseUrl2=yield*operations.resolveControlPlaneUrl();if(baseUrl2===undefined){const cause=new Error("Harness report API URL is not configured.");return yield*new ReportConfigurationUnavailable({cause,message:cause.message,operation:"resolve-control-plane-url"})}const submitted=yield*operations.submit(baseUrl2,report);yield*operations.recordSubmitted(input2.repoRoot);return submitted});var reportCommandMetadata=declareCommandMetadata({examples:[{command:"hi report --message '...'",summary:"Submit a Harness report."}],group:"commands",interaction:"none",name:"report",options:[{name:"message",summary:"Raw report text for Harness triage."},{name:"title",summary:"Deprecated: optional title hint. The API generates the final title."},{name:"body",summary:"Deprecated: optional body hint. The API generates the final body."},{name:"type",summary:"Report type."},{name:"severity",summary:"Report severity."},{name:"area",summary:"Harness area."},{name:"repo-root",summary:"Repository root used for safe git context."},{name:"skill-pack",summary:"Affected skill pack, for example `hi-cli` or `docs-ingest-phase`."},{name:"command",summary:"Affected CLI command, for example `hi report` or `hi init`."},{name:"expected",summary:"Expected behavior."},{name:"actual",summary:"Actual behavior."},{name:"steps",summary:"Reproduction steps or evidence summary."},{name:"labels",summary:"Comma-separated extra GitHub labels."},{name:"json",summary:"Print JSON output."}],outputModes:["interactive","plain","json"],summary:"Submit reusable Harness friction to GitHub-backed maintainer triage."});var messageOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"message")).pipe(withOptionMetadata(reportCommandMetadata,"message")));var titleOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"title")).pipe(withOptionMetadata(reportCommandMetadata,"title")));var bodyOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"body")).pipe(withOptionMetadata(reportCommandMetadata,"body")));var typeOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"type"),["bug","docs","workflow","tooling","other"]).pipe(exports_Flag.withDefault("other"),withOptionMetadata(reportCommandMetadata,"type"));var severityOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"severity"),["low","medium","high"]).pipe(exports_Flag.withDefault("medium"),withOptionMetadata(reportCommandMetadata,"severity"));var areaOption=exports_Flag.choice(metadataOptionName(reportCommandMetadata,"area"),["cli","wiki","skill","docs","workflow","backoffice","other"]).pipe(exports_Flag.withDefault("other"),withOptionMetadata(reportCommandMetadata,"area"));var repoRootOption=exports_Flag.string(metadataOptionName(reportCommandMetadata,"repo-root")).pipe(exports_Flag.withDefault(process.cwd()),withOptionMetadata(reportCommandMetadata,"repo-root"));var skillPackOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"skill-pack")).pipe(withOptionMetadata(reportCommandMetadata,"skill-pack")));var commandOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"command")).pipe(withOptionMetadata(reportCommandMetadata,"command")));var expectedOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"expected")).pipe(withOptionMetadata(reportCommandMetadata,"expected")));var actualOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"actual")).pipe(withOptionMetadata(reportCommandMetadata,"actual")));var stepsOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"steps")).pipe(withOptionMetadata(reportCommandMetadata,"steps")));var labelsOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(reportCommandMetadata,"labels")).pipe(withOptionMetadata(reportCommandMetadata,"labels")));var jsonOption2=exports_Flag.boolean(metadataOptionName(reportCommandMetadata,"json")).pipe(withOptionMetadata(reportCommandMetadata,"json"));var optionalValue=(value5)=>isNone2(value5)||value5.value.trim().length===0?undefined:value5.value.trim();var reportExpectedFailure=(failure)=>{if(failure._tag==="@punks/cli/report-submission/ReportInputInvalid"){return new CliValidationError({message:"Report content is required.",recoveryCommand:"hi report --help"})}if(failure._tag==="@punks/cli/report-submission/ReportConfigurationUnavailable"){return new CliValidationError({message:"Harness report API URL is not configured.",recoveryCommand:"hi report"})}if(failure._tag==="@punks/cli/report-submission/ReportSubmissionResponseInvalid"){return new CliValidationError({message:"Harness report submission did not return a GitHub issue URL.",recoveryCommand:"hi report"})}return new CliValidationError({message:failure.operation==="record-submitted"?"Harness report submission could not be recorded locally.":"Harness report submission failed.",recoveryCommand:"hi report"})};var reportOperationResult=(submitted)=>{const{githubUrl}=submitted;const subject=githubUrl??submitted.reportId;return{changes:submitted.deduplicated===true?[]:[{action:`submit:${submitted.status}`,state:"completed",subject}],degradations:[],facts:{deduplicated:submitted.deduplicated===true,...githubUrl===undefined?{}:{githubUrl},kind:"report-submission",reportId:submitted.reportId,status:submitted.status,title:submitted.title??null},issues:[],nextActions:githubUrl===undefined?[]:[{kind:"review",subject:githubUrl}],status:submitted.deduplicated===true?"no-op":"success",warnings:submitted.deduplicated===true?[{code:"report-deduplicated",subject},{code:"report-status",subject:submitted.status}]:[]}};var executeReportCommand=(input2,operation=runReportSubmissionApplication)=>gen2(function*submitReport(){const submitted=yield*operation(input2).pipe(mapError3(reportExpectedFailure));return{...submitted,operation:reportOperationResult(submitted)}});var makeReportCommand=(operation=runReportSubmissionApplication)=>exports_Command.make(reportCommandMetadata.name,{actual:actualOption,area:areaOption,body:bodyOption,command:commandOption,expected:expectedOption,json:jsonOption2,labels:labelsOption,message:messageOption,repoRoot:repoRootOption,severity:severityOption,skillPack:skillPackOption,steps:stepsOption,title:titleOption,type:typeOption},({message,title,body,type:type2,severity,area,repoRoot,skillPack,command,expected,actual,steps,labels})=>captureCommandResult(executeReportCommand({actual:optionalValue(actual),area,body:optionalValue(body),command:optionalValue(command),expected:optionalValue(expected),extraLabels:optionalValue(labels),message:optionalValue(message),repoRoot,severity,skillPack:optionalValue(skillPack),steps:optionalValue(steps),title:optionalValue(title),type:type2},operation))).pipe(withCommandMetadata(reportCommandMetadata));var reportCommand=makeReportCommand();import path10 from"node:path";var RepositoryScaffoldingInteraction=Service("@punks/cli/features/repository-scaffolding/RepositoryScaffoldingInteraction");class RepositoryScaffoldingOperationFailure extends TaggedErrorClass()("@punks/cli/repository-scaffolding/RepositoryScaffoldingOperationFailure",{cause:Defect(),message:String5,operation:Literals(["initialize-repository","setup-repository"])}){}var RepositoryScaffoldingOperations=Service("@punks/cli/features/repository-scaffolding/RepositoryScaffoldingOperations");var runRepositoryScaffoldingApplication=fn2("RepositoryScaffolding.run")(function*runRepositoryScaffoldingApplication2(input2){const interaction=yield*RepositoryScaffoldingInteraction;const operations=yield*RepositoryScaffoldingOperations;return yield*operations.run(input2,interaction)});var outputSummary="Output directory for scaffolded files. Defaults to the current working directory.";var baselineSummary="Scaffold baseline to use: stable, bundled, or an exact version. Defaults to stable.";var refreshBaselineSummary="Refetch the stable baseline instead of reusing the local cache.";var initCommandMetadata=declareCommandMetadata({examples:[{command:"hi init",summary:"Initialize the current repository."}],group:"commands",interaction:"required",name:"init",options:[{name:"output",summary:outputSummary},{name:"baseline",summary:baselineSummary},{name:"refresh-baseline",summary:refreshBaselineSummary}],outputModes:["interactive","plain"],summary:"Seed docs onboarding, requirements/backlog/spec skills, and wiki structure. Agents: activate $hi-cli, then $docs-onboarding."});var scaffoldCommandMetadata=declareCommandMetadata({examples:[{command:"hi scaffold",summary:"Scaffold the current repository."}],group:"commands",interaction:"optional",name:"scaffold",options:[{name:"input",summary:"Repository root to scan. Defaults to the current working directory."},{name:"output",summary:outputSummary},{name:"json",summary:"Print the full machine-readable scaffold payload to stdout after completion."},{name:"repo-shape",summary:"Override repo shape detection. Use 'monorepo' or 'single' when auto-detection is not the desired scaffold mode."},{name:"baseline",summary:baselineSummary},{name:"refresh-baseline",summary:refreshBaselineSummary},{name:"yes",summary:"Run non-interactively and accept the resolved default scaffold selection."}],outputModes:["interactive","plain","json"],summary:"Repo-aware AI setup. Agents: activate $hi-cli, then reconcile .devpunks output with the real repo layout."});var silentNonInteractiveScaffoldingInteraction={confirmSelection:()=>die3("Non-interactive scaffold mode cannot confirm interactively"),emit:()=>void_3,keepPrefilledSelection:()=>die3("Non-interactive scaffold mode cannot edit the prefilled selection interactively"),selectPacks:()=>die3("Non-interactive scaffold mode cannot select packs interactively"),selectRepoSettings:()=>die3("Non-interactive scaffold mode cannot select repository settings interactively"),selectWikiFramework:()=>die3("Non-interactive scaffold mode cannot select a wiki framework interactively")};var outputOption=(metadata)=>exports_Flag.optional(exports_Flag.string(metadataOptionName(metadata,"output")).pipe(exports_Flag.withAlias("o"),withOptionMetadata(metadata,"output")));var inputOption2=exports_Flag.optional(exports_Flag.string(metadataOptionName(scaffoldCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(scaffoldCommandMetadata,"input")));var jsonOption3=exports_Flag.boolean(metadataOptionName(scaffoldCommandMetadata,"json")).pipe(withOptionMetadata(scaffoldCommandMetadata,"json"));var repoShapeOption=exports_Flag.optional(exports_Flag.choice(metadataOptionName(scaffoldCommandMetadata,"repo-shape"),["auto","monorepo","single"]).pipe(withOptionMetadata(scaffoldCommandMetadata,"repo-shape")));var baselineOption2=(metadata)=>exports_Flag.optional(exports_Flag.string(metadataOptionName(metadata,"baseline")).pipe(withOptionMetadata(metadata,"baseline")));var refreshBaselineOption2=(metadata)=>exports_Flag.boolean(metadataOptionName(metadata,"refresh-baseline")).pipe(withOptionMetadata(metadata,"refresh-baseline"));var yesOption=exports_Flag.boolean(metadataOptionName(scaffoldCommandMetadata,"yes")).pipe(withOptionMetadata(scaffoldCommandMetadata,"yes"));var scaffoldOperationResult=(input2,result4)=>{const failedTools=result4.toolBootstrapStatuses.filter((tool)=>tool.status==="failed");const projectionPartial=result4.projectionStatus==="partial";const issues=[...projectionPartial?[{action:"project",code:"scaffold-projection-partial",errorMessage:"Scaffold projection completed partially.",kind:"handled-failure",subject:result4.outputDirectory}]:[],...failedTools.map((tool)=>({action:"bootstrap-required-tool",code:`scaffold-required-tool-${tool.toolId}-failed`,errorMessage:tool.errorMessage,kind:"handled-failure",subject:tool.toolId}))];return{changes:[{action:input2.kind==="init"?"initialize":"setup",state:"completed",subject:result4.outputDirectory},...result4.toolBootstrapStatuses.filter((tool)=>tool.status!=="failed").map((tool)=>({action:tool.status==="installed"?"install-required-tool":"verify-required-tool",state:"completed",subject:tool.toolId}))],degradations:[],issues,nextActions:issues.length===0?[{kind:"none"}]:[...failedTools.length===0?[]:[{kind:"run",subject:"hi tools ensure"}],...projectionPartial?[{kind:"review",subject:result4.outputDirectory}]:[]],status:issues.length===0?"success":"partial",warnings:[]}};var executeScaffoldCommand=(input2,operation=runRepositoryScaffoldingApplication)=>scoped2(gen2(function*executeScaffold(){const result4=yield*operation(input2);const operationResult=scaffoldOperationResult(input2,result4);return input2.kind==="setup"&&input2.emitJson?{jsonPayload:result4.machinePayload,operation:operationResult}:operationResult}));var makeInitCommand=(operation=runRepositoryScaffoldingApplication)=>exports_Command.make(initCommandMetadata.name,{baseline:baselineOption2(initCommandMetadata),output:outputOption(initCommandMetadata),refreshBaseline:refreshBaselineOption2(initCommandMetadata)},({output:output2,baseline,refreshBaseline})=>gen2(function*runInitCommand(){const outputMode=yield*SelectedOutputMode;if(outputMode!=="interactive"){return yield*new CliValidationError({message:outputMode==="json"?"`hi init` requires interactive input and is unavailable in JSON mode.":"`hi init` requires interactive input and is unavailable when output is redirected.",recoveryCommand:"hi init"})}return yield*captureCommandResult(executeScaffoldCommand({baseline:getOrUndefined(baseline),kind:"init",outputDirectory:path10.resolve(process.cwd(),getOrElse(output2,()=>".")),refreshBaseline},operation))})).pipe(withCommandMetadata(initCommandMetadata));var makeScaffoldCommand=(operation=runRepositoryScaffoldingApplication)=>exports_Command.make(scaffoldCommandMetadata.name,{baseline:baselineOption2(scaffoldCommandMetadata),input:inputOption2,json:jsonOption3,output:outputOption(scaffoldCommandMetadata),refreshBaseline:refreshBaselineOption2(scaffoldCommandMetadata),repoShape:repoShapeOption,yes:yesOption},({input:input2,output:output2,json:json3,repoShape,baseline,refreshBaseline,yes})=>gen2(function*runScaffoldCommand(){const selectedOutputMode=yield*SelectedOutputMode;const emitJson=json3||selectedOutputMode==="json";return yield*captureCommandResult(executeScaffoldCommand({assumeYes:yes||selectedOutputMode!=="interactive",baseline:getOrUndefined(baseline),emitJson,kind:"setup",...isSome2(output2)?{outputDirectory:path10.resolve(process.cwd(),output2.value)}:{},refreshBaseline,repoShape:getOrElse(repoShape,()=>"auto"),scanDirectory:path10.resolve(process.cwd(),getOrElse(input2,()=>".")),toolStdio:selectedOutputMode==="interactive"?"inherit":"ignore"},operation).pipe(selectedOutputMode==="interactive"?(effect2)=>effect2:provideService2(RepositoryScaffoldingInteraction,silentNonInteractiveScaffoldingInteraction)))})).pipe(withCommandMetadata(scaffoldCommandMetadata));var initCommand=makeInitCommand();var scaffoldCommand=makeScaffoldCommand();var skillsCommandMetadata=declareCommandMetadata({examples:[{command:"hi skills rename",summary:"Migrate legacy operator skills."}],group:"commands",interaction:"none",name:"skills",options:[],outputModes:["interactive","plain","json"],summary:"Deprecated operator-skill compatibility commands."});var skillsRenameCommandMetadata=declareCommandMetadata({examples:[{command:"hi skills rename",summary:"Delegate to operator migration."}],group:"skills",interaction:"none",name:"rename",options:[],outputModes:["interactive","plain","json"],summary:"Deprecated alias for `hi operator migrate`."});var skillsRenameOperationResult=(operation)=>({...operation,warnings:[...operation.warnings,{code:"skills-rename-deprecated",subject:"hi operator migrate"}]});var skillsRenameCommand=exports_Command.make(skillsRenameCommandMetadata.name,{},()=>captureCommandResult(executeOperatorCommand("migrate").pipe(map7(skillsRenameOperationResult)))).pipe(withCommandMetadata(skillsRenameCommandMetadata));var skillsCommandRoot=exports_Command.make(skillsCommandMetadata.name,{},()=>captureCommandResult(succeed6({changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[{code:"skills-command-deprecated",subject:"hi operator"}]}))).pipe(withCommandMetadata(skillsCommandMetadata));var skillsCommand=skillsCommandRoot.pipe(exports_Command.withSubcommands([skillsRenameCommand]));import path11 from"node:path";class ToolEnsureOperationFailure extends TaggedErrorClass()("@punks/cli/tool-ensure/ToolEnsureOperationFailure",{cause:Defect(),message:String5,operation:Literal2("ensure-tools")}){}var ToolEnsureOperations=Service("@punks/cli/features/tool-ensure/ToolEnsureOperations");var baselineToolIds=["agent-browser","opensrc","portless","skills"];var requiredToolsForSkills=(skillIds,baseline)=>[...new Set([...baselineToolIds,...baseline.skills.filter((skill)=>skillIds.includes(skill.id)).flatMap((skill)=>skill.requiresTools)])].toSorted();var ensureTools=({baseline,rootDirectory,capabilities,runtime,stdio="inherit"})=>{const settings=capabilities.readSettings(rootDirectory);const toolIds=settings?.requiredTools??requiredToolsForSkills([],baseline);const statuses=capabilities.ensureTools(toolIds,baseline,runtime,{mode:"refresh-latest",stdio});return{hasFailures:statuses.some((status2)=>status2.status==="failed"),rootDirectory,statuses,toolIds}};var runToolEnsureApplication=fn2("ToolEnsure.run")(function*runToolEnsureApplication2(input2){const operations=yield*ToolEnsureOperations;return yield*operations.run(input2)});var toolsCommandMetadata=declareCommandMetadata({examples:[{command:"hi tools ensure",summary:"Ensure required tools are installed."}],group:"commands",interaction:"none",name:"tools",options:[],outputModes:["interactive","plain","json"],summary:"Manage external Harness tool requirements."});var toolsEnsureCommandMetadata=declareCommandMetadata({examples:[{command:"hi tools ensure",summary:"Refresh the selected managed toolchain."}],group:"tools",interaction:"none",name:"ensure",options:[{name:"input",summary:"Scaffolded repository root to inspect. Defaults to the current working directory."},{name:"baseline",summary:"Trusted scaffold baseline: stable, bundled, or an exact version. Defaults to stable."},{name:"refresh-baseline",summary:"Refetch the stable baseline instead of reusing the local cache."}],outputModes:["interactive","plain","json"],summary:"Refresh auto-managed required tools to trusted latest targets; validate manual platform tools without upgrading them."});var toolsRootOperation=succeed6({changes:[],degradations:[],issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[]});var toolEnsureStatus=(changeCount,issueCount)=>{if(issueCount>0){return changeCount>0?"partial":"failed"}return changeCount>0?"success":"no-op"};var inputOption3=exports_Flag.optional(exports_Flag.string(metadataOptionName(toolsEnsureCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(toolsEnsureCommandMetadata,"input")));var baselineOption3=exports_Flag.optional(exports_Flag.string(metadataOptionName(toolsEnsureCommandMetadata,"baseline")).pipe(withOptionMetadata(toolsEnsureCommandMetadata,"baseline")));var refreshBaselineOption3=exports_Flag.boolean(metadataOptionName(toolsEnsureCommandMetadata,"refresh-baseline")).pipe(withOptionMetadata(toolsEnsureCommandMetadata,"refresh-baseline"));var toolEnsureOperationResult=(result4)=>{const changes=result4.statuses.filter((status2)=>status2.status==="installed").map((status2)=>({action:"install",state:"completed",subject:status2.toolId}));const issues=result4.statuses.filter((status2)=>status2.status==="failed").map((status2)=>({action:"install",code:"tool-install-failed",errorMessage:status2.errorMessage,kind:"handled-failure",subject:status2.toolId}));return{changes,degradations:[],issues,nextActions:issues.length>0?[{kind:"retry",subject:"required-tools"}]:[{kind:"none"}],status:toolEnsureStatus(changes.length,issues.length),warnings:[]}};var executeToolsEnsureCommand=(input2,operation=runToolEnsureApplication)=>gen2(function*ensureRequiredTools(){const result4=yield*operation(input2);return toolEnsureOperationResult(result4)});var toolsEnsureCommand=exports_Command.make(toolsEnsureCommandMetadata.name,{baseline:baselineOption3,input:inputOption3,refreshBaseline:refreshBaselineOption3},({input:input2,baseline,refreshBaseline})=>gen2(function*ensureTools(){const outputMode=yield*SelectedOutputMode;return yield*captureCommandResult(executeToolsEnsureCommand({baseline:getOrUndefined(baseline),refreshBaseline,rootDirectory:path11.resolve(process.cwd(),getOrElse(input2,()=>".")),stdio:outputMode==="interactive"?"inherit":"ignore"}))})).pipe(withCommandMetadata(toolsEnsureCommandMetadata));var toolsCommandRoot=exports_Command.make(toolsCommandMetadata.name,{},()=>captureCommandResult(toolsRootOperation)).pipe(withCommandMetadata(toolsCommandMetadata));var toolsCommand=toolsCommandRoot.pipe(exports_Command.withSubcommands([toolsEnsureCommand]));import path12 from"node:path";var updateCommandMetadata=declareCommandMetadata({examples:[{command:"hi update --check",summary:"Preview managed scaffold updates."}],group:"commands",interaction:"optional",name:"update",options:[{name:"input",summary:"Scaffolded repository root to update. Defaults to the current working directory."},{name:"check",summary:"Preview managed scaffold updates, write nothing, and exit nonzero when updates are available."},{name:"write",summary:"Apply managed scaffold updates without asking for confirmation."},{name:"yes",summary:"Apply managed scaffold updates without asking for confirmation."},{name:"json",summary:"Print the machine-readable update payload to stdout."},{name:"baseline",summary:"Scaffold baseline to use: stable, bundled, or an exact version. Defaults to stable."},{name:"refresh-baseline",summary:"Refetch the stable baseline instead of reusing the local cache."}],outputModes:["interactive","plain","json"],summary:"Refresh managed scaffold assets from the recorded .devpunks scaffold manifest."});var inputOption4=exports_Flag.optional(exports_Flag.string(metadataOptionName(updateCommandMetadata,"input")).pipe(exports_Flag.withAlias("i"),withOptionMetadata(updateCommandMetadata,"input")));var checkOption=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"check")).pipe(withOptionMetadata(updateCommandMetadata,"check"));var writeOption=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"write")).pipe(withOptionMetadata(updateCommandMetadata,"write"));var yesOption2=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"yes")).pipe(withOptionMetadata(updateCommandMetadata,"yes"));var jsonOption4=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"json")).pipe(withOptionMetadata(updateCommandMetadata,"json"));var baselineOption4=exports_Flag.optional(exports_Flag.string(metadataOptionName(updateCommandMetadata,"baseline")).pipe(withOptionMetadata(updateCommandMetadata,"baseline")));var refreshBaselineOption4=exports_Flag.boolean(metadataOptionName(updateCommandMetadata,"refresh-baseline")).pipe(withOptionMetadata(updateCommandMetadata,"refresh-baseline"));var silentNonInteractiveUpdateInteraction={confirmApply:()=>succeed6(false),emit:()=>void_3};var executeUpdateCommand=(input2,operation=runScaffoldUpdateApplication)=>scoped2(gen2(function*executeUpdate(){const result4=yield*operation(input2);return input2.emitJson?{jsonPayload:publicUpdateResult(result4),operation:result4.operation}:result4}));var makeUpdateCommand=(operation=runScaffoldUpdateApplication)=>exports_Command.make(updateCommandMetadata.name,{baseline:baselineOption4,check:checkOption,input:inputOption4,json:jsonOption4,refreshBaseline:refreshBaselineOption4,write:writeOption,yes:yesOption2},({input:input2,check:check3,write:write2,yes,json:json3,baseline,refreshBaseline})=>gen2(function*runUpdateCommand(){const selectedOutputMode=yield*SelectedOutputMode;return yield*captureCommandResult(executeUpdateCommand({baseline:getOrUndefined(baseline),check:check3,emitJson:json3||selectedOutputMode==="json",refreshBaseline,rootDirectory:path12.resolve(process.cwd(),getOrElse(input2,()=>".")),toolStdio:selectedOutputMode==="interactive"?"inherit":"ignore",write:write2,yes},operation).pipe(selectedOutputMode==="interactive"?(effect2)=>effect2:provideService2(UpdateInteraction,silentNonInteractiveUpdateInteraction)))})).pipe(withCommandMetadata(updateCommandMetadata));var updateCommand=makeUpdateCommand();import{spawnSync}from"node:child_process";import{existsSync as existsSync4,realpathSync}from"node:fs";var parseSemver=(value5)=>{const match8=value5.match(/^v?(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-(?<prerelease>[0-9A-Za-z.-]+))?$/u);if(match8===null){return null}return{major:Number.parseInt(match8[1],10),minor:Number.parseInt(match8[2],10),patch:Number.parseInt(match8[3],10),prerelease:match8[4]??null}};var isNumericPrereleaseIdentifier=(value5)=>/^(?<zero>0|[1-9]\d*)$/u.test(value5);var comparePrerelease2=(candidate,current)=>{const candidateParts=candidate.split(".");const currentParts=current.split(".");const maxLength=Math.max(candidateParts.length,currentParts.length);for(let index2=0;index2<maxLength;index2+=1){const candidatePart=candidateParts[index2];const currentPart=currentParts[index2];if(candidatePart===undefined){return-1}if(currentPart===undefined){return 1}if(candidatePart===currentPart){continue}const candidateIsNumeric=isNumericPrereleaseIdentifier(candidatePart);const currentIsNumeric=isNumericPrereleaseIdentifier(currentPart);if(candidateIsNumeric&&currentIsNumeric){return Number.parseInt(candidatePart,10)>Number.parseInt(currentPart,10)?1:-1}if(candidateIsNumeric!==currentIsNumeric){return candidateIsNumeric?-1:1}return candidatePart>currentPart?1:-1}return 0};var isNewerVersion=(candidate,current)=>{const parsedCandidate=parseSemver(candidate);const parsedCurrent=parseSemver(current);if(parsedCandidate===null||parsedCurrent===null){return false}if(parsedCandidate.major!==parsedCurrent.major){return parsedCandidate.major>parsedCurrent.major}if(parsedCandidate.minor!==parsedCurrent.minor){return parsedCandidate.minor>parsedCurrent.minor}if(parsedCandidate.patch!==parsedCurrent.patch){return parsedCandidate.patch>parsedCurrent.patch}if(parsedCandidate.prerelease!==null&&parsedCurrent.prerelease!==null){return comparePrerelease2(parsedCandidate.prerelease,parsedCurrent.prerelease)>0}return parsedCurrent.prerelease!==null&&parsedCandidate.prerelease===null};var readTaggedVersion=async({packageName,registry="https://registry.npmjs.org",tag:tag4,timeoutMs})=>{if(typeof fetch!=="function"){return null}const controller=new AbortController;const timeout3=setTimeout(()=>controller.abort(),timeoutMs);try{const response=await fetch(`${registry.replace(/\/+$/u,"")}/${encodeURIComponent(packageName)}/${encodeURIComponent(tag4)}`,{headers:{accept:"application/json"},signal:controller.signal});if(!response.ok){return null}const payload=await response.json();return typeof payload.version==="string"?payload.version:null}catch{return null}finally{clearTimeout(timeout3)}};var checkSelfUpdate=async({currentVersion,packageName,registry,tag:tag4="latest",timeoutMs=750})=>{const latestVersion=await readTaggedVersion({packageName,...registry===undefined?{}:{registry},tag:tag4,timeoutMs});if(latestVersion===null){return null}return{currentVersion,latestVersion,packageName,tag:tag4,updateAvailable:isNewerVersion(latestVersion,currentVersion)}};var looksLikePath=(value5)=>value5.includes("/")||value5.includes("\\")||existsSync4(value5);var defaultEntrypointCandidates=()=>[process.argv[1]??"",process.execPath].filter((value5)=>value5.length>0);var packageManagerForRuntimePath=(runtimePath)=>{const normalizedEntrypoint=runtimePath.toLowerCase();if(normalizedEntrypoint.includes("/.bun/")||normalizedEntrypoint.includes("\\.bun\\")||normalizedEntrypoint.includes("/install/global/node_modules/@punks/cli/")||normalizedEntrypoint.includes("\\install\\global\\node_modules\\@punks\\cli\\")){return"bun"}if(normalizedEntrypoint.includes("/pnpm/")||normalizedEntrypoint.includes("\\pnpm\\")||normalizedEntrypoint.includes("/.pnpm/")){return"pnpm"}if(normalizedEntrypoint.includes("/yarn/")||normalizedEntrypoint.includes("\\yarn\\")||normalizedEntrypoint.includes("/.yarn/")){return"yarn"}if(normalizedEntrypoint.includes("/node_modules/@punks/cli/")||normalizedEntrypoint.includes("\\node_modules\\@punks\\cli\\")){return"npm"}return null};var detectCliInstallPackageManager=({entrypoint,userAgent}={})=>{const entrypointCandidates=entrypoint===undefined?defaultEntrypointCandidates():[entrypoint];const runtimePaths=entrypointCandidates.flatMap((candidate)=>{if(candidate.length===0||!looksLikePath(candidate)){return[]}try{return[candidate,realpathSync(candidate)]}catch{return[candidate]}});for(const runtimePath of runtimePaths){const packageManager=packageManagerForRuntimePath(runtimePath);if(packageManager!==null){return packageManager}}if(runtimePaths.length>0){return null}if(userAgent?.startsWith("bun/")===true){return"bun"}if(userAgent?.startsWith("pnpm/")===true){return"pnpm"}if(userAgent?.startsWith("yarn/")===true){return"yarn"}if(userAgent?.startsWith("npm/")===true){return"npm"}return null};var globalInstallCommandForPackageManager=({packageManager,packageName,tag:tag4})=>{const specifier=`${packageName}@${tag4}`;switch(packageManager){case"bun":{return["bun","add","-g",specifier,"--minimum-release-age=0"]}case"pnpm":{return["pnpm","add","-g",specifier]}case"npm":{return["npm","install","-g",specifier,"--min-release-age=0"]}case"yarn":{return["yarn","global","add",specifier]}default:{return packageManager}}};var minimumReleaseAgeEnvironmentForPackageManager=(packageManager)=>{switch(packageManager){case"pnpm":{return{npm_config_minimum_release_age:"0"}}case"yarn":{return{YARN_NPM_MINIMAL_AGE_GATE:"0"}}case"bun":case"npm":{return{}}default:{return packageManager}}};var runCliInstallCommand=({baseEnvironment={},command,environment})=>{const result4=spawnSync(command[0],command.slice(1),{env:{...baseEnvironment,...environment},stdio:"inherit"});return result4.status===0};var autoUpdateCliIfStale=async({currentVersion,packageName,tag:tag4="latest",timeoutMs=750,entrypoint,runtime={}})=>{const check3=await checkSelfUpdate({currentVersion,packageName,...runtime.npmRegistry===undefined?{}:{registry:runtime.npmRegistry},tag:tag4,timeoutMs});if(check3===null){return{check:check3,status:"unavailable"}}if(!check3.updateAvailable){return{check:check3,status:"current"}}const packageManager=detectCliInstallPackageManager({...entrypoint===undefined?{}:{entrypoint},...runtime.npmUserAgent===undefined?{}:{userAgent:runtime.npmUserAgent}});if(packageManager===null){return{check:check3,command:null,packageManager,status:"manager-not-detected"}}const command=globalInstallCommandForPackageManager({packageManager,packageName,tag:tag4});const environment=minimumReleaseAgeEnvironmentForPackageManager(packageManager);return{check:check3,command,environment,packageManager,status:"available"}};var upgradeCli=async({currentVersion,packageName,tag:tag4="latest",timeoutMs=5000,entrypoint,force=false,runtime={}})=>{const check3=await checkSelfUpdate({currentVersion,packageName,...runtime.npmRegistry===undefined?{}:{registry:runtime.npmRegistry},tag:tag4,timeoutMs});if(check3===null){return{check:check3,status:"unavailable"}}if(!check3.updateAvailable&&!force){return{check:check3,status:"current"}}const packageManager=detectCliInstallPackageManager({...entrypoint===undefined?{}:{entrypoint},...runtime.npmUserAgent===undefined?{}:{userAgent:runtime.npmUserAgent}});if(packageManager===null){return{check:check3,command:null,packageManager,status:"manager-not-detected"}}const command=globalInstallCommandForPackageManager({packageManager,packageName,tag:tag4});const environment=minimumReleaseAgeEnvironmentForPackageManager(packageManager);if(runCliInstallCommand({...runtime.commandEnvironment===undefined?{}:{baseEnvironment:runtime.commandEnvironment},command,environment})){return{check:check3,command,environment,packageManager,status:"upgraded"}}return{check:check3,command,packageManager,status:"failed"}};import{tmpdir as tmpdir3}from"node:os";import path13 from"node:path";var CliControlPlaneConfig=Service("@punks/cli/CliControlPlaneConfig");var CliReleaseConfig=Service("@punks/cli/CliReleaseConfig");var CliRuntimeConfig=Service("@punks/cli/CliRuntimeConfig");var controlPlaneEnvironment=makeEnvironmentConfig(Struct({CI:optional(String5),DP_CONTROL_PLANE_URL:optional(URLFromString),DP_DISABLE_BUNDLED_CONTROL_PLANE_URL:optional(Literals(["0","1"])),DP_TELEMETRY_SOURCE:optional(String5),NODE_ENV:optional(String5),VITEST:optional(String5)}));var releaseEnvironment=makeEnvironmentConfig(Struct({DP_BASELINE:optional(NonEmptyString),DP_BASELINE_REFRESH:optional(Literals(["0","1"])),DP_BASELINE_URL:optional(URLFromString),DP_UPDATE_TAG:optional(NonEmptyString),GH_TOKEN:optional(EnvironmentSecret),GITHUB_TOKEN:optional(EnvironmentSecret),HOME:optional(NonEmptyString),XDG_CACHE_HOME:optional(NonEmptyString)}));var runtimeEnvironment=makeEnvironmentConfig(Struct({CI:optional(String5),COLORFGBG:optional(String5),DP_SCRIPT_RUNTIME:optional(NonEmptyString),FORCE_COLOR:optional(String5),HI_NO_SKILL_UPDATE_CHECK:optional(Literals(["0","1"])),HI_NO_UPDATE_CHECK:optional(Literals(["0","1"])),HI_STARTUP_CHECK_CLI:optional(Literals(["0","1"])),HI_STARTUP_CHECK_INTERVAL_MS:optional(NumberFromString.check(isInt(),isGreaterThanOrEqualTo3(0))),HI_STARTUP_CHECK_SKILL:optional(Literals(["0","1"])),HI_STARTUP_CHECK_WORKER:optional(Literals(["0","1"])),HI_THEME:optional(Literals(["dark","light"])),HI_UPDATE_TAG:optional(NonEmptyString),NO_COLOR:optional(String5),NPM_CONFIG_REGISTRY:optional(URLFromString),npm_config_registry:optional(URLFromString),npm_config_user_agent:optional(String5)}));var stripTrailingSlashes=(value5)=>value5.toString().replace(/\/+$/u,"");var commandEnvironmentKeys=["AGENT_BROWSER_EXECUTABLE_PATH","ALL_PROXY","APPDATA","BUN_INSTALL","CI","COLORTERM","COMSPEC","CLAUDE_CODE","CLAUDE_PROJECT_DIR","CODEX_HOME","CODEX_THREAD_ID","DISPLAY","DP_SCRIPT_RUNTIME","DP_NO_CLIPBOARD","FORCE_COLOR","GH_CONFIG_DIR","HI_NO_SKILL_UPDATE_CHECK","HI_NO_UPDATE_CHECK","HI_OPERATOR_AGENT","HI_OPERATOR_MIGRATION_RETRY","HI_OPERATOR_MUTATION_RETRY","HI_STARTUP_CHECK_CLI","HI_STARTUP_CHECK_INTERVAL_MS","HI_STARTUP_CHECK_SKILL","HI_STARTUP_CHECK_WORKER","HI_THEME","HI_UPDATE_TAG","HOME","HTTP_PROXY","HTTPS_PROXY","LANG","LC_ALL","LOCALAPPDATA","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_ENV","NO_COLOR","NO_PROXY","NPM_CONFIG_REGISTRY","PATH","PATHEXT","Path","SHELL","SSL_CERT_DIR","SSL_CERT_FILE","SYSTEMROOT","TEMP","TERM","TMP","TMPDIR","USERPROFILE","VITEST","WAYLAND_DISPLAY","WINDIR","XAUTHORITY","XDG_CACHE_HOME","XDG_CONFIG_HOME","XDG_RUNTIME_DIR","all_proxy","http_proxy","https_proxy","no_proxy","npm_config_registry","npm_config_user_agent"];var commandEnvironment=(input2)=>Object.fromEntries(commandEnvironmentKeys.flatMap((key)=>input2[key]===undefined?[]:[[key,input2[key]]]));var loadCliRuntimeConfiguration=(provider,input2)=>decodeEnvironment({config:runtimeEnvironment,name:"CLI runtime",provider}).pipe(map7((environment)=>{const ciPresent=input2.CI!==undefined||environment.CI!==undefined;const forceColor=input2.FORCE_COLOR??environment.FORCE_COLOR;const noColorPresent=input2.NO_COLOR!==undefined||environment.NO_COLOR!==undefined;return{commandEnvironment:commandEnvironment(input2),forceColor:forceColor!==undefined&&forceColor!=="0",noColor:noColorPresent,npmRegistry:(environment.npm_config_registry?.toString()??environment.NPM_CONFIG_REGISTRY?.toString()??"https://registry.npmjs.org").replace(/\/+$/u,""),...environment.npm_config_user_agent===undefined?{}:{npmUserAgent:environment.npm_config_user_agent},scriptRuntimePath:environment.DP_SCRIPT_RUNTIME??"node",skillUpdateChecksEnabled:environment.HI_NO_SKILL_UPDATE_CHECK!=="1"&&!ciPresent,startupCheckCli:environment.HI_STARTUP_CHECK_CLI==="1",startupCheckIntervalMs:environment.HI_STARTUP_CHECK_INTERVAL_MS??12*60*60*1000,startupCheckSkill:environment.HI_STARTUP_CHECK_SKILL==="1",startupWorker:environment.HI_STARTUP_CHECK_WORKER==="1",updateChecksEnabled:environment.HI_NO_UPDATE_CHECK!=="1"&&!ciPresent,updateTag:environment.HI_UPDATE_TAG??"latest",...environment.HI_THEME===undefined?{}:{terminalTheme:environment.HI_THEME},...environment.COLORFGBG===undefined?{}:{colorForegroundBackground:environment.COLORFGBG}}}));var makeCliConfigLayer=(provider,input2={})=>mergeAll2(effect(CliControlPlaneConfig,decodeEnvironment({config:controlPlaneEnvironment,name:"CLI control plane",provider}).pipe(map7((environment)=>{let telemetrySource;const ciPresent=input2.CI!==undefined||environment.CI!==undefined;const vitestPresent=input2.VITEST!==undefined||environment.VITEST!==undefined;if(ciPresent){telemetrySource="ci"}else if(environment.DP_TELEMETRY_SOURCE==="debug"){telemetrySource="debug"}else if(environment.NODE_ENV==="test"||vitestPresent){telemetrySource="test"}return{disableBundledUrl:environment.DP_DISABLE_BUNDLED_CONTROL_PLANE_URL==="1",...environment.DP_CONTROL_PLANE_URL===undefined?{}:{baseUrl:stripTrailingSlashes(environment.DP_CONTROL_PLANE_URL)},...telemetrySource===undefined?{}:{telemetrySource}}}))),effect(CliReleaseConfig,decodeEnvironment({config:releaseEnvironment,name:"CLI release",provider}).pipe(map7((environment)=>{const githubToken=environment.GH_TOKEN??environment.GITHUB_TOKEN;return{cacheDirectory:environment.XDG_CACHE_HOME??path13.join(environment.HOME??tmpdir3(),".cache"),refreshBaseline:environment.DP_BASELINE_REFRESH==="1",updateTag:environment.DP_UPDATE_TAG??"latest",...environment.DP_BASELINE===undefined?{}:{baseline:environment.DP_BASELINE},...environment.DP_BASELINE_URL===undefined?{}:{baselineUrl:stripTrailingSlashes(environment.DP_BASELINE_URL)},...githubToken===undefined?{}:{githubToken}}}))),effect(CliRuntimeConfig,loadCliRuntimeConfiguration(provider,input2)));var upgradeCommandMetadata=declareCommandMetadata({examples:[{command:"hi upgrade",summary:"Upgrade the installed CLI."}],group:"commands",interaction:"none",name:"upgrade",options:[{name:"tag",summary:"npm dist-tag to install, for example `latest`, `next`, or `beta`."},{name:"force",summary:"Reinstall the selected dist-tag even when the current version is fresh."},{name:"json",summary:"Print JSON output."}],outputModes:["interactive","plain","json"],summary:"Upgrade this CLI through the package manager used for its global install."});var tagOption=exports_Flag.optional(exports_Flag.string(metadataOptionName(upgradeCommandMetadata,"tag")).pipe(withOptionMetadata(upgradeCommandMetadata,"tag")));var forceOption=exports_Flag.boolean(metadataOptionName(upgradeCommandMetadata,"force")).pipe(withOptionMetadata(upgradeCommandMetadata,"force"));var jsonOption5=exports_Flag.boolean(metadataOptionName(upgradeCommandMetadata,"json")).pipe(withOptionMetadata(upgradeCommandMetadata,"json"));var posixSafeComponent=/^[A-Za-z0-9_@%+=:,./-]+$/u;var windowsUnsafeComponent=/[\r\n"%]/u;var quotePosixComponent=(value5)=>posixSafeComponent.test(value5)?value5:`'${value5.replaceAll("'",`'"'"'`)}'`;var quoteWindowsComponent=(value5)=>{if(windowsUnsafeComponent.test(value5)){return}const trailingBackslashes=value5.match(/\\+$/u)?.[0]??"";return`"${value5}${trailingBackslashes}"`};var formatUpgradeRecoveryCommand=({command,environment,platform})=>{if(command.length===0||command.some((component)=>component.includes("\x00"))){return}const environmentEntries=Object.entries(environment);if(environmentEntries.some(([key,value5])=>key.length===0||key.includes("=")||value5.includes("\x00"))){return}if(platform==="win32"){const commandComponents=command.map(quoteWindowsComponent);const assignments=[];for(const[key,value5]of environmentEntries){if(windowsUnsafeComponent.test(key)||windowsUnsafeComponent.test(value5)){return}assignments.push(`set "${key}=${value5}"&&`)}if(commandComponents.some((component)=>component===undefined)){return}return`cmd.exe /d /v:off /s /c "${[...assignments,...commandComponents].join(" ")}"`}return[...environmentEntries.length===0?[]:["env"],...environmentEntries.map(([key,value5])=>quotePosixComponent(`${key}=${value5}`)),...command.map(quotePosixComponent)].join(" ")};var upgradeOperationResult=(result4)=>{switch(result4.status){case"upgraded":{return{changes:[{action:"upgrade",state:"completed",subject:result4.check.packageName}],degradations:[],facts:{command:result4.command,currentVersion:result4.check.currentVersion,environment:result4.environment,kind:"cli-upgrade",latestVersion:result4.check.latestVersion,packageManager:result4.packageManager,packageName:result4.check.packageName,status:result4.status,tag:result4.check.tag},issues:[],nextActions:[{kind:"none"}],status:"success",warnings:[]}}case"current":{return result4.check===null?undefined:{changes:[],degradations:[],facts:{command:null,currentVersion:result4.check.currentVersion,environment:{},kind:"cli-upgrade",latestVersion:result4.check.latestVersion,packageManager:null,packageName:result4.check.packageName,status:result4.status,tag:result4.check.tag},issues:[],nextActions:[{kind:"none"}],status:"no-op",warnings:[]}}default:{return}}};var upgradeExpectedFailure=(result4,platform=process.platform)=>{const recoveryCommand=(()=>{if(!("command"in result4)||result4.command===null){return result4.check===null?undefined:formatUpgradeRecoveryCommand({command:["npm","install","-g",`${result4.check.packageName}@${result4.check.tag}`],environment:{},platform})}return formatUpgradeRecoveryCommand({command:result4.command,environment:"environment"in result4?result4.environment:{},platform})})();switch(result4.status){case"current":{return result4.check===null?new CliValidationError({message:"Could not read the npm registry version for this CLI."}):undefined}case"unavailable":{return new CliValidationError({message:"Could not read the npm registry version for this CLI."})}case"manager-not-detected":{return new CliValidationError({message:"Could not detect how this CLI was installed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"available":{return new CliValidationError({message:"Upgrade command was not executed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"failed":{return new CliValidationError({message:"CLI upgrade failed.",...recoveryCommand===undefined?{}:{recoveryCommand}})}case"upgraded":{return}default:{return result4}}};var makeUpgradeCommand=(operation=upgradeCli)=>exports_Command.make(upgradeCommandMetadata.name,{force:forceOption,json:jsonOption5,tag:tagOption},({tag:tag4,force,json:_json})=>captureCommandResult(gen2(function*executeUpgradeCommand(){const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const result4=yield*tryPromise2({catch:()=>new CliValidationError({message:"CLI upgrade failed."}),try:()=>operation({currentVersion:version2,force,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:getOrElse(tag4,()=>release.updateTag)})});const failure=upgradeExpectedFailure(result4);if(failure!==undefined){return yield*fail6(failure)}return upgradeOperationResult(result4)}))).pipe(withCommandMetadata(upgradeCommandMetadata));var upgradeCommand=makeUpgradeCommand();var registration=(command,commandMetadata,children=[])=>({children,command,metadata:commandMetadata});var operatorChildren=[registration(operatorSubcommands[0],operatorStatusCommandMetadata),registration(operatorSubcommands[1],operatorInstallCommandMetadata),registration(operatorSubcommands[2],operatorUpdateCommandMetadata),registration(operatorSubcommands[3],operatorMigrateCommandMetadata)];var rootRegistrations=[registration(checkCommand,checkCommandMetadata),registration(ensureCommand,ensureCommandMetadata),registration(initCommand,initCommandMetadata),registration(operatorCommandRoot,operatorCommandMetadata,operatorChildren),registration(reportCommand,reportCommandMetadata),registration(scaffoldCommand,scaffoldCommandMetadata),registration(skillsCommandRoot,skillsCommandMetadata,[registration(skillsRenameCommand,skillsRenameCommandMetadata)]),registration(toolsCommandRoot,toolsCommandMetadata,[registration(toolsEnsureCommand,toolsEnsureCommandMetadata)]),registration(updateCommand,updateCommandMetadata),registration(upgradeCommand,upgradeCommandMetadata)];var flatten4=(registrations)=>registrations.flatMap(({children,metadata:commandMetadata})=>[commandMetadata,...flatten4(children)]);var resolveRegistrations=(nodes,parentPath=[])=>nodes.map((node)=>{if(node.command.name!==node.metadata.name){throw new CommandMetadataError(`Executable command '${node.command.name}' does not match metadata name '${node.metadata.name}'.`)}const[first,...rest]=parentPath;const path14=first===undefined?[node.metadata.name]:[first,...rest,node.metadata.name];return{children:resolveRegistrations(node.children,path14),command:node.command,metadata:commandMetadataFromDeclaration(path14,node.metadata)}});var buildRegisteredCommand=(node)=>{const children=node.children.map((child)=>buildRegisteredCommand(child));return children.length===0?node.command:exports_Command.withSubcommands(node.command,children)};var buildCommandRegistry=(rootCommand,registrations)=>{const executableCommands=registrations.map((node)=>buildRegisteredCommand(node));const resolvedRegistrations=resolveRegistrations(registrations);const reference=createCommandMetadataRegistry(flatten4(resolvedRegistrations));const discovery=reference.map(({path:commandPath,summary})=>({path:[...commandPath],summary}));return{command:exports_Command.withSubcommands(rootCommand,executableCommands),commands:reference,discovery,reference,registrations:resolvedRegistrations}};var rootCommand=exports_Command.make("hi",{},()=>void_3).pipe(exports_Command.withDescription("Harness Intelligence CLI. Agents: activate $hi-cli before acting on generated output."));var commandRegistry=buildCommandRegistry(rootCommand,rootRegistrations);import{execFileSync as execFileSync2}from"node:child_process";import{homedir as homedir2}from"node:os";import path19 from"node:path";import{existsSync as existsSync5,readFileSync as readFileSync5,readdirSync as readdirSync3}from"node:fs";import path14 from"node:path";class CliDetectionError extends TaggedErrorClass()("CliDetectionError",{cause:optional(Defect()),message:String5}){}var ignoredDirectoryNames=new Set([".git",".agents",".claude",".codex",".cursor",".devpunks",".devpunks-cache",".next",".opencode",".source",".turbo","coverage","dist","docs","examples","build","node_modules","opensrc","scripts","skills","test-fixtures","tmp","worktrees",".venv","venv","__pycache__"]);var detectionOrder=["nextjs","react","tanstack-query","elysia","trpc","drizzle","better-auth","effect","turborepo"];var languageDetectionOrder=["python","typescript"];var sourceLanguageExtensions=[{language:"python",pattern:/\.py$/u},{language:"typescript",pattern:/\.(?:ts|tsx)$/u}];var conventionalWorkspaceRoots=["apps","packages","services","libs"];var wikiRootPaths=new Set(["app/wiki","apps/wiki","wiki"]);var isRecord4=(value5)=>typeof value5==="object"&&value5!==null;var dependencyRecordSchema=Record(String5,String5);var packageJsonSchema=fromJsonString2(Struct({dependencies:optional(dependencyRecordSchema),devDependencies:optional(dependencyRecordSchema),name:optional(String5),optionalDependencies:optional(dependencyRecordSchema),peerDependencies:optional(dependencyRecordSchema),workspaces:optional(Unknown2)}));var parsePackageJsonRecord=decodeUnknownSync2(packageJsonSchema);var decodeWorkspacePackages=decodeUnknownSync2(ArraySchema(String5));var collectPackageNames=(pkg)=>{const names=new Set;const addEntries=(record3)=>{if(!record3){return}for(const name2 of Object.keys(record3)){names.add(name2)}};addEntries(pkg.dependencies);addEntries(pkg.devDependencies);addEntries(pkg.peerDependencies);addEntries(pkg.optionalDependencies);return[...names].toSorted()};var normalizeRelativePath=(relativePath)=>relativePath.split(path14.sep).join("/");var isWikiRelativePath=(relativePath)=>{const normalized=normalizeRelativePath(relativePath);return[...wikiRootPaths].some((wikiRoot)=>normalized===wikiRoot||normalized.startsWith(`${wikiRoot}/`))};var isWikiManifest=(manifest)=>isWikiRelativePath(manifest.relativePath);var packDetectionManifests=(manifests)=>manifests.filter((manifest)=>!isWikiManifest(manifest));var recursiveFindFiles=(cwd,filename)=>{const results=[];const visit2=(directory3)=>{for(const entry of readdirSync3(directory3,{withFileTypes:true})){if(ignoredDirectoryNames.has(entry.name)){continue}const absolutePath=path14.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}if(entry.isFile()&&entry.name===filename){results.push(absolutePath)}}};if(existsSync5(cwd)){visit2(cwd)}return results.toSorted()};var discoverConventionalWorkspacePackageJsonPaths=(cwd)=>conventionalWorkspaceRoots.flatMap((rootDirectoryName)=>{const rootDirectory=path14.join(cwd,rootDirectoryName);if(!existsSync5(rootDirectory)){return[]}return readdirSync3(rootDirectory,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path14.join(rootDirectory,entry.name,"package.json")).filter((manifestPath)=>existsSync5(manifestPath))});var discoverTopLevelPackageJsonPaths=(cwd)=>readdirSync3(cwd,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path14.join(cwd,entry.name,"package.json")).filter((manifestPath)=>existsSync5(manifestPath));var readPackageJsonWorkspacePatterns=(pkg)=>{const{workspaces}=pkg;if(isArray(workspaces)){return decodeWorkspacePackages(workspaces)}if(isRecord4(workspaces)&&isArray(workspaces.packages)){return decodeWorkspacePackages(workspaces.packages)}return[]};var readPnpmWorkspacePatterns=(cwd)=>{const workspacePath=path14.join(cwd,"pnpm-workspace.yaml");if(!existsSync5(workspacePath)){return[]}const patterns=[];let inPackagesSection=false;for(const rawLine of readFileSync5(workspacePath,"utf-8").split(/\r?\n/u)){const line=rawLine.trim();if(line==="packages:"){inPackagesSection=true;continue}if(!inPackagesSection){continue}if(line.startsWith("- ")){const pattern=line.slice(2).trim().replaceAll(/^['"]|['"]$/gu,"");if(pattern.length>0){patterns.push(pattern)}continue}if(line.length>0&&!line.startsWith("#")){break}}return patterns};var expandWorkspacePattern=(cwd,pattern)=>{if(pattern.endsWith("/*")){const baseDirectory=path14.join(cwd,pattern.slice(0,-2));if(!existsSync5(baseDirectory)){return[]}return readdirSync3(baseDirectory,{withFileTypes:true}).filter((entry)=>entry.isDirectory()&&!ignoredDirectoryNames.has(entry.name)).map((entry)=>path14.join(baseDirectory,entry.name,"package.json")).filter((manifestPath2)=>existsSync5(manifestPath2)).toSorted()}if(pattern.includes("*")){return[]}const manifestPath=path14.join(cwd,pattern,"package.json");return existsSync5(manifestPath)?[manifestPath]:[]};var discoverPackageJsonPaths=(cwd)=>{const rootPackageJsonPath=path14.join(cwd,"package.json");const recursivePackageJsonPaths=recursiveFindFiles(cwd,"package.json");if(!existsSync5(rootPackageJsonPath)){return recursivePackageJsonPaths}const rootPackageJson=parsePackageJsonRecord(readFileSync5(rootPackageJsonPath,"utf-8"));const workspacePatterns=new Set([...readPackageJsonWorkspacePatterns(rootPackageJson),...readPnpmWorkspacePatterns(cwd)]);const workspacePackageJsonPaths=[...workspacePatterns].flatMap((pattern)=>expandWorkspacePattern(cwd,pattern));const conventionalWorkspacePackageJsonPaths=discoverConventionalWorkspacePackageJsonPaths(cwd);const topLevelPackageJsonPaths=discoverTopLevelPackageJsonPaths(cwd);return[...recursivePackageJsonPaths,...workspacePackageJsonPaths,...conventionalWorkspacePackageJsonPaths,...topLevelPackageJsonPaths].filter((value5,index2,values3)=>values3.indexOf(value5)===index2).toSorted()};var detectTechnologies=(manifests)=>{const packageNames=new Set(packDetectionManifests(manifests).flatMap((manifest)=>manifest.dependencies));const detected=new Set;const hasPackage=(packageName)=>packageNames.has(packageName);const hasPackagePrefix=(prefix)=>[...packageNames].some((packageName)=>packageName.startsWith(prefix));if(hasPackage("next")){detected.add("nextjs");detected.add("react")}if(hasPackage("react")||hasPackage("react-dom")){detected.add("react")}if(hasPackage("@tanstack/react-query")||hasPackage("@tanstack/query-core")||hasPackage("@tanstack/react-query-devtools")||hasPackage("@tanstack/react-query-persist-client")||hasPackage("@tanstack/query-persist-client-core")){detected.add("tanstack-query")}if(hasPackage("elysia")){detected.add("elysia")}if(hasPackagePrefix("@trpc/")){detected.add("trpc")}if(hasPackage("drizzle-orm")||hasPackage("drizzle-kit")){detected.add("drizzle")}if(hasPackage("better-auth")){detected.add("better-auth")}if(hasPackage("effect")||hasPackagePrefix("@effect/")){detected.add("effect")}if(hasPackage("turbo")){detected.add("turborepo")}return detectionOrder.filter((technology)=>detected.has(technology))};var hasPackageTrigger=(packageNames,trigger)=>trigger.endsWith("/")?[...packageNames].some((packageName)=>packageName.startsWith(trigger)):packageNames.has(trigger);var isSourceDirectoryPath=(cwd,directory3)=>path14.relative(cwd,directory3)!=="";var detectSourceLanguages=(cwd)=>{const detected=new Set;const visit2=(directory3)=>{for(const entry of readdirSync3(directory3,{withFileTypes:true})){if(ignoredDirectoryNames.has(entry.name)){continue}const absolutePath=path14.join(directory3,entry.name);if(entry.isDirectory()){visit2(absolutePath);continue}const relativePath=path14.relative(cwd,absolutePath);if(entry.isFile()&&isSourceDirectoryPath(cwd,directory3)&&!isWikiRelativePath(relativePath)){for(const{language,pattern}of sourceLanguageExtensions){if(pattern.test(entry.name)&&!entry.name.endsWith(".d.ts")){detected.add(language)}}}}};if(existsSync5(cwd)){visit2(cwd)}return languageDetectionOrder.filter((language)=>detected.has(language))};var detectLanguages=(cwd,manifests)=>{const packageNames=new Set(packDetectionManifests(manifests).flatMap((manifest)=>manifest.dependencies));const detected=new Set(detectSourceLanguages(cwd));if(hasPackageTrigger(packageNames,"typescript")){detected.add("typescript")}return languageDetectionOrder.filter((language)=>detected.has(language))};var detectMonorepoSignals=(cwd,manifests)=>{const signals=[];for(const workspacePath of recursiveFindFiles(cwd,"pnpm-workspace.yaml")){signals.push({path:workspacePath,type:"pnpm-workspace"})}for(const turboConfigPath of recursiveFindFiles(cwd,"turbo.json")){signals.push({path:turboConfigPath,type:"turbo-config"})}for(const manifest of manifests){const pkg=parsePackageJsonRecord(readFileSync5(manifest.path,"utf-8"));const{workspaces}=pkg;const hasWorkspaces=isArray(workspaces)||isRecord4(workspaces)&&isArray(workspaces.packages);if(hasWorkspaces){signals.push({path:manifest.path,type:"package-json-workspaces"})}}const workspaceManifests=manifests.filter((manifest)=>{const pkg=parsePackageJsonRecord(readFileSync5(manifest.path,"utf-8"));const{workspaces}=pkg;return!(isArray(workspaces)||isRecord4(workspaces)&&isArray(workspaces.packages))});if(workspaceManifests.length>1){signals.push({path:cwd,type:"workspace-packages"})}return signals.filter((signal,index2,allSignals)=>allSignals.findIndex((candidate)=>candidate.type===signal.type&&candidate.path===signal.path)===index2)};var detectRepository=(cwd)=>try_3({catch:(cause)=>new CliDetectionError({cause,message:"Failed to detect repository shape."}),try:()=>{const manifestPaths=discoverPackageJsonPaths(cwd);const manifests=manifestPaths.map((manifestPath)=>{const pkg=parsePackageJsonRecord(readFileSync5(manifestPath,"utf-8"));return{dependencies:collectPackageNames(pkg),packageName:pkg.name??null,path:manifestPath,relativePath:path14.relative(cwd,manifestPath)||"package.json"}});const detectedLanguages=detectLanguages(cwd,manifests);const detectedTechnologies=detectTechnologies(manifests);const monorepoSignals=detectMonorepoSignals(cwd,manifests);return{cwd,detectedLanguages,detectedTechnologies,manifests,monorepo:monorepoSignals.length>0,monorepoSignals}}});var manifestPaths=(result4)=>result4.manifests.map((manifest)=>path14.relative(result4.cwd,manifest.path)||"package.json");var applyRepoShapeMode=(result4,repoShapeMode)=>repoShapeMode==="auto"?result4:{...result4,monorepo:repoShapeMode==="monorepo"};var shouldUseClipboard=(environment)=>environment.VITEST!=="true"&&environment.NODE_ENV!=="test"&&environment.DP_NO_CLIPBOARD!=="1";import{existsSync as existsSync6,mkdirSync as mkdirSync3,readFileSync as readFileSync6,rmSync,writeFileSync as writeFileSync3}from"node:fs";import path15 from"node:path";var nodeFilesystem={exists:existsSync6,read:(filePath)=>readFileSync6(filePath,"utf-8"),remove:(filePath,options4)=>rmSync(filePath,{force:true,recursive:options4?.recursive??false}),write:(filePath,content)=>{mkdirSync3(path15.dirname(filePath),{recursive:true});writeFileSync3(filePath,content,"utf-8")}};var ScaffoldCapabilities=Service("@punks/cli/scaffold/ScaffoldCapabilities");import{existsSync as existsSync7,readFileSync as readFileSync7,writeFileSync as writeFileSync4}from"node:fs";import path16 from"node:path";var harnessDirectories=new Set([".agents",".claude",".codex",".cursor",".opencode"]);var normalizeGitignorePattern=(line)=>{const trimmed=line.trim();if(trimmed===""||trimmed.startsWith("#")||trimmed.startsWith("!")){return null}return trimmed.replace(/^\//u,"").replace(/\/\*\*?$/u,"").replace(/\/$/u,"")};var isHarnessDirectoryIgnore=(line)=>{const normalized=normalizeGitignorePattern(line);return normalized!==null&&harnessDirectories.has(normalized)};var removeHarnessDirectoriesFromGitignore=(rootDirectory)=>{const gitignorePath=path16.join(rootDirectory,".gitignore");if(!existsSync7(gitignorePath)){return{gitignorePath,removedPatterns:[]}}const original=readFileSync7(gitignorePath,"utf-8");const hadFinalNewline=original.endsWith(`
346
346
  `);const removedPatterns=[];const keptLines=original.split(/\r?\n/u).filter((line,index2,lines2)=>{if(index2===lines2.length-1&&line===""){return false}if(!isHarnessDirectoryIgnore(line)){return true}removedPatterns.push(line.trim());return false});if(removedPatterns.length===0){return{gitignorePath,removedPatterns}}writeFileSync4(gitignorePath,`${keptLines.join(`
347
347
  `)}${hadFinalNewline?`
348
348
  `:""}`,"utf-8");return{gitignorePath,removedPatterns}};import{createHash as createHash4}from"node:crypto";import{chmodSync,existsSync as existsSync9,lstatSync as lstatSync3,mkdtempSync,mkdirSync as mkdirSync5,readdirSync as readdirSync4,readFileSync as readFileSync8,readlinkSync as readlinkSync2,realpathSync as realpathSync2,rmSync as rmSync3,symlinkSync,writeFileSync as writeFileSync5}from"node:fs";import{tmpdir as tmpdir4}from"node:os";import path18 from"node:path";import{runInNewContext}from"node:vm";var orderedSchemaFields=(...entries3)=>Object.fromEntries(entries3);var ContextPlanVersion=Literal2("1");var ContributionKind=Literals(["skill","scoped-prompt","lifecycle-hook","tool-configuration","subagent-template"]);var ContributionIdentity=Struct({id:NonEmptyString,version:NonEmptyString});var ContributionProvenance=Struct(orderedSchemaFields(["source",NonEmptyString],["revision",NonEmptyString]));var ContributionCompatibility=Struct({id:NonEmptyString,versionRange:NonEmptyString});var ContributionReferenceClosure=ArraySchema(NonEmptyString);var ContributionOrder=Number6.pipe(check2(isInt(),isGreaterThanOrEqualTo3(0)));var contributionFields=orderedSchemaFields(["identity",ContributionIdentity],["provenance",ContributionProvenance],["compatibility",ArraySchema(ContributionCompatibility)],["references",ContributionReferenceClosure],["order",ContributionOrder]);var ContextContribution=Union2([Struct({kind:Literal2("skill"),...contributionFields}),Struct({kind:Literal2("scoped-prompt"),...contributionFields}),Struct({kind:Literal2("lifecycle-hook"),...contributionFields}),Struct({kind:Literal2("tool-configuration"),...contributionFields}),Struct({kind:Literal2("subagent-template"),...contributionFields})]);var SelectedPack=Struct({id:NonEmptyString,order:ContributionOrder});var RepositoryScope=Struct(orderedSchemaFields(["id",NonEmptyString],["packs",ArraySchema(SelectedPack)],["contributions",ArraySchema(ContextContribution)]));var ContextPlan=Struct(orderedSchemaFields(["version",ContextPlanVersion],["scopes",ArraySchema(RepositoryScope)])).annotate({parseOptions:{onExcessProperty:"error"}});var phaseSkillIds=["bug-discovery-phase","bug-resolution-phase","debugging-phase","delivery-phase","design-phase","docs-ingest-phase","finder-phase","requirements-phase","resolve-debt-phase","review-phase"];var phaseSkillSet=new Set(phaseSkillIds);var scopedPrimarySkills=(skills)=>skills.filter((skill)=>!phaseSkillSet.has(skill));var renderPrimarySkills=(skills)=>(scopedPrimarySkills(skills).length===0?["simplify"]:scopedPrimarySkills(skills)).map((skill)=>`\`${skill}\``).join(", ");var titleFromSegment=(value5)=>value5.split(/[-_]/u).filter((segment)=>segment.length>0).map((segment)=>segment.charAt(0).toUpperCase()+segment.slice(1)).join(" ");var sharedAgentsPromptTemplate=readDataFile("AGENTS.md");var rootPromptTemplate=`## Root Prompt Scaffold
@@ -1530,7 +1530,7 @@ Keep this framework pinned unless the user explicitly changes it. \`punks update
1530
1530
  `)};var packDriftPrompt=({rootDirectory,finalPacks,resolvedPacks})=>["You are updating a repo whose current package manifests resolve to a different punks pack set than the recorded scaffold manifest.","",`Repo root: ${rootDirectory}`,`Recorded packs: ${finalPacks.join(", ")}`,`Currently resolved packs: ${resolvedPacks.join(", ")}`,"","Run `hi scaffold` from the repo root and intentionally accept/edit the new pack selection. Then inspect the generated prompt specs, skills, hooks, and subagent manifests before continuing product work."].join(`
1531
1531
  `);var buildChanges=({rootDirectory,expectedDirectory,expectedFiles,previousFiles})=>{const previousByPath=new Map(previousFiles.map((file5)=>[file5.path,file5]));return expectedFiles.flatMap((expected)=>{const currentHash=hashPath(rootDirectory,expected.path);if(currentHash===expected.sha256){return[]}if(currentHash!==null&&expected.path.endsWith(".json")&&jsonContentEquals(contentForDiff(rootDirectory,expected.path),contentForDiff(expectedDirectory,expected.path))){return[]}const previous=previousByPath.get(expected.path);let status2="changed";if(currentHash===null){status2="missing"}else if(previous!==undefined&&currentHash!==previous.sha256){status2="local-edited"}return[{kind:expected.kind,path:expected.path,status:status2}]}).toSorted((left,right)=>left.path.localeCompare(right.path))};var syncSubagentsScriptFile=".agents/scripts/sync-subagents.mjs";var projectAuthoredWikiSyncFile="apps/wiki/scripts/sync-content.mjs";var isWikiManagedPath=(relativePath)=>relativePath.startsWith("wiki/")||relativePath.startsWith("app/wiki/")||relativePath.startsWith("apps/wiki/");var canonicalClaudePromptSource=(relativePath)=>relativePath===".claude/CLAUDE.md"?".agents/AGENTS.md":path25.posix.join(path25.posix.dirname(relativePath),"AGENTS.md");var isConsumerOwnedClaudePrompt=({relativePath,rootDirectory,previousFile,recordedFileType})=>{if(path25.posix.basename(relativePath)!=="CLAUDE.md"){return false}const absolutePath=path25.join(rootDirectory,relativePath);const targetExists=pathLexists(absolutePath);if(targetExists&&lstatSync4(absolutePath).isSymbolicLink()){const currentHash=hashPath(rootDirectory,relativePath);const canonicalTarget=path25.relative(path25.dirname(absolutePath),path25.join(rootDirectory,canonicalClaudePromptSource(relativePath)));return previousFile===undefined||recordedFileType!==undefined&&recordedFileType!=="symlink"||(currentHash===null?readlinkSync3(absolutePath)!==canonicalTarget:currentHash!==previousFile.sha256)}return targetExists&&!lstatSync4(absolutePath).isSymbolicLink()&&(previousFile===undefined||recordedFileType!=="file"||hashPath(rootDirectory,relativePath)!==previousFile.sha256)};var isManagedClaudePromptCopy=({relativePath,rootDirectory,previousFile,recordedFileType})=>{if(path25.posix.basename(relativePath)!=="CLAUDE.md"||previousFile===undefined||recordedFileType!==undefined&&recordedFileType!=="file"){return false}const targetPath=path25.join(rootDirectory,relativePath);const sourceRelativePath=canonicalClaudePromptSource(relativePath);const sourcePath=path25.join(rootDirectory,sourceRelativePath);return existsSync14(targetPath)&&lstatSync4(targetPath).isFile()&&existsSync14(sourcePath)&&lstatSync4(sourcePath).isFile()&&hashPath(rootDirectory,relativePath)===previousFile.sha256&&(recordedFileType==="file"||hashContent2(readFileSync13(targetPath))===hashContent2(readFileSync13(sourcePath)))};var isTailoredSyncSubagentsScript=(rootDirectory)=>{const scriptPath=path25.join(rootDirectory,syncSubagentsScriptFile);if(!existsSync14(scriptPath)){return false}const content=readFileSync13(scriptPath,"utf-8");return/["'`](?:app|apps|packages|infra)\//u.test(content)};var isProjectAuthoredManagedFile=({file:file5,rootDirectory})=>{if(file5.path===projectAuthoredWikiSyncFile){return existsSync14(path25.join(rootDirectory,file5.path))}if(file5.path===".agents/scripts/sync-subagents.mjs"){return isTailoredSyncSubagentsScript(rootDirectory)}if(file5.kind==="agent-prompt"||file5.kind==="handoff"||file5.kind==="manifest"||file5.kind==="prompt-spec"||file5.kind==="subagent"){return true}return file5.path===".claude/CLAUDE.md"||file5.path===".codex/AGENTS.md"||file5.path===".opencode/AGENTS.md"||file5.path.startsWith(".claude/agents/")||file5.path.startsWith(".codex/agents/")||file5.path.startsWith(".cursor/agents/")||file5.path.startsWith(".opencode/agents/")};var buildLegacyRequiredToolsPromptChanges=({rootDirectory})=>{const promptFiles=[agentHandoffFile,agentSystemPromptFile4];return promptFiles.flatMap((promptFile)=>{const absolutePath=path25.join(rootDirectory,promptFile);if(!existsSync14(absolutePath)){return[]}const current=readFileSync13(absolutePath,"utf-8");if(!current.includes(legacyRequiredToolsFile)){return[]}return[{kind:"handoff",path:promptFile,status:"local-edited"}]})};var rewriteLegacyRequiredToolsPrompt=({rootDirectory,relativePath})=>{const absolutePath=path25.join(rootDirectory,relativePath);if(!existsSync14(absolutePath)){return}const current=readFileSync13(absolutePath,"utf-8");if(!current.includes(legacyRequiredToolsFile)){return}writeFileSync8(absolutePath,current.replaceAll(legacyRequiredToolsFile,repoSettingsDisplayFile))};var copyIfExists=({rootDirectory,targetDirectory,relativePath,ignoreGeneratedRootDirectories=false})=>{const sourcePath=path25.join(rootDirectory,relativePath);if(!existsSync14(sourcePath)){return}const targetPath=path25.join(targetDirectory,relativePath);const stat3=lstatSync4(sourcePath);mkdirSync8(path25.dirname(targetPath),{recursive:true});if(stat3.isSymbolicLink()){symlinkSync3(readlinkSync3(sourcePath),targetPath);return}cpSync3(sourcePath,targetPath,{filter:(source)=>{const relativeSource=path25.relative(sourcePath,source).split(path25.sep).join("/");return!ignoreGeneratedRootDirectories||!hasIgnoredWikiAlignmentRootDirectory(relativeSource)},recursive:true,verbatimSymlinks:true})};var readWikiFrameworkPin=(wikiDirectory)=>{const pinPath=path25.join(wikiDirectory,"wiki-framework.md");if(!existsSync14(pinPath)){return"next"}const content=readFileSync13(pinPath,"utf-8");if(content.includes("`tanstack-start`")){return"tanstack-start"}if(content.includes("`next`")){return"next"}return"next"};var wikiRootForAlignment=(rootDirectory,detection,hasRootMarkers)=>{if(hasRootMarkers("apps/wiki")){return"apps/wiki"}if(hasRootMarkers("app/wiki")){return"app/wiki"}if(existsSync14(path25.join(rootDirectory,"apps/wiki"))){return"apps/wiki"}if(existsSync14(path25.join(rootDirectory,"wiki"))){return"wiki"}return detection.monorepo?"apps/wiki":"wiki"};var buildWikiAlignment=({rootDirectory,detection,expectedDirectory,scriptEnvironment,scriptRuntimePath:scriptRuntimePath2})=>{const hasWikiRootMarkers2=(relativeRoot)=>{const absoluteRoot=path25.join(rootDirectory,relativeRoot);return["package.json","backlog-provider.md","wiki-framework.md"].some((marker)=>existsSync14(path25.join(absoluteRoot,marker)))};const wikiRoot=wikiRootForAlignment(rootDirectory,detection,hasWikiRootMarkers2);copyIfExists({ignoreGeneratedRootDirectories:true,relativePath:wikiRoot,rootDirectory,targetDirectory:expectedDirectory});copyIfExists({relativePath:"docs",rootDirectory,targetDirectory:expectedDirectory});const wikiFramework=readWikiFrameworkPin(path25.join(expectedDirectory,wikiRoot));scaffoldWikiForDirectory({monorepo:wikiRoot==="apps/wiki",outputDirectory:expectedDirectory,wikiFramework});const syncScript=path25.join(expectedDirectory,wikiRoot,"scripts","sync-content.mjs");if(existsSync14(syncScript)){runJavaScriptFileSync({cwd:expectedDirectory,file:syncScript,...scriptEnvironment===undefined?{}:{environment:scriptEnvironment},...scriptRuntimePath2===undefined?{}:{runtimePath:scriptRuntimePath2}})}const expectedFiles=collectRelativeFiles2(expectedDirectory,wikiRoot).map((relativePath)=>({kind:"harness",path:relativePath,sha256:hashPath(expectedDirectory,relativePath)??""})).filter((file5)=>!isProjectAuthoredManagedFile({file:file5,rootDirectory}));return{changes:buildChanges({expectedDirectory,expectedFiles,previousFiles:[],rootDirectory}),expectedDirectory,expectedFiles}};var readValidatedWikiFrameworkPin=(wikiDirectory)=>{const pinPath=path25.join(wikiDirectory,"wiki-framework.md");if(!existsSync14(pinPath)){return"next"}const content=readFileSync13(pinPath,"utf-8");if(content.includes("`tanstack-start`")){return"tanstack-start"}if(content.includes("`next`")){return"next"}throw new Error(`Invalid wiki framework pin: ${pinPath}`)};var buildGitignoreCleanup=({rootDirectory,expectedDirectory})=>{const relativePath=".gitignore";if(!existsSync14(path25.join(rootDirectory,relativePath))){return[]}copyManagedFile({fromDirectory:rootDirectory,relativePath,toDirectory:expectedDirectory});const cleanup=removeHarnessDirectoriesFromGitignore(expectedDirectory);if(cleanup.removedPatterns.length===0){return[]}const expectedFile={kind:"harness",path:relativePath,sha256:hashPath(expectedDirectory,relativePath)??""};return buildChanges({expectedDirectory,expectedFiles:[expectedFile],previousFiles:[],rootDirectory})};var semanticFile=({content,encoding="utf-8",kind="harness",mode=420,path:relativePath})=>({content,encoding,kind,...encoding==="symlink"?{}:{mode},path:relativePath,provenance:{revision:version2,source:"scaffold-semantics"}});var isJsonValue=(value5)=>{if(value5===null||typeof value5==="boolean"||typeof value5==="number"||typeof value5==="string"){return true}if(Array.isArray(value5)){return value5.every(isJsonValue)}return typeof value5==="object"&&Object.values(value5).every(isJsonValue)};var isJsonObject2=(value5)=>isJsonValue(value5)&&typeof value5==="object"&&value5!==null&&!Array.isArray(value5);var isStringArray2=(value5)=>Array.isArray(value5)&&value5.every((entry)=>typeof entry==="string");var projectionSemanticState=({desiredState})=>{const files=new Map;const structuredEntries=[];for(const projection of desiredState.projections){for(const action2 of projection.actions){const applyFileSemantics=()=>{if(action2.operation==="use-native-mirror"&&typeof action2.nativePath==="string"&&typeof action2.canonicalPath==="string"){const nativeRoot=`${action2.nativePath.split("/skills/")[0]}/skills`;const canonicalRoot=`${action2.canonicalPath.split("/skills/")[0]}/skills`;files.set(nativeRoot,semanticFile({content:path25.posix.relative(path25.posix.dirname(nativeRoot),canonicalRoot),encoding:"symlink",path:nativeRoot}))}if(action2.operation==="mirror"&&action2.id.includes(":lifecycle-hook:")&&typeof action2.source==="string"&&typeof action2.target==="string"&&action2.source!==action2.target){files.set(action2.target,semanticFile({content:path25.posix.relative(path25.posix.dirname(action2.target),action2.source),encoding:"symlink",kind:action2.target.includes("/hooks/")?"hook":"harness",path:action2.target}))}if(action2.operation==="merge-json"&&typeof action2.file==="string"&&isStringArray2(action2.path)&&isJsonValue(action2.value)){const value5=action2.file===".claude/settings.json"?[action2.value]:action2.value;structuredEntries.push({file:action2.file,kind:"field",path:action2.path,provenance:{revision:version2,source:"harness-projection"},value:value5})}};applyFileSemantics();const applyJsonKeySemantics=()=>{if(action2.operation==="merge-json"&&typeof action2.target==="string"&&action2.file===undefined&&!action2.target.includes("#")&&isJsonObject2(action2.value)){for(const[key,value5]of Object.entries(action2.value)){if(action2.target==="opencode.json"&&key==="formatter"&&isJsonObject2(value5)&&"harness-format-edited-file"in value5){structuredEntries.push({file:action2.target,kind:"key",path:["formatter","harness-format-edited-file"],provenance:{revision:version2,source:"harness-projection"},value:value5["harness-format-edited-file"]});continue}structuredEntries.push({file:action2.target,kind:"key",path:[key],provenance:{revision:version2,source:"harness-projection"},value:value5})}}};applyJsonKeySemantics();const applyHookConfigSemantics=()=>{const{config}=action2;if(action2.operation==="mirror"&&isJsonObject2(config)&&typeof config.path==="string"&&typeof config.event==="string"&&typeof config.command==="string"&&(config.timeout===undefined||typeof config.timeout==="number")){structuredEntries.push({file:config.path,kind:"field",path:["hooks",config.event],provenance:{revision:version2,source:"harness-projection"},value:[{command:config.command,...config.timeout===undefined?{}:{timeout:config.timeout}}]})}};applyHookConfigSemantics()}}const codexHookActions=desiredState.projections.flatMap(({actions})=>actions).filter((action2)=>action2.operation==="merge-toml"&&action2.id.includes(":lifecycle-hook:"));const applyCodexHookSemantics=()=>{if(codexHookActions.length===0){return}const hasUpdateCheck=codexHookActions.some((action2)=>action2.id.includes("scaffold-update-check"));const hasFormatHook=codexHookActions.some((action2)=>action2.id.includes("format-edited-file"));const lines2=["[agents]","max_depth = 1","","[features]","codex_hooks = true","","[hooks]"];if(hasUpdateCheck||hasFormatHook){const hooks=[...hasUpdateCheck?[' { type = "command", command = "node \\"$(git rev-parse --show-toplevel)/.codex/hooks/scaffold-update-check.mjs\\" codex", statusMessage = "Checking Harness scaffold", timeout = 60 },']:[],...hasFormatHook?[' { type = "command", command = "node \\"$(git rev-parse --show-toplevel)/.codex/hooks/format-edited-file.mjs\\" session-start", statusMessage = "Capturing edited-file baseline", timeout = 30 },']:[]];lines2.push("SessionStart = [",' { matcher = "startup|resume", hooks = [',...hooks," ] },","]")}if(hasFormatHook){lines2.push("PostToolUse = [",' { matcher = "Bash|apply_patch|.*apply.?patch.*|edit|write|multiedit", hooks = [',' { type = "command", command = "node \\"$(git rev-parse --show-toplevel)/.codex/hooks/format-edited-file.mjs\\" post", statusMessage = "Auto-formatting edited files", timeout = 30 },'," ] },","]")}lines2.push("");files.set(".codex/config.toml",semanticFile({content:lines2.join(`
1532
1532
  `),path:".codex/config.toml"}))};applyCodexHookSemantics();return{files:[...files.values()],structuredEntries}};var wikiRootForDetection=(detection)=>{const detectedManifestPaths=new Set(detection.manifests.map(({relativePath})=>relativePath.split(path25.sep).join("/")));if(detectedManifestPaths.has("apps/wiki/package.json")){return"apps/wiki"}if(detectedManifestPaths.has("app/wiki/package.json")){return"app/wiki"}if(detectedManifestPaths.has("wiki/package.json")){return"wiki"}return detection.monorepo?"apps/wiki":"wiki"};var wikiSemanticState=({detection,finalPacks,framework,settings})=>{if(!finalPacks.includes("docs")){return{files:[],structuredEntries:[]}}const wikiRoot=wikiRootForDetection(detection);const template=makeWikiScaffoldTemplate(wikiRoot,framework);const files=[...template.files.map((file5)=>semanticFile({...file5,path:path25.posix.join(wikiRoot,file5.path)})),...template.rawSubdirectories.map((directory3)=>semanticFile({content:"",path:path25.posix.join(wikiRoot,"raw",directory3,".gitkeep")})),semanticFile({content:"",path:path25.posix.join(wikiRoot,"content/docs/project/.gitkeep")}),semanticFile({content:"",path:path25.posix.join(wikiRoot,"specs/.gitkeep")}),semanticFile({content:template.agentsMarkdown,path:path25.posix.join(wikiRoot,"AGENTS.md")}),semanticFile({content:"AGENTS.md",encoding:"symlink",path:path25.posix.join(wikiRoot,"CLAUDE.md")}),semanticFile({content:template.indexMarkdown,path:path25.posix.join(wikiRoot,"index.md")}),semanticFile({content:template.logMarkdown,path:path25.posix.join(wikiRoot,"log.md")}),semanticFile({content:renderBacklogProviderMarkdown(settings.backlogProvider),path:path25.posix.join(wikiRoot,"backlog-provider.md")}),semanticFile({content:renderWikiFrameworkMarkdown(framework),path:path25.posix.join(wikiRoot,"wiki-framework.md")})];return{files,structuredEntries:[]}};var semanticDesiredState=({desiredState,detection,finalPacks,wikiFramework,settings})=>{const projection=projectionSemanticState({desiredState});const wiki=wikiSemanticState({detection,finalPacks,framework:wikiFramework,settings});return{files:[...projection.files,...wiki.files],structuredEntries:[...projection.structuredEntries,...wiki.structuredEntries]}};var desiredFileBytes=(file5)=>file5.encoding==="base64"?Buffer.from(file5.content,"base64"):file5.content;var desiredFileFingerprint=(file5)=>JSON.stringify({mode:file5.mode===undefined?null:fileMode2(file5.mode),sha256:hashContent2(file5.encoding==="symlink"?`symlink:${file5.content}`:desiredFileBytes(file5)),type:file5.encoding==="symlink"?"symlink":"file"});var observeManagedFile=({expectedMode,kind,relativePath,rootDirectory})=>{const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false});const projectAuthored=isProjectAuthoredManagedFile({file:{kind,path:relativePath,sha256:""},rootDirectory});if(!pathLexists(absolutePath)){return{fingerprint:"missing",kind,mode:null,path:relativePath,projectAuthored,sha256:null,type:"missing"}}const stat3=lstatSync4(absolutePath);if(!stat3.isSymbolicLink()&&!stat3.isFile()){return{fingerprint:JSON.stringify({mode:null,sha256:null,type:"other"}),kind,mode:fileMode2(stat3.mode),path:relativePath,projectAuthored,sha256:null,type:"other"}}const isSymlink=stat3.isSymbolicLink();const bytes=isSymlink?undefined:readFileSync13(absolutePath);const sha256=hashContent2(isSymlink?`symlink:${readlinkSync3(absolutePath)}`:bytes??"");const mode=isSymlink?null:fileMode2(stat3.mode);return{...bytes===undefined?{}:{content:bytes.toString("utf-8")},fingerprint:JSON.stringify({mode:expectedMode===undefined||isSymlink?null:mode,sha256,type:isSymlink?"symlink":"file"}),kind,mode,path:relativePath,projectAuthored,sha256,type:isSymlink?"symlink":"file"}};var packageFileForWorkspace=(workspace)=>workspace==="."?"package.json":path25.posix.join(workspace,"package.json");var readJsonObject=(absolutePath)=>{try{const value5=JSON.parse(readFileSync13(absolutePath,"utf-8"));return typeof value5==="object"&&value5!==null&&!Array.isArray(value5)?value5:null}catch{return null}};var applyManagedLifecycleHook=({action:action2,entryFile,leaf,parent,priorEntry})=>{const desiredHook=action2._tag==="SafeRemoveScaffoldEntry"?undefined:managedLifecycleHook(action2.desired);let previousHook;if(action2._tag==="SafeRemoveScaffoldEntry"){previousHook=managedLifecycleHook(action2.previous)}else if(priorEntry!==undefined){previousHook=managedLifecycleHook(priorEntry)}const managedHook=desiredHook??previousHook;if(managedHook===undefined){return false}const current=parent[leaf];if(current!==undefined&&!Array.isArray(current)){throw new Error(`Lifecycle hook configuration is not an array: ${entryFile}`)}const previousValue=(previousHook??desiredHook)?.value;let removedPrevious=false;const consumerHooks=(current??[]).filter((hook)=>{if(!removedPrevious&&previousValue!==undefined&&stableJsonStringify(hook)===stableJsonStringify(previousValue)){removedPrevious=true;return false}return true});if(action2._tag==="SafeRemoveScaffoldEntry"){if(consumerHooks.length===0){Reflect.deleteProperty(parent,leaf)}else{parent[leaf]=consumerHooks}}else{parent[leaf]=[...consumerHooks,(desiredHook??managedHook).value]}return true};var receiptForFile=({kind,relativePath,rootDirectory})=>{const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false});const stat3=lstatSync4(absolutePath);const type2=stat3.isSymbolicLink()?"symlink":"file";return{kind,mode:type2==="symlink"?null:fileMode2(stat3.mode),path:relativePath,sha256:hashPath(rootDirectory,relativePath)??"",type:type2}};var writeJsonDocument=(absolutePath,document)=>{mkdirSync8(path25.dirname(absolutePath),{recursive:true});writeFileSync8(absolutePath,`${encodePrettyJson3(document)}
1533
- `)};var usesClassicYarn=(rootDirectory,configuredManager,configuredVersion)=>{if(configuredManager==="yarn"&&configuredVersion!==null){return/^1(?:\.|$)/u.test(configuredVersion)}if(configuredManager!==null){return false}const yarnLockfile=path25.join(rootDirectory,"yarn.lock");return existsSync14(yarnLockfile)&&/(?:^|\n)# yarn lockfile v1(?:\n|$)/u.test(readFileSync13(yarnLockfile,"utf-8"))};var dependencyLockfileCommand=(rootDirectory)=>{const rootManifest=readJsonObject(path25.join(rootDirectory,"package.json"));const configuredValue=typeof rootManifest?.packageManager==="string"?rootManifest.packageManager:null;const configuredMatch=configuredValue===null?null:/^(?<manager>[^@]+)(?:@(?<version>.+))?$/u.exec(configuredValue);const configured=configuredMatch?.groups?.manager??null;const configuredVersion=configuredMatch?.groups?.version??null;const manager=configured??[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["package-lock.json","npm"],["yarn.lock","yarn"]].find(([lockfile])=>existsSync14(path25.join(rootDirectory,lockfile)))?.[1]??null;switch(manager){case"bun":{return["bun",["install","--lockfile-only"]]}case"npm":{return["npm",["install","--package-lock-only","--ignore-scripts"]]}case"pnpm":{return["pnpm",["install","--lockfile-only","--ignore-scripts"]]}case"yarn":{if(usesClassicYarn(rootDirectory,configured,configuredVersion)){return["yarn",["install","--ignore-scripts","--non-interactive"]]}return["yarn",["install","--mode=update-lockfile"]]}default:{return null}}};var defaultDependencyProcess=(command,args2,cwd)=>{const result4=spawnSync3(command,[...args2],{cwd,encoding:"utf-8",stdio:"pipe"});if(result4.error!==undefined||result4.status!==0){throw new Error(result4.error?.message||result4.stderr.trim()||`${command} exited ${result4.status??1}`)}};var dependencyLockfiles=["bun.lock","bun.lockb","package-lock.json","pnpm-lock.yaml","yarn.lock"];var snapshotDependencyLockfiles=(rootDirectory)=>new Map(dependencyLockfiles.map((lockfile)=>{const absolutePath=path25.join(rootDirectory,lockfile);return[absolutePath,existsSync14(absolutePath)?readFileSync13(absolutePath):null]}));var restoreDependencyLockfiles=(snapshot)=>{for(const[absolutePath,content]of snapshot){if(content===null){rmSync6(absolutePath,{force:true})}else{writeFileSync8(absolutePath,content)}}};var makeScaffoldReconciliationApplicators=({dependencyProcess,priorReceipt,rootDirectory})=>({applyDependency:(action2)=>try_3({catch:(cause)=>cause,try:()=>{const entry=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous:action2.desired;const absolutePath=resolveMutableJsonPath(rootDirectory,packageFileForWorkspace(entry.workspace));const document=readJsonObject(absolutePath);if(document===null){throw new Error(`Package manifest is not a JSON object: ${packageFileForWorkspace(entry.workspace)}`)}const sectionValue=document[entry.section];if(sectionValue!==undefined&&(typeof sectionValue!=="object"||sectionValue===null||Array.isArray(sectionValue))){throw new Error(`Package dependency section is not an object: ${entry.section}`)}const section2=sectionValue??{};const previousPackageManifest=readFileSync13(absolutePath);const lockfileSnapshot=snapshotDependencyLockfiles(rootDirectory);if(action2._tag==="SafeRemoveScaffoldEntry"){Reflect.deleteProperty(section2,entry.name)}else{section2[entry.name]=entry.version}document[entry.section]=section2;writeJsonDocument(absolutePath,document);const lockfileCommand=dependencyLockfileCommand(rootDirectory);if(lockfileCommand!==null){try{dependencyProcess(lockfileCommand[0],lockfileCommand[1],rootDirectory)}catch(error2){writeFileSync8(absolutePath,previousPackageManifest);restoreDependencyLockfiles(lockfileSnapshot);throw error2}}return action2._tag==="SafeRemoveScaffoldEntry"?null:{name:entry.name,section:entry.section,version:entry.version,workspace:entry.workspace}}}),applyFile:(action2)=>try_3({catch:(cause)=>cause,try:()=>{const relativePath=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path;const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false});if(action2._tag==="SafeRemoveScaffoldEntry"){rmSync6(absolutePath,{force:true,recursive:true});return null}const{desired}=action2;mkdirSync8(path25.dirname(absolutePath),{recursive:true});if(desired.encoding==="symlink"){rmSync6(absolutePath,{force:true,recursive:true});symlinkSync3(desired.content,absolutePath)}else{if(pathLexists(absolutePath)&&lstatSync4(absolutePath).isSymbolicLink()){rmSync6(absolutePath,{force:true})}writeFileSync8(absolutePath,desired.encoding==="base64"?Buffer.from(desired.content,"base64"):desired.content);if(desired.mode!==undefined){chmodSync2(absolutePath,fileMode2(desired.mode))}}return receiptForFile({kind:desired.kind,relativePath,rootDirectory})}}),applyStructuredEntry:(action2)=>try_3({catch:(cause)=>cause,try:()=>{const entry=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous:action2.desired;const absolutePath=resolveMutableJsonPath(rootDirectory,entry.file);const document=existsSync14(absolutePath)?readJsonObject(absolutePath):{};if(document===null){throw new Error(`Structured configuration is not a JSON object: ${entry.file}`)}if(entry.path.length===0){throw new Error(`Structured entry path is empty: ${entry.file}`)}let parent=document;for(const segment of entry.path.slice(0,-1)){const value5=parent[segment];if(value5===undefined){const child={};parent[segment]=child;parent=child}else if(typeof value5==="object"&&value5!==null&&!Array.isArray(value5)){parent=value5}else{throw new Error(`Structured configuration cannot traverse ${segment}: ${entry.file}`)}}const leaf=entry.path.at(-1)??"";const priorEntry=priorReceipt.structuredEntries.find((candidate)=>JSON.stringify([candidate.file,candidate.kind,candidate.path])===action2.identity);const appliedLifecycleHook=applyManagedLifecycleHook({action:action2,entryFile:entry.file,leaf,parent,...priorEntry===undefined?{}:{priorEntry}});if(!appliedLifecycleHook&&action2._tag==="SafeRemoveScaffoldEntry"){Reflect.deleteProperty(parent,leaf)}else if(!appliedLifecycleHook){parent[leaf]=entry.value}writeJsonDocument(absolutePath,document);return action2._tag==="SafeRemoveScaffoldEntry"?null:{file:entry.file,kind:entry.kind,path:entry.path,value:entry.value}}}),persistReceipt:(receipt)=>try_3({catch:(cause)=>cause,try:()=>{const manifestPath=path25.join(rootDirectory,scaffoldManifestFile);const manifest=readJsonObject(manifestPath);if(manifest===null){throw new Error(`Scaffold manifest is not a JSON object: ${scaffoldManifestFile}`)}manifest.managedFiles=receipt.files.map(({kind,path:relativePath,sha256})=>({kind,path:relativePath,sha256}));manifest.managedFileTypes=Object.fromEntries(receipt.files.map(({path:relativePath,type:type2})=>[relativePath,type2]));manifest.managedFileModes=Object.fromEntries(receipt.files.map(({mode,path:relativePath,type:type2})=>[relativePath,type2==="symlink"?null:mode]));manifest.managedDependencies=receipt.dependencies;manifest.managedStructuredEntries=receipt.structuredEntries;manifest.scaffoldDegradations=receipt.degradations;writeJsonDocument(manifestPath,manifest)}})});var reconciliationControlledPaths=({desiredState,plan,priorReceipt})=>{const entryPath=new Map;const recordEntryPath=(item,identity3,relativePath)=>{entryPath.set(`${item}\x00${identity3}`,relativePath)};for(const file5 of[...desiredState.files,...priorReceipt.files]){recordEntryPath("file",file5.path,file5.path)}for(const dependency of[...desiredState.dependencies,...priorReceipt.dependencies]){recordEntryPath("dependency",JSON.stringify([dependency.workspace,dependency.section,dependency.name]),packageFileForWorkspace(dependency.workspace))}for(const entry of[...desiredState.structuredEntries,...priorReceipt.structuredEntries]){recordEntryPath("structured-entry",JSON.stringify([entry.file,entry.kind,entry.path]),entry.file)}const paths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...desiredState.structuredEntries.map(({file:file5})=>file5)]);for(const action2 of plan.actions){if(action2.item==="file"){paths.add(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path)}else if(action2.item==="dependency"){paths.add(packageFileForWorkspace(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.workspace:action2.desired.workspace))}else{paths.add(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.file:action2.desired.file)}}for(const conflict of plan.conflicts){const relativePath=entryPath.get(`${conflict.item}\x00${conflict.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}for(const skip of plan.skips){const relativePath=entryPath.get(`${skip.item}\x00${skip.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}for(const failure of plan.failures){if(failure._tag==="CrossFamilyScaffoldOwnershipFailure"){paths.add(failure.path);continue}if("item"in failure){const relativePath=entryPath.get(`${failure.item}\x00${failure.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}}return paths};var removableStaleManagedFiles=({plan,reconciliationPaths,staleFiles})=>{const safeFileActionPaths=new Set(plan.actions.flatMap((action2)=>{if(action2.item!=="file"){return[]}return[action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path]}));return staleFiles.filter((relativePath)=>!reconciliationPaths.has(relativePath)||safeFileActionPaths.has(relativePath)).toSorted()};var reconciliationStatus=(outcomes)=>{const blocked=outcomes.some(({_tag})=>_tag==="ScaffoldActionBlocked"||_tag==="ScaffoldActionFailed"||_tag==="ScaffoldConflictPreserved"||_tag==="ScaffoldPlanningFailed");if(!blocked){return"succeeded"}return outcomes.some(({_tag})=>_tag==="ScaffoldActionSucceeded")?"partial":"failed"};var publicReconciliationOperation=(action2)=>{if(action2._tag==="SafeCreateScaffoldEntry"){return"create"}return action2._tag==="SafeUpdateScaffoldEntry"?"update":"remove"};var publicReconciliationActions=(plan)=>plan.actions.map((action2)=>({identity:action2.identity,item:action2.item,operation:publicReconciliationOperation(action2)}));var mergePrioritizedChanges=(target,changes)=>{const priority={changed:0,"local-edited":1,missing:2};for(const change of changes){const previous=target.get(change.path);if(previous===undefined||priority[change.status]>priority[previous.status]){target.set(change.path,change)}}};var observeStructuredValue=(document,entry)=>{let value5=document;for(const[index2,segment]of entry.path.entries()){if(typeof value5!=="object"||value5===null||Array.isArray(value5)){return{_tag:"InvalidStructuredObservation",message:`Structured configuration cannot traverse ${entry.path.slice(0,index2).join(".")}: ${entry.file}`}}if(!Object.hasOwn(value5,segment)){return{_tag:"MissingStructuredObservation"}}value5=value5[segment]}const expectedHook=managedLifecycleHook(entry);if(expectedHook!==undefined){if(!Array.isArray(value5)){return{_tag:"InvalidStructuredObservation",message:`Lifecycle hook configuration is not an array: ${entry.file}`}}const observedHook=value5.find((candidate)=>stableJsonStringify(candidate)===stableJsonStringify(expectedHook.value));return observedHook===undefined?{_tag:"MissingStructuredObservation"}:{_tag:"PresentStructuredObservation",value:[observedHook]}}return{_tag:"PresentStructuredObservation",value:value5}};var dependencyObservationIdentity=({name:name2,section:section2,workspace})=>JSON.stringify([workspace,section2,name2]);var structuredObservationIdentity=({file:file5,kind,path:entryPath})=>JSON.stringify([file5,kind,entryPath]);var observedEntryKey=(item,identity3)=>JSON.stringify([item,identity3]);var observeDesiredState=({desiredState,manifest,rootDirectory,semanticState})=>{const desiredFiles=new Map([...desiredState.files,...semanticState.files].map((file5)=>[file5.path,file5]));const files=new Map;for(const file5 of manifest.managedFiles??[]){files.set(file5.path,{kind:file5.kind})}for(const file5 of desiredFiles.values()){files.set(file5.path,{kind:file5.kind,...file5.mode===undefined?{}:{mode:file5.mode}})}const dependencyEntries=new Map([...desiredState.dependencies,...manifest.managedDependencies??[]].map((entry)=>[dependencyObservationIdentity(entry),entry]));const structuredEntries=new Map([...desiredState.structuredEntries,...semanticState.structuredEntries,...manifest.managedStructuredEntries??[]].map((entry)=>[structuredObservationIdentity(entry),entry]));const invalidEntries=new Map;for(const entry of structuredEntries.values()){const identity3=structuredObservationIdentity(entry);try{resolveMutableJsonPath(rootDirectory,entry.file);if(!files.has(entry.file)){files.set(entry.file,{kind:"harness"})}}catch(error2){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:error2 instanceof Error?error2.message:String(error2)})}}const dependencies=[...dependencyEntries.values()].flatMap((dependency)=>{const identity3=dependencyObservationIdentity(dependency);let manifestPath;try{manifestPath=resolveMutableJsonPath(rootDirectory,packageFileForWorkspace(dependency.workspace))}catch(error2){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:error2 instanceof Error?error2.message:String(error2)});return[]}if(!existsSync14(manifestPath)){return[]}const packageManifest=readJsonObject(manifestPath);if(packageManifest===null){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package manifest is not a JSON object: ${packageFileForWorkspace(dependency.workspace)}`});return[]}const section2=packageManifest[dependency.section];if(section2===undefined){return[]}if(typeof section2!=="object"||section2===null||Array.isArray(section2)){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package dependency section is not an object: ${dependency.section}`});return[]}const value5=section2[dependency.name];if(value5===undefined){return[]}if(typeof value5!=="string"){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package dependency version is not a string: ${identity3}`});return[]}return[{name:dependency.name,section:dependency.section,version:value5,workspace:dependency.workspace}]});const observedStructuredEntries=[...structuredEntries.values()].flatMap((entry)=>{const identity3=structuredObservationIdentity(entry);let absolutePath;try{absolutePath=resolveMutableJsonPath(rootDirectory,entry.file)}catch(error2){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:error2 instanceof Error?error2.message:String(error2)});return[]}if(!existsSync14(absolutePath)){return[]}const document=readJsonObject(absolutePath);if(document===null){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:`Structured configuration is not a JSON object: ${entry.file}`});return[]}const observation=observeStructuredValue(document,entry);if(observation._tag==="InvalidStructuredObservation"){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:observation.message});return[]}return observation._tag==="MissingStructuredObservation"?[]:[{file:entry.file,kind:entry.kind,path:entry.path,value:observation.value}]});const observedFiles=[...files].flatMap(([relativePath,file5])=>{try{return[observeManagedFile({...file5.mode===undefined?{}:{expectedMode:file5.mode},kind:file5.kind,relativePath,rootDirectory})]}catch(error2){invalidEntries.set(observedEntryKey("file",relativePath),{identity:relativePath,item:"file",message:error2 instanceof Error?error2.message:String(error2)});return[]}});return{dependencies,files:observedFiles,invalidEntries:[...invalidEntries.values()].toSorted((left,right)=>left.identity.localeCompare(right.identity)),structuredEntries:observedStructuredEntries,version:"1"}};var priorReceiptFromManifest=(manifest,rootDirectory,desiredFiles)=>{const desiredModes=new Map(desiredFiles.map((file5)=>[file5.path,file5.mode]));return{dependencies:manifest.managedDependencies??[],files:(manifest.managedFiles??[]).filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).map((file5)=>{const type2=manifest.managedFileTypes?.[file5.path]==="symlink"?"symlink":"file";const recordedMode=manifest.managedFileModes?.[file5.path];const absolutePath=resolveContainedReceiptPath(rootDirectory,file5.path,{followLeaf:false});const currentMode=type2==="file"&&pathLexists(absolutePath)&&lstatSync4(absolutePath).isFile()?fileMode2(lstatSync4(absolutePath).mode):undefined;const desiredMode=desiredModes.get(file5.path);let inferredMode;if(recordedMode===undefined&&type2==="symlink"){inferredMode=null}else if(recordedMode===undefined&&currentMode!==undefined&&desiredMode!==undefined&&currentMode===desiredMode%512&&hashPath(rootDirectory,file5.path)===file5.sha256){inferredMode=currentMode}const mode=recordedMode===undefined?inferredMode:recordedMode;return{kind:file5.kind,...mode===undefined?{}:{mode},path:file5.path,sha256:file5.sha256,type:type2}}),structuredEntries:(manifest.managedStructuredEntries??[]).map((entry)=>({...entry,value:entry.value})),version:"1"}};var changeStatus=({path:relativePath,observedFiles,previousFiles})=>{const observed=observedFiles.get(relativePath);if(observed===undefined||observed.type==="missing"){return"missing"}const previous=previousFiles.find((file5)=>file5.path===relativePath);return previous!==undefined&&previous.sha256!==observed.sha256?"local-edited":"changed"};var compareObservedState=({desiredState,manifest,observedState,semanticState})=>{const previousFiles=manifest.managedFiles??[];const observedFiles=new Map(observedState.files.map((file5)=>[file5.path,file5]));const semanticPaths=new Set(semanticState.files.map((file5)=>file5.path));const changes=new Map;const addChange=(change)=>{const previous=changes.get(change.path);const priority={changed:0,"local-edited":1,missing:2};if(previous===undefined||priority[change.status]>priority[previous.status]){changes.set(change.path,change)}};const comparableFiles=new Map([...desiredState.files,...semanticState.files].map((file5)=>[file5.path,file5]));const compareFiles=()=>{for(const file5 of comparableFiles.values()){const observed=observedFiles.get(file5.path);if(file5.kind==="context-plan"||file5.kind==="projection-receipt"||observed?.projectAuthored===true&&!semanticPaths.has(file5.path)){continue}const fingerprintMatches=observed?.fingerprint===desiredFileFingerprint(file5);const jsonMatches=!fingerprintMatches&&file5.encoding!=="base64"&&file5.encoding!=="symlink"&&file5.mode===undefined&&file5.path.endsWith(".json")&&jsonContentEquals(observed?.content??"",file5.content);if(fingerprintMatches||jsonMatches){continue}addChange({kind:file5.kind,path:file5.path,status:changeStatus({observedFiles,path:file5.path,previousFiles})})}};compareFiles();const observedDependencies=new Map(observedState.dependencies.map((dependency)=>[`${dependency.workspace}:${dependency.section}:${dependency.name}`,dependency]));for(const dependency of desiredState.dependencies){const identity3=`${dependency.workspace}:${dependency.section}:${dependency.name}`;if(observedDependencies.get(identity3)?.version===dependency.version){continue}const packageFile=packageFileForWorkspace(dependency.workspace);addChange({kind:"manifest",path:packageFile,status:changeStatus({observedFiles,path:packageFile,previousFiles})})}const observedStructuredEntries=new Map(observedState.structuredEntries.map((entry)=>[JSON.stringify([entry.file,entry.kind,entry.path]),entry]));for(const entry of[...desiredState.structuredEntries,...semanticState.structuredEntries]){if(entry.file===repoSettingsDisplayFile&&observedFiles.get(entry.file)?.type==="missing"){continue}const identity3=JSON.stringify([entry.file,entry.kind,entry.path]);const observed=observedStructuredEntries.get(identity3);if(observed!==undefined&&stableJsonStringify(observed.value)===stableJsonStringify(entry.value)){continue}addChange({kind:"harness",path:entry.file,status:changeStatus({observedFiles,path:entry.file,previousFiles})})}const desiredPaths=new Set([...desiredState.files.map((file5)=>file5.path),...desiredState.dependencies.map((dependency)=>packageFileForWorkspace(dependency.workspace)),...desiredState.structuredEntries.map((entry)=>entry.file),...semanticState.files.map((file5)=>file5.path),...semanticState.structuredEntries.map((entry)=>entry.file)]);const staleFiles=previousFiles.filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).filter(({kind})=>kind!=="context-plan"&&kind!=="projection-receipt").filter((file5)=>observedFiles.get(file5.path)?.projectAuthored!==true).map((file5)=>file5.path).filter((file5)=>!desiredPaths.has(file5)).toSorted();return{changedFiles:[...changes.values()].toSorted((left,right)=>left.path.localeCompare(right.path)),staleFiles}};var resolveUpdateToolRuntime=({scriptEnvironment,toolRuntime})=>{if(toolRuntime!==undefined){return toolRuntime}if(scriptEnvironment===undefined){return}return makeToolCommandRuntime(Object.fromEntries(Object.entries(scriptEnvironment).filter((entry)=>entry[1]!==undefined)))};var runScaffoldOperation=({operation:operation2,rootDirectory,interaction,check:requestedCheck=false,write:requestedWrite=false,yes:requestedYes=false,emitJson:requestedEmitJson=false,ensureTools:requestedEnsureTools=true,baseline=bundledBaseline,allowBundledBaselineDriftApply=false,toolStdio:requestedToolStdio,toolRuntime,scaffoldLifecycle={},reconciliationApplicators,dependencyProcess=defaultDependencyProcess,configuration={disableBundledUrl:true},emitOutput=true,scriptEnvironment,scriptRuntimePath:scriptRuntimePath2})=>{const check3=operation2==="check"||requestedCheck;const write2=operation2==="update"&&requestedWrite;const yes=operation2==="update"&&requestedYes;const emitJson=operation2==="update"&&requestedEmitJson;const ensureTools2=operation2==="update"&&requestedEnsureTools;const toolStdio=requestedToolStdio??(emitJson?"ignore":"inherit");const resolvedToolRuntime=resolveUpdateToolRuntime({scriptEnvironment,toolRuntime});let updateStagingDirectory=null;let wikiStagingDirectory=null;return gen2(function*executeScaffoldOperation(){const projectSettings=yield*ProjectSettings;const writeHuman=noopHumanOutput;const manifest=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to read scaffold manifest."}),try:()=>readManifest(rootDirectory)});yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid managed file receipt path."}),try:()=>{for(const file5 of manifest.managedFiles??[]){resolveContainedReceiptPath(rootDirectory,file5.path,{followLeaf:false})}}});const finalPacks=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid scaffold manifest."}),try:()=>normalizePacks(manifest.finalPacks,baseline)});const repoShapeMode=normalizeRepoShapeMode(manifest.repoShapeMode);const detection=applyRepoShapeMode(yield*detectRepository(rootDirectory),repoShapeMode);const resolved=resolvePackSelection(detection,baseline);const manifestBaseline=manifest.baseline;const baselineDrift=typeof manifestBaseline?.version==="string"&&manifestBaseline.version!==baseline.summary.version;const resolvedPacks=resolved.preselectedPacks;const packDrift=hasActionablePackDrift({finalPacks,resolvedPacks});const updateFinalPacks=write2||yes?acceptResolvedPacks({baseline,finalPacks,resolvedPacks}):finalPacks;const wikiRoot=wikiRootForDetection(detection);const wikiFramework=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid wiki framework pin."}),try:()=>readValidatedWikiFrameworkPin(path25.join(rootDirectory,wikiRoot))});const wikiPromptTarget=wikiPromptTargetFor({wikiFramework,wikiRoot});const wikiPromptTargets=updateFinalPacks.includes("docs")?[wikiPromptTarget]:[];const expectedDirectory=mkdtempSync3(path25.join(tmpdir6(),"punks-update-"));updateStagingDirectory=expectedDirectory;const repoSettingsOnDisk=yield*projectSettings.read(rootDirectory).pipe(map7(some2),catchTag2("ProjectSettingsMissing",()=>succeed6(none2())),mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const inferredRepoSettings=isNone2(repoSettingsOnDisk)?yield*projectSettings.infer(rootDirectory).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message}))):none2();const repoSettings=match(repoSettingsOnDisk,{onNone:()=>inferredRepoSettings,onSome:({settings})=>some2(settings)});if(isNone2(repoSettings)){return yield*fail6(new CliValidationError({message:`Project settings are missing at ${path25.join(rootDirectory,projectSettingsFile)}.`}))}const calculatedRequiredTools=requiredToolsForSkills2(selectedSkills3(updateFinalPacks,baseline),baseline);const settingsRequiredTools=deriveRequiredTools({repositoryManager:repoSettings.value.repositoryManager,requiredTools:calculatedRequiredTools});const contextPlan=yield*compileScaffoldContextPlan({additionalPromptTargets:wikiPromptTargets,baseline,detection,finalPacks:updateFinalPacks,preserveExistingSubagentManifest:false,scanDirectory:rootDirectory}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const settingsChanges=isSome2(repoSettings)?yield*gen2(function*settingsChanges2(){if(isSome2(repoSettingsOnDisk)){const source=path25.join(rootDirectory,projectSettingsFile);const destination=path25.join(expectedDirectory,projectSettingsFile);mkdirSync8(path25.dirname(destination),{recursive:true});cpSync3(source,destination);yield*projectSettings.write(expectedDirectory,{_tag:"CalculatedToolsChange",requiredTools:calculatedRequiredTools});yield*projectSettings.write(expectedDirectory,{_tag:"ManagedVersionsChange",baselineVersion:baseline.summary.version,cliVersion:version2})}else{yield*projectSettings.initialize(expectedDirectory,{calculatedTools:{requiredTools:calculatedRequiredTools},managedVersions:{baselineVersion:baseline.summary.version,cliVersion:version2},userChoices:{assetProviderSlug:repoSettings.value.assetProviderSlug,backlogProvider:repoSettings.value.backlogProvider,...repoSettings.value.backlogProjectUrl===undefined?{}:{backlogProjectUrl:repoSettings.value.backlogProjectUrl},repositoryManager:repoSettings.value.repositoryManager}})}const expectedFile={kind:"harness",path:projectSettingsFile,sha256:hashPath(expectedDirectory,projectSettingsFile)??""};return buildChanges({expectedDirectory,expectedFiles:[expectedFile],previousFiles:[],rootDirectory})}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message}))):[];const materialize=(desiredState)=>writeScaffoldOutput({additionalPromptTargets:wikiPromptTargets,baseline,contextPlan:desiredState?.contextPlan??contextPlan,detection,displayOutputDirectory:rootDirectory,outputDirectory:expectedDirectory,preserveExistingManagedFiles:false,repoShapeMode,scanDirectory:rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2},...desiredState===undefined?{}:{desiredState,...isSome2(repoSettings)?{settings:desiredState.settings}:{}}}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})),map7((output2)=>{if(desiredState===undefined){return output2}const contextEvidence=new Set([".devpunks/context-plan.json",".devpunks/harness-projection-receipt.json"]);for(const relativePath of contextEvidence){rmSync6(path25.join(expectedDirectory,relativePath),{force:true})}const manifestPath=path25.join(expectedDirectory,scaffoldManifestFile);const stagedManifest=JSON.parse(readFileSync13(manifestPath,"utf-8"));stagedManifest.generatedFiles=(stagedManifest.generatedFiles??[]).filter((relativePath)=>!contextEvidence.has(relativePath));stagedManifest.managedFiles=(stagedManifest.managedFiles??[]).filter(({path:relativePath})=>!contextEvidence.has(relativePath));if(typeof stagedManifest.managedFileTypes==="object"&&stagedManifest.managedFileTypes!==null){stagedManifest.managedFileTypes=Object.fromEntries(Object.entries(stagedManifest.managedFileTypes).filter(([relativePath])=>!contextEvidence.has(relativePath)))}delete stagedManifest.contextPlanFile;delete stagedManifest.projectionReceiptFile;delete stagedManifest.projectionStatus;writeFileSync8(manifestPath,encodePrettyJson3(stagedManifest));return{...output2,contextPlanFile:null,generatedFiles:output2.generatedFiles.filter((relativePath)=>!contextEvidence.has(relativePath)),managedFiles:output2.managedFiles.filter(({path:relativePath})=>!contextEvidence.has(relativePath)),projectionReceiptFile:null,projectionStatus:null}}));const expected=yield*gen2(function*expected2(){const desiredSettings={...repoSettings.value,baselineVersion:baseline.summary.version,cliVersion:version2,requiredTools:settingsRequiredTools};const gather=()=>planScaffoldOutput({additionalPromptTargets:wikiPromptTargets,baseline,contextPlan,detection,displayOutputDirectory:rootDirectory,outputDirectory:rootDirectory,preserveExistingManagedFiles:false,repoShapeMode,scanDirectory:rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2},...isSome2(repoSettings)?{settings:desiredSettings}:{}}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})),map7((plan)=>({...plan,files:plan.files.filter(({kind})=>kind!=="projection-receipt")})),map7((plan)=>desiredScaffoldStateInput({...plan,settings:desiredSettings})));const observe=({desiredState})=>sync2(()=>{const semanticState=semanticDesiredState({desiredState,detection,finalPacks:updateFinalPacks,settings:desiredSettings,wikiFramework});return observeDesiredState({desiredState,manifest,rootDirectory,semanticState})});const compiler=scaffoldLifecycle.compileDesiredState===undefined?{}:{compile:scaffoldLifecycle.compileDesiredState};const planReconciliation=scaffoldLifecycle.planReconciliation??((input2)=>planScaffoldReconciliation(input2,nodeScaffoldContentHasher));const reconcile=({desiredState,observedState})=>{const semanticState=semanticDesiredState({desiredState,detection,finalPacks:updateFinalPacks,settings:desiredSettings,wikiFramework});const structuredEntries=[...desiredState.structuredEntries,...semanticState.structuredEntries].filter(({file:file5})=>file5!==repoSettingsDisplayFile);const entryOwnedPaths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...structuredEntries.map(({file:file5})=>file5)]);const belongsToLegacyFileLane=({kind,path:relativePath})=>kind==="context-plan"||kind==="projection-receipt"||kind==="agent-prompt"||kind==="handoff"||kind==="manifest"||kind==="prompt-spec"||kind==="required-tools"||kind==="subagent"||path25.posix.basename(relativePath)==="CLAUDE.md"||isWikiManagedPath(relativePath)||relativePath===projectAuthoredWikiSyncFile||relativePath===syncSubagentsScriptFile&&isTailoredSyncSubagentsScript(rootDirectory);const files=[...desiredState.files,...semanticState.files].filter((file5)=>!entryOwnedPaths.has(file5.path)&&!belongsToLegacyFileLane(file5));const stagedDesiredState={...desiredState,files,structuredEntries};const manifestReceipt=priorReceiptFromManifest(manifest,rootDirectory,stagedDesiredState.files);const applicationReceipt={...manifestReceipt,files:manifestReceipt.files.filter(({path:relativePath})=>!entryOwnedPaths.has(relativePath)),structuredEntries:manifestReceipt.structuredEntries.filter(({file:file5})=>file5!==repoSettingsDisplayFile)};const planningReceipt={...applicationReceipt,files:applicationReceipt.files.filter((file5)=>!belongsToLegacyFileLane(file5))};const plan=planReconciliation({desiredState:stagedDesiredState,observedState,priorReceipt:planningReceipt});const comparison=compareObservedState({desiredState,manifest,observedState,semanticState});return materialize(desiredState).pipe(map7((output2)=>({comparison,desiredState:stagedDesiredState,output:output2,plan,priorReceipt:applicationReceipt})))};if(operation2==="check"){const lifecycle2=yield*runCheckScaffoldLifecycle({...compiler,compare:reconcile,gather,observe});if(lifecycle2._tag==="ScaffoldLifecycleCompilationFailed"){return yield*fail6(new CliValidationError({message:lifecycle2.compilation.errors.map(({message})=>message).join(`
1533
+ `)};var usesClassicYarn=(rootDirectory,configuredManager,configuredVersion)=>{if(configuredManager==="yarn"&&configuredVersion!==null){return/^1(?:\.|$)/u.test(configuredVersion)}if(configuredManager!==null){return false}const yarnLockfile=path25.join(rootDirectory,"yarn.lock");return existsSync14(yarnLockfile)&&/(?:^|\n)# yarn lockfile v1(?:\n|$)/u.test(readFileSync13(yarnLockfile,"utf-8"))};var dependencyLockfileCommand=(rootDirectory)=>{const rootManifest=readJsonObject(path25.join(rootDirectory,"package.json"));const configuredValue=typeof rootManifest?.packageManager==="string"?rootManifest.packageManager:null;const configuredMatch=configuredValue===null?null:/^(?<manager>[^@]+)(?:@(?<version>.+))?$/u.exec(configuredValue);const configured=configuredMatch?.groups?.manager??null;const configuredVersion=configuredMatch?.groups?.version??null;const manager=configured??[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["package-lock.json","npm"],["yarn.lock","yarn"]].find(([lockfile])=>existsSync14(path25.join(rootDirectory,lockfile)))?.[1]??null;switch(manager){case"bun":{return["bun",["install","--lockfile-only"]]}case"npm":{return["npm",["install","--package-lock-only","--ignore-scripts"]]}case"pnpm":{return["pnpm",["install","--lockfile-only","--ignore-scripts"]]}case"yarn":{if(usesClassicYarn(rootDirectory,configured,configuredVersion)){return["yarn",["install","--ignore-scripts","--non-interactive"]]}return["yarn",["install","--mode=update-lockfile"]]}default:{return null}}};var defaultDependencyProcess=(command,args2,cwd)=>{const result4=spawnSync3(command,[...args2],{cwd,encoding:"utf-8",stdio:"pipe"});if(result4.error!==undefined||result4.status!==0){throw new Error(result4.error?.message||result4.stderr.trim()||`${command} exited ${result4.status??1}`)}};var dependencyLockfiles=["bun.lock","bun.lockb","package-lock.json","pnpm-lock.yaml","yarn.lock"];var snapshotDependencyLockfiles=(rootDirectory)=>new Map(dependencyLockfiles.map((lockfile)=>{const absolutePath=path25.join(rootDirectory,lockfile);return[absolutePath,existsSync14(absolutePath)?readFileSync13(absolutePath):null]}));var restoreDependencyLockfiles=(snapshot)=>{for(const[absolutePath,content]of snapshot){if(content===null){rmSync6(absolutePath,{force:true})}else{writeFileSync8(absolutePath,content)}}};var makeScaffoldReconciliationApplicators=({dependencyProcess,priorReceipt,rootDirectory})=>({applyDependency:(action2)=>try_3({catch:(cause)=>cause,try:()=>{const entry=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous:action2.desired;const absolutePath=resolveMutableJsonPath(rootDirectory,packageFileForWorkspace(entry.workspace));const document=readJsonObject(absolutePath);if(document===null){throw new Error(`Package manifest is not a JSON object: ${packageFileForWorkspace(entry.workspace)}`)}const sectionValue=document[entry.section];if(sectionValue!==undefined&&(typeof sectionValue!=="object"||sectionValue===null||Array.isArray(sectionValue))){throw new Error(`Package dependency section is not an object: ${entry.section}`)}const section2=sectionValue??{};const previousPackageManifest=readFileSync13(absolutePath);const lockfileSnapshot=snapshotDependencyLockfiles(rootDirectory);if(action2._tag==="SafeRemoveScaffoldEntry"){Reflect.deleteProperty(section2,entry.name)}else{section2[entry.name]=entry.version}document[entry.section]=section2;writeJsonDocument(absolutePath,document);const lockfileCommand=dependencyLockfileCommand(rootDirectory);if(lockfileCommand!==null){try{dependencyProcess(lockfileCommand[0],lockfileCommand[1],rootDirectory)}catch(error2){writeFileSync8(absolutePath,previousPackageManifest);restoreDependencyLockfiles(lockfileSnapshot);throw error2}}return action2._tag==="SafeRemoveScaffoldEntry"?null:{name:entry.name,section:entry.section,version:entry.version,workspace:entry.workspace}}}),applyFile:(action2)=>try_3({catch:(cause)=>cause,try:()=>{const relativePath=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path;const absolutePath=resolveContainedReceiptPath(rootDirectory,relativePath,{followLeaf:false});if(action2._tag==="SafeRemoveScaffoldEntry"){rmSync6(absolutePath,{force:true,recursive:true});return null}const{desired}=action2;mkdirSync8(path25.dirname(absolutePath),{recursive:true});if(desired.encoding==="symlink"){rmSync6(absolutePath,{force:true,recursive:true});symlinkSync3(desired.content,absolutePath)}else{if(pathLexists(absolutePath)&&lstatSync4(absolutePath).isSymbolicLink()){rmSync6(absolutePath,{force:true})}writeFileSync8(absolutePath,desired.encoding==="base64"?Buffer.from(desired.content,"base64"):desired.content);if(desired.mode!==undefined){chmodSync2(absolutePath,fileMode2(desired.mode))}}return receiptForFile({kind:desired.kind,relativePath,rootDirectory})}}),applyStructuredEntry:(action2)=>try_3({catch:(cause)=>cause,try:()=>{const entry=action2._tag==="SafeRemoveScaffoldEntry"?action2.previous:action2.desired;const absolutePath=resolveMutableJsonPath(rootDirectory,entry.file);const document=existsSync14(absolutePath)?readJsonObject(absolutePath):{};if(document===null){throw new Error(`Structured configuration is not a JSON object: ${entry.file}`)}if(entry.path.length===0){throw new Error(`Structured entry path is empty: ${entry.file}`)}let parent=document;for(const segment of entry.path.slice(0,-1)){const value5=parent[segment];if(value5===undefined){const child={};parent[segment]=child;parent=child}else if(typeof value5==="object"&&value5!==null&&!Array.isArray(value5)){parent=value5}else{throw new Error(`Structured configuration cannot traverse ${segment}: ${entry.file}`)}}const leaf=entry.path.at(-1)??"";const priorEntry=priorReceipt.structuredEntries.find((candidate)=>JSON.stringify([candidate.file,candidate.kind,candidate.path])===action2.identity);const appliedLifecycleHook=applyManagedLifecycleHook({action:action2,entryFile:entry.file,leaf,parent,...priorEntry===undefined?{}:{priorEntry}});if(!appliedLifecycleHook&&action2._tag==="SafeRemoveScaffoldEntry"){Reflect.deleteProperty(parent,leaf)}else if(!appliedLifecycleHook){parent[leaf]=entry.value}writeJsonDocument(absolutePath,document);return action2._tag==="SafeRemoveScaffoldEntry"?null:{file:entry.file,kind:entry.kind,path:entry.path,value:entry.value}}}),persistReceipt:(receipt)=>try_3({catch:(cause)=>cause,try:()=>{const manifestPath=path25.join(rootDirectory,scaffoldManifestFile);const manifest=readJsonObject(manifestPath);if(manifest===null){throw new Error(`Scaffold manifest is not a JSON object: ${scaffoldManifestFile}`)}manifest.managedFiles=receipt.files.map(({kind,path:relativePath,sha256})=>({kind,path:relativePath,sha256}));manifest.managedFileTypes=Object.fromEntries(receipt.files.map(({path:relativePath,type:type2})=>[relativePath,type2]));manifest.managedFileModes=Object.fromEntries(receipt.files.map(({mode,path:relativePath,type:type2})=>[relativePath,type2==="symlink"?null:mode]));manifest.managedDependencies=receipt.dependencies;manifest.managedStructuredEntries=receipt.structuredEntries;manifest.scaffoldDegradations=receipt.degradations;writeJsonDocument(manifestPath,manifest)}})});var reconciliationControlledPaths=({desiredState,plan,priorReceipt})=>{const entryPath=new Map;const recordEntryPath=(item,identity3,relativePath)=>{entryPath.set(`${item}\x00${identity3}`,relativePath)};for(const file5 of[...desiredState.files,...priorReceipt.files]){recordEntryPath("file",file5.path,file5.path)}for(const dependency of[...desiredState.dependencies,...priorReceipt.dependencies]){recordEntryPath("dependency",JSON.stringify([dependency.workspace,dependency.section,dependency.name]),packageFileForWorkspace(dependency.workspace))}for(const entry of[...desiredState.structuredEntries,...priorReceipt.structuredEntries]){recordEntryPath("structured-entry",JSON.stringify([entry.file,entry.kind,entry.path]),entry.file)}const paths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...desiredState.structuredEntries.map(({file:file5})=>file5)]);for(const action2 of plan.actions){if(action2.item==="file"){paths.add(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path)}else if(action2.item==="dependency"){paths.add(packageFileForWorkspace(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.workspace:action2.desired.workspace))}else{paths.add(action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.file:action2.desired.file)}}for(const conflict of plan.conflicts){const relativePath=entryPath.get(`${conflict.item}\x00${conflict.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}for(const skip of plan.skips){const relativePath=entryPath.get(`${skip.item}\x00${skip.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}for(const failure of plan.failures){if(failure._tag==="CrossFamilyScaffoldOwnershipFailure"){paths.add(failure.path);continue}if("item"in failure){const relativePath=entryPath.get(`${failure.item}\x00${failure.identity}`);if(relativePath!==undefined){paths.add(relativePath)}}}return paths};var removableStaleManagedFiles=({plan,reconciliationPaths,staleFiles})=>{const safeFileActionPaths=new Set(plan.actions.flatMap((action2)=>{if(action2.item!=="file"){return[]}return[action2._tag==="SafeRemoveScaffoldEntry"?action2.previous.path:action2.desired.path]}));return staleFiles.filter((relativePath)=>!reconciliationPaths.has(relativePath)||safeFileActionPaths.has(relativePath)).toSorted()};var reconciliationStatus=(outcomes)=>{const blocked=outcomes.some(({_tag})=>_tag==="ScaffoldActionBlocked"||_tag==="ScaffoldActionFailed"||_tag==="ScaffoldConflictPreserved"||_tag==="ScaffoldPlanningFailed");if(!blocked){return"succeeded"}return outcomes.some(({_tag})=>_tag==="ScaffoldActionSucceeded")?"partial":"failed"};var publicReconciliationOperation=(action2)=>{if(action2._tag==="SafeCreateScaffoldEntry"){return"create"}return action2._tag==="SafeUpdateScaffoldEntry"?"update":"remove"};var publicReconciliationActions=(plan)=>plan.actions.map((action2)=>({identity:action2.identity,item:action2.item,operation:publicReconciliationOperation(action2)}));var mergePrioritizedChanges=(target,changes)=>{const priority={changed:0,"local-edited":1,missing:2};for(const change of changes){const previous=target.get(change.path);if(previous===undefined||priority[change.status]>priority[previous.status]){target.set(change.path,change)}}};var observeStructuredValue=(document,entry)=>{let value5=document;for(const[index2,segment]of entry.path.entries()){if(typeof value5!=="object"||value5===null||Array.isArray(value5)){return{_tag:"InvalidStructuredObservation",message:`Structured configuration cannot traverse ${entry.path.slice(0,index2).join(".")}: ${entry.file}`}}if(!Object.hasOwn(value5,segment)){return{_tag:"MissingStructuredObservation"}}value5=value5[segment]}const expectedHook=managedLifecycleHook(entry);if(expectedHook!==undefined){if(!Array.isArray(value5)){return{_tag:"InvalidStructuredObservation",message:`Lifecycle hook configuration is not an array: ${entry.file}`}}const observedHook=value5.find((candidate)=>stableJsonStringify(candidate)===stableJsonStringify(expectedHook.value));return observedHook===undefined?{_tag:"MissingStructuredObservation"}:{_tag:"PresentStructuredObservation",value:[observedHook]}}return{_tag:"PresentStructuredObservation",value:value5}};var dependencyObservationIdentity=({name:name2,section:section2,workspace})=>JSON.stringify([workspace,section2,name2]);var structuredObservationIdentity=({file:file5,kind,path:entryPath})=>JSON.stringify([file5,kind,entryPath]);var observedEntryKey=(item,identity3)=>JSON.stringify([item,identity3]);var observeDesiredState=({desiredState,manifest,rootDirectory,semanticState})=>{const desiredFiles=new Map([...desiredState.files,...semanticState.files].map((file5)=>[file5.path,file5]));const files=new Map;for(const file5 of manifest.managedFiles??[]){files.set(file5.path,{kind:file5.kind})}for(const file5 of desiredFiles.values()){files.set(file5.path,{kind:file5.kind,...file5.mode===undefined?{}:{mode:file5.mode}})}const dependencyEntries=new Map([...desiredState.dependencies,...manifest.managedDependencies??[]].map((entry)=>[dependencyObservationIdentity(entry),entry]));const structuredEntries=new Map([...desiredState.structuredEntries,...semanticState.structuredEntries,...manifest.managedStructuredEntries??[]].map((entry)=>[structuredObservationIdentity(entry),entry]));const invalidEntries=new Map;for(const entry of structuredEntries.values()){const identity3=structuredObservationIdentity(entry);try{resolveMutableJsonPath(rootDirectory,entry.file);if(!files.has(entry.file)){files.set(entry.file,{kind:"harness"})}}catch(error2){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:error2 instanceof Error?error2.message:String(error2)})}}const dependencies=[...dependencyEntries.values()].flatMap((dependency)=>{const identity3=dependencyObservationIdentity(dependency);let manifestPath;try{manifestPath=resolveMutableJsonPath(rootDirectory,packageFileForWorkspace(dependency.workspace))}catch(error2){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:error2 instanceof Error?error2.message:String(error2)});return[]}if(!existsSync14(manifestPath)){return[]}const packageManifest=readJsonObject(manifestPath);if(packageManifest===null){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package manifest is not a JSON object: ${packageFileForWorkspace(dependency.workspace)}`});return[]}const section2=packageManifest[dependency.section];if(section2===undefined){return[]}if(typeof section2!=="object"||section2===null||Array.isArray(section2)){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package dependency section is not an object: ${dependency.section}`});return[]}const value5=section2[dependency.name];if(value5===undefined){return[]}if(typeof value5!=="string"){invalidEntries.set(observedEntryKey("dependency",identity3),{identity:identity3,item:"dependency",message:`Package dependency version is not a string: ${identity3}`});return[]}return[{name:dependency.name,section:dependency.section,version:value5,workspace:dependency.workspace}]});const observedStructuredEntries=[...structuredEntries.values()].flatMap((entry)=>{const identity3=structuredObservationIdentity(entry);let absolutePath;try{absolutePath=resolveMutableJsonPath(rootDirectory,entry.file)}catch(error2){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:error2 instanceof Error?error2.message:String(error2)});return[]}if(!existsSync14(absolutePath)){return[]}const document=readJsonObject(absolutePath);if(document===null){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:`Structured configuration is not a JSON object: ${entry.file}`});return[]}const observation=observeStructuredValue(document,entry);if(observation._tag==="InvalidStructuredObservation"){invalidEntries.set(observedEntryKey("structured-entry",identity3),{identity:identity3,item:"structured-entry",message:observation.message});return[]}return observation._tag==="MissingStructuredObservation"?[]:[{file:entry.file,kind:entry.kind,path:entry.path,value:observation.value}]});const observedFiles=[...files].flatMap(([relativePath,file5])=>{try{return[observeManagedFile({...file5.mode===undefined?{}:{expectedMode:file5.mode},kind:file5.kind,relativePath,rootDirectory})]}catch(error2){invalidEntries.set(observedEntryKey("file",relativePath),{identity:relativePath,item:"file",message:error2 instanceof Error?error2.message:String(error2)});return[]}});return{dependencies,files:observedFiles,invalidEntries:[...invalidEntries.values()].toSorted((left,right)=>left.identity.localeCompare(right.identity)),structuredEntries:observedStructuredEntries,version:"1"}};var priorReceiptFromManifest=(manifest,rootDirectory,desiredFiles)=>{const desiredModes=new Map(desiredFiles.map((file5)=>[file5.path,file5.mode]));return{dependencies:manifest.managedDependencies??[],files:(manifest.managedFiles??[]).filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).map((file5)=>{const type2=manifest.managedFileTypes?.[file5.path]==="symlink"?"symlink":"file";const recordedMode=manifest.managedFileModes?.[file5.path];const absolutePath=resolveContainedReceiptPath(rootDirectory,file5.path,{followLeaf:false});const currentMode=type2==="file"&&pathLexists(absolutePath)&&lstatSync4(absolutePath).isFile()?fileMode2(lstatSync4(absolutePath).mode):undefined;const desiredMode=desiredModes.get(file5.path);let inferredMode;if(recordedMode===undefined&&type2==="symlink"){inferredMode=null}else if(recordedMode===undefined&&currentMode!==undefined&&desiredMode!==undefined&&currentMode===desiredMode%512&&hashPath(rootDirectory,file5.path)===file5.sha256){inferredMode=currentMode}const mode=recordedMode===undefined?inferredMode:recordedMode;return{kind:file5.kind,...mode===undefined?{}:{mode},path:file5.path,sha256:file5.sha256,type:type2}}),structuredEntries:(manifest.managedStructuredEntries??[]).map((entry)=>({...entry,value:entry.value})),version:"1"}};var changeStatus=({path:relativePath,observedFiles,previousFiles})=>{const observed=observedFiles.get(relativePath);if(observed===undefined||observed.type==="missing"){return"missing"}const previous=previousFiles.find((file5)=>file5.path===relativePath);return previous!==undefined&&previous.sha256!==observed.sha256?"local-edited":"changed"};var compareObservedState=({desiredState,manifest,observedState,semanticState})=>{const previousFiles=manifest.managedFiles??[];const observedFiles=new Map(observedState.files.map((file5)=>[file5.path,file5]));const semanticPaths=new Set(semanticState.files.map((file5)=>file5.path));const changes=new Map;const addChange=(change)=>{const previous=changes.get(change.path);const priority={changed:0,"local-edited":1,missing:2};if(previous===undefined||priority[change.status]>priority[previous.status]){changes.set(change.path,change)}};const comparableFiles=new Map([...desiredState.files,...semanticState.files].map((file5)=>[file5.path,file5]));const compareFiles=()=>{for(const file5 of comparableFiles.values()){const observed=observedFiles.get(file5.path);if(file5.kind==="context-plan"||file5.kind==="projection-receipt"||observed?.projectAuthored===true&&!semanticPaths.has(file5.path)){continue}const fingerprintMatches=observed?.fingerprint===desiredFileFingerprint(file5);const jsonMatches=!fingerprintMatches&&file5.encoding!=="base64"&&file5.encoding!=="symlink"&&file5.mode===undefined&&file5.path.endsWith(".json")&&jsonContentEquals(observed?.content??"",file5.content);if(fingerprintMatches||jsonMatches){continue}addChange({kind:file5.kind,path:file5.path,status:changeStatus({observedFiles,path:file5.path,previousFiles})})}};compareFiles();const observedDependencies=new Map(observedState.dependencies.map((dependency)=>[`${dependency.workspace}:${dependency.section}:${dependency.name}`,dependency]));for(const dependency of desiredState.dependencies){const identity3=`${dependency.workspace}:${dependency.section}:${dependency.name}`;if(observedDependencies.get(identity3)?.version===dependency.version){continue}const packageFile=packageFileForWorkspace(dependency.workspace);addChange({kind:"manifest",path:packageFile,status:changeStatus({observedFiles,path:packageFile,previousFiles})})}const observedStructuredEntries=new Map(observedState.structuredEntries.map((entry)=>[JSON.stringify([entry.file,entry.kind,entry.path]),entry]));for(const entry of[...desiredState.structuredEntries,...semanticState.structuredEntries]){if(entry.file===repoSettingsDisplayFile&&observedFiles.get(entry.file)?.type==="missing"){continue}const identity3=JSON.stringify([entry.file,entry.kind,entry.path]);const observed=observedStructuredEntries.get(identity3);if(observed!==undefined&&stableJsonStringify(observed.value)===stableJsonStringify(entry.value)){continue}addChange({kind:"harness",path:entry.file,status:changeStatus({observedFiles,path:entry.file,previousFiles})})}const desiredPaths=new Set([...desiredState.files.map((file5)=>file5.path),...desiredState.dependencies.map((dependency)=>packageFileForWorkspace(dependency.workspace)),...desiredState.structuredEntries.map((entry)=>entry.file),...semanticState.files.map((file5)=>file5.path),...semanticState.structuredEntries.map((entry)=>entry.file)]);const staleFiles=previousFiles.filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).filter(({kind})=>kind!=="context-plan"&&kind!=="projection-receipt").filter((file5)=>observedFiles.get(file5.path)?.projectAuthored!==true).map((file5)=>file5.path).filter((file5)=>!desiredPaths.has(file5)).toSorted();return{changedFiles:[...changes.values()].toSorted((left,right)=>left.path.localeCompare(right.path)),staleFiles}};var resolveUpdateToolRuntime=({scriptEnvironment,toolRuntime})=>{if(toolRuntime!==undefined){return toolRuntime}if(scriptEnvironment===undefined){return}return makeToolCommandRuntime(Object.fromEntries(Object.entries(scriptEnvironment).filter((entry)=>entry[1]!==undefined)))};var runScaffoldOperation=({operation:operation2,rootDirectory,interaction,check:requestedCheck=false,write:requestedWrite=false,yes:requestedYes=false,emitJson:requestedEmitJson=false,ensureTools:requestedEnsureTools=true,baseline=bundledBaseline,allowBundledBaselineDriftApply=false,toolStdio:requestedToolStdio,toolRuntime,scaffoldLifecycle={},reconciliationApplicators,dependencyProcess=defaultDependencyProcess,configuration={disableBundledUrl:true},emitOutput=true,scriptEnvironment,scriptRuntimePath:scriptRuntimePath2})=>{const check3=operation2==="check"||requestedCheck;const write2=operation2==="update"&&requestedWrite;const yes=operation2==="update"&&requestedYes;const emitJson=operation2==="update"&&requestedEmitJson;const ensureTools2=operation2==="update"&&requestedEnsureTools;const toolStdio=requestedToolStdio??(emitJson?"ignore":"inherit");const resolvedToolRuntime=resolveUpdateToolRuntime({scriptEnvironment,toolRuntime});let updateStagingDirectory=null;let wikiStagingDirectory=null;return gen2(function*executeScaffoldOperation(){const projectSettings=yield*ProjectSettings;const writeHuman=noopHumanOutput;const manifest=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Failed to read scaffold manifest."}),try:()=>readManifest(rootDirectory)});yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid managed file receipt path."}),try:()=>{for(const file5 of manifest.managedFiles??[]){resolveContainedReceiptPath(rootDirectory,file5.path,{followLeaf:false})}}});const finalPacks=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid scaffold manifest."}),try:()=>normalizePacks(manifest.finalPacks,baseline)});const repoShapeMode=normalizeRepoShapeMode(manifest.repoShapeMode);const detection=applyRepoShapeMode(yield*detectRepository(rootDirectory),repoShapeMode);const resolved=resolvePackSelection(detection,baseline);const manifestBaseline=manifest.baseline;const baselineDrift=typeof manifestBaseline?.version==="string"&&manifestBaseline.version!==baseline.summary.version;const resolvedPacks=resolved.preselectedPacks;const packDrift=hasActionablePackDrift({finalPacks,resolvedPacks});const updateFinalPacks=write2||yes?acceptResolvedPacks({baseline,finalPacks,resolvedPacks}):finalPacks;const wikiRoot=wikiRootForDetection(detection);const wikiFramework=yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Invalid wiki framework pin."}),try:()=>readValidatedWikiFrameworkPin(path25.join(rootDirectory,wikiRoot))});const wikiPromptTarget=wikiPromptTargetFor({wikiFramework,wikiRoot});const wikiPromptTargets=updateFinalPacks.includes("docs")?[wikiPromptTarget]:[];const expectedDirectory=mkdtempSync3(path25.join(tmpdir6(),"punks-update-"));updateStagingDirectory=expectedDirectory;const repoSettingsOnDisk=yield*projectSettings.read(rootDirectory).pipe(map7(some2),catchTag2("ProjectSettingsMissing",()=>succeed6(none2())),mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const inferredRepoSettings=isNone2(repoSettingsOnDisk)?yield*projectSettings.infer(rootDirectory).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message}))):none2();const repoSettings=match(repoSettingsOnDisk,{onNone:()=>inferredRepoSettings,onSome:({settings})=>some2(settings)});if(isNone2(repoSettings)){return yield*fail6(new CliValidationError({message:`Project settings are missing at ${path25.join(rootDirectory,projectSettingsFile)}.`}))}const calculatedRequiredTools=requiredToolsForSkills2(selectedSkills3(updateFinalPacks,baseline),baseline);const settingsRequiredTools=deriveRequiredTools({repositoryManager:repoSettings.value.repositoryManager,requiredTools:calculatedRequiredTools});const contextPlan=yield*compileScaffoldContextPlan({additionalPromptTargets:wikiPromptTargets,baseline,detection,finalPacks:updateFinalPacks,preserveExistingSubagentManifest:false,scanDirectory:rootDirectory}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})));const settingsChanges=isSome2(repoSettings)?yield*gen2(function*settingsChanges(){if(isSome2(repoSettingsOnDisk)){const source=path25.join(rootDirectory,projectSettingsFile);const destination=path25.join(expectedDirectory,projectSettingsFile);mkdirSync8(path25.dirname(destination),{recursive:true});cpSync3(source,destination);yield*projectSettings.write(expectedDirectory,{_tag:"CalculatedToolsChange",requiredTools:calculatedRequiredTools});yield*projectSettings.write(expectedDirectory,{_tag:"ManagedVersionsChange",baselineVersion:baseline.summary.version,cliVersion:version2})}else{yield*projectSettings.initialize(expectedDirectory,{calculatedTools:{requiredTools:calculatedRequiredTools},managedVersions:{baselineVersion:baseline.summary.version,cliVersion:version2},userChoices:{assetProviderSlug:repoSettings.value.assetProviderSlug,backlogProvider:repoSettings.value.backlogProvider,...repoSettings.value.backlogProjectUrl===undefined?{}:{backlogProjectUrl:repoSettings.value.backlogProjectUrl},repositoryManager:repoSettings.value.repositoryManager}})}const expectedFile={kind:"harness",path:projectSettingsFile,sha256:hashPath(expectedDirectory,projectSettingsFile)??""};return buildChanges({expectedDirectory,expectedFiles:[expectedFile],previousFiles:[],rootDirectory})}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message}))):[];const materialize=(desiredState)=>writeScaffoldOutput({additionalPromptTargets:wikiPromptTargets,baseline,contextPlan:desiredState?.contextPlan??contextPlan,detection,displayOutputDirectory:rootDirectory,outputDirectory:expectedDirectory,preserveExistingManagedFiles:false,repoShapeMode,scanDirectory:rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2},...desiredState===undefined?{}:{desiredState,...isSome2(repoSettings)?{settings:desiredState.settings}:{}}}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})),map7((output2)=>{if(desiredState===undefined){return output2}const contextEvidence=new Set([".devpunks/context-plan.json",".devpunks/harness-projection-receipt.json"]);for(const relativePath of contextEvidence){rmSync6(path25.join(expectedDirectory,relativePath),{force:true})}const manifestPath=path25.join(expectedDirectory,scaffoldManifestFile);const stagedManifest=JSON.parse(readFileSync13(manifestPath,"utf-8"));stagedManifest.generatedFiles=(stagedManifest.generatedFiles??[]).filter((relativePath)=>!contextEvidence.has(relativePath));stagedManifest.managedFiles=(stagedManifest.managedFiles??[]).filter(({path:relativePath})=>!contextEvidence.has(relativePath));if(typeof stagedManifest.managedFileTypes==="object"&&stagedManifest.managedFileTypes!==null){stagedManifest.managedFileTypes=Object.fromEntries(Object.entries(stagedManifest.managedFileTypes).filter(([relativePath])=>!contextEvidence.has(relativePath)))}delete stagedManifest.contextPlanFile;delete stagedManifest.projectionReceiptFile;delete stagedManifest.projectionStatus;writeFileSync8(manifestPath,encodePrettyJson3(stagedManifest));return{...output2,contextPlanFile:null,generatedFiles:output2.generatedFiles.filter((relativePath)=>!contextEvidence.has(relativePath)),managedFiles:output2.managedFiles.filter(({path:relativePath})=>!contextEvidence.has(relativePath)),projectionReceiptFile:null,projectionStatus:null}}));const expected=yield*gen2(function*expected(){const desiredSettings={...repoSettings.value,baselineVersion:baseline.summary.version,cliVersion:version2,requiredTools:settingsRequiredTools};const gather=()=>planScaffoldOutput({additionalPromptTargets:wikiPromptTargets,baseline,contextPlan,detection,displayOutputDirectory:rootDirectory,outputDirectory:rootDirectory,preserveExistingManagedFiles:false,repoShapeMode,scanDirectory:rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2},...isSome2(repoSettings)?{settings:desiredSettings}:{}}).pipe(mapError3((cause)=>new CliValidationError({cause,message:cause.message})),map7((plan)=>({...plan,files:plan.files.filter(({kind})=>kind!=="projection-receipt")})),map7((plan)=>desiredScaffoldStateInput({...plan,settings:desiredSettings})));const observe=({desiredState})=>sync2(()=>{const semanticState=semanticDesiredState({desiredState,detection,finalPacks:updateFinalPacks,settings:desiredSettings,wikiFramework});return observeDesiredState({desiredState,manifest,rootDirectory,semanticState})});const compiler=scaffoldLifecycle.compileDesiredState===undefined?{}:{compile:scaffoldLifecycle.compileDesiredState};const planReconciliation=scaffoldLifecycle.planReconciliation??((input2)=>planScaffoldReconciliation(input2,nodeScaffoldContentHasher));const reconcile=({desiredState,observedState})=>{const semanticState=semanticDesiredState({desiredState,detection,finalPacks:updateFinalPacks,settings:desiredSettings,wikiFramework});const structuredEntries=[...desiredState.structuredEntries,...semanticState.structuredEntries].filter(({file:file5})=>file5!==repoSettingsDisplayFile);const entryOwnedPaths=new Set([...desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...structuredEntries.map(({file:file5})=>file5)]);const belongsToLegacyFileLane=({kind,path:relativePath})=>kind==="context-plan"||kind==="projection-receipt"||kind==="agent-prompt"||kind==="handoff"||kind==="manifest"||kind==="prompt-spec"||kind==="required-tools"||kind==="subagent"||path25.posix.basename(relativePath)==="CLAUDE.md"||isWikiManagedPath(relativePath)||relativePath===projectAuthoredWikiSyncFile||relativePath===syncSubagentsScriptFile&&isTailoredSyncSubagentsScript(rootDirectory);const files=[...desiredState.files,...semanticState.files].filter((file5)=>!entryOwnedPaths.has(file5.path)&&!belongsToLegacyFileLane(file5));const stagedDesiredState={...desiredState,files,structuredEntries};const manifestReceipt=priorReceiptFromManifest(manifest,rootDirectory,stagedDesiredState.files);const applicationReceipt={...manifestReceipt,files:manifestReceipt.files.filter(({path:relativePath})=>!entryOwnedPaths.has(relativePath)),structuredEntries:manifestReceipt.structuredEntries.filter(({file:file5})=>file5!==repoSettingsDisplayFile)};const planningReceipt={...applicationReceipt,files:applicationReceipt.files.filter((file5)=>!belongsToLegacyFileLane(file5))};const plan=planReconciliation({desiredState:stagedDesiredState,observedState,priorReceipt:planningReceipt});const comparison=compareObservedState({desiredState,manifest,observedState,semanticState});return materialize(desiredState).pipe(map7((output2)=>({comparison,desiredState:stagedDesiredState,output:output2,plan,priorReceipt:applicationReceipt})))};if(operation2==="check"){const lifecycle2=yield*runCheckScaffoldLifecycle({...compiler,compare:reconcile,gather,observe});if(lifecycle2._tag==="ScaffoldLifecycleCompilationFailed"){return yield*fail6(new CliValidationError({message:lifecycle2.compilation.errors.map(({message})=>message).join(`
1534
1534
  `)}))}return lifecycle2.comparison}const lifecycle=yield*runUpdateScaffoldLifecycle({...compiler,gather,observe,reconcile});if(lifecycle._tag==="ScaffoldLifecycleCompilationFailed"){return yield*fail6(new CliValidationError({message:lifecycle.compilation.errors.map(({message})=>message).join(`
1535
1535
  `)}))}return lifecycle.reconciliation});const observedComparison=expected.comparison;const expectedOutput=expected.output;const reconciliationPlan=expected.plan;const receiptEntryOwnedPaths=new Set([...expected.desiredState.dependencies.map(({workspace})=>packageFileForWorkspace(workspace)),...expected.desiredState.structuredEntries.map(({file:file5})=>file5)]);const reconciliationPaths=reconciliationControlledPaths({desiredState:expected.desiredState,plan:reconciliationPlan,priorReceipt:expected.priorReceipt});const previousFiles=manifest.managedFiles??[];const previousFilesByPath=new Map(previousFiles.map((file5)=>[file5.path,file5]));const stageLegacyClaudeSymlinks=()=>{const stagedLegacyClaudeSymlinkFiles2=previousFiles.filter((file5)=>{if(file5.kind!=="harness"||path25.posix.basename(file5.path)!=="CLAUDE.md"||existsSync14(path25.join(expectedDirectory,file5.path))||!existsSync14(path25.join(rootDirectory,file5.path))||!lstatSync4(path25.join(rootDirectory,file5.path)).isSymbolicLink()||hashPath(rootDirectory,file5.path)!==file5.sha256){return false}const canonicalSource=path25.join(rootDirectory,canonicalClaudePromptSource(file5.path));return existsSync14(canonicalSource)&&lstatSync4(canonicalSource).isFile()});for(const file5 of stagedLegacyClaudeSymlinkFiles2){copyManagedFile({fromDirectory:rootDirectory,relativePath:file5.path,toDirectory:expectedDirectory})}return stagedLegacyClaudeSymlinkFiles2};const stagedLegacyClaudeSymlinkFiles=stageLegacyClaudeSymlinks();const claudeCandidatePaths=new Set([...previousFiles.filter(({kind,path:relativePath})=>kind==="harness"&&path25.posix.basename(relativePath)==="CLAUDE.md").map(({path:relativePath})=>relativePath),...collectRelativeFiles2(expectedDirectory,".").filter((relativePath)=>path25.posix.basename(relativePath)==="CLAUDE.md")]);const managedClaudeCopyPaths=new Set([...claudeCandidatePaths].filter((relativePath)=>{const previousFile=previousFilesByPath.get(relativePath);return isManagedClaudePromptCopy({previousFile,recordedFileType:previousFile===undefined?undefined:manifest.managedFileTypes?.[relativePath],relativePath,rootDirectory})}));const stageManagedClaudeCopies=()=>{for(const relativePath of managedClaudeCopyPaths){const canonicalSourceRelativePath=canonicalClaudePromptSource(relativePath);const stagedCanonicalSource=path25.join(expectedDirectory,canonicalSourceRelativePath);const currentCanonicalSource=path25.join(rootDirectory,canonicalSourceRelativePath);const previousCanonicalSource=previousFilesByPath.get(canonicalSourceRelativePath);const canonicalSource=previousCanonicalSource!==undefined&&hashPath(rootDirectory,canonicalSourceRelativePath)===previousCanonicalSource.sha256?stagedCanonicalSource:currentCanonicalSource;if(existsSync14(canonicalSource)&&lstatSync4(canonicalSource).isFile()){const stagedTarget=path25.join(expectedDirectory,relativePath);mkdirSync8(path25.dirname(stagedTarget),{recursive:true});rmSync6(stagedTarget,{force:true,recursive:true});cpSync3(canonicalSource,stagedTarget)}else{copyManagedFile({fromDirectory:rootDirectory,relativePath,toDirectory:expectedDirectory})}}};stageManagedClaudeCopies();const managedClaudeCanonicalSourcePaths=new Set([...managedClaudeCopyPaths].map(canonicalClaudePromptSource).filter((relativePath)=>{const previousFile=previousFilesByPath.get(relativePath);return previousFile!==undefined&&hashPath(rootDirectory,relativePath)===previousFile.sha256&&expectedOutput.managedFiles.some(({path:expectedPath})=>expectedPath===relativePath)}));const preservedManagedClaudeCopyFiles=[...managedClaudeCopyPaths].filter((relativePath)=>!expectedOutput.managedFiles.some(({path:expectedPath})=>expectedPath===relativePath)).flatMap((relativePath)=>{const previousFile=previousFilesByPath.get(relativePath);return previousFile===undefined?[]:[{...previousFile,sha256:hashPath(expectedDirectory,relativePath)??""}]});const consumerOwnedClaudePaths=new Set([...claudeCandidatePaths].filter((relativePath)=>{if(managedClaudeCopyPaths.has(relativePath)){return false}const previousFile=previousFilesByPath.get(relativePath);return isConsumerOwnedClaudePrompt({previousFile,recordedFileType:previousFile===undefined?undefined:manifest.managedFileTypes?.[relativePath],relativePath,rootDirectory})}));const recordedContextEvidence=previousFiles.filter(({kind})=>kind==="context-plan"||kind==="projection-receipt");yield*try_3({catch:(cause)=>new CliValidationError({cause,message:cause instanceof Error?cause.message:"Recorded context evidence drifted."}),try:()=>{for(const file5 of recordedContextEvidence){if(hashPath(rootDirectory,file5.path)!==file5.sha256){throw new Error(`Recorded context evidence drifted: ${file5.path}`)}}}});const prepareManagedState=()=>{const preservedContextEvidence=previousFiles.filter(({kind})=>kind==="context-plan"||kind==="projection-receipt").map((file5)=>{copyManagedFile({fromDirectory:rootDirectory,relativePath:file5.path,toDirectory:expectedDirectory});return file5});const expectedManagedFiles2=[...expectedOutput.managedFiles.filter(({path:relativePath})=>!receiptEntryOwnedPaths.has(relativePath)).filter(({path:relativePath})=>!consumerOwnedClaudePaths.has(relativePath)&&!preservedContextEvidence.some(({path:preservedPath})=>preservedPath===relativePath)).filter((file5)=>!isProjectAuthoredManagedFile({file:file5,rootDirectory})||pathLexists(path25.join(rootDirectory,file5.path))).map((file5)=>managedClaudeCopyPaths.has(file5.path)?{...file5,sha256:hashPath(expectedDirectory,file5.path)??""}:file5),...stagedLegacyClaudeSymlinkFiles,...preservedManagedClaudeCopyFiles,...preservedContextEvidence].filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).toSorted((left,right)=>left.path.localeCompare(right.path));const expectedManifestPath=path25.join(expectedDirectory,scaffoldManifestFile);const expectedManifest=JSON.parse(readFileSync13(expectedManifestPath,"utf-8"));if(preservedContextEvidence.length>0){expectedManifest.generatedFiles=[...new Set([...expectedManifest.generatedFiles??[],...preservedContextEvidence.map(({path:relativePath})=>relativePath)])].toSorted();if(preservedContextEvidence.some(({kind})=>kind==="context-plan")){expectedManifest.contextPlanFile=".devpunks/context-plan.json"}if(preservedContextEvidence.some(({kind})=>kind==="projection-receipt")){const projectionReceiptFile=".devpunks/harness-projection-receipt.json";const projectionReceipt=JSON.parse(readFileSync13(path25.join(expectedDirectory,projectionReceiptFile),"utf-8"));expectedManifest.projectionReceiptFile=projectionReceiptFile;if(typeof projectionReceipt.status==="string"){expectedManifest.projectionStatus=projectionReceipt.status}}}const expectedManagedPaths=new Set(expectedManagedFiles2.map(({path:relativePath})=>relativePath));const expectedManagedFileTypes2=Object.fromEntries([...expectedManagedPaths].map((relativePath)=>[relativePath,lstatSync4(path25.join(expectedDirectory,relativePath)).isSymbolicLink()?"symlink":"file"]));expectedManifest.managedFiles=manifest.managedFiles??[];expectedManifest.managedFileTypes=manifest.managedFileTypes??{};expectedManifest.managedFileModes=manifest.managedFileModes??{};expectedManifest.managedDependencies=manifest.managedDependencies??[];expectedManifest.managedStructuredEntries=manifest.managedStructuredEntries??[];writeFileSync8(expectedManifestPath,encodePrettyJson3(expectedManifest));const reconciliationFilePaths=new Set(expected.desiredState.files.map(({path:relativePath})=>relativePath));const applicationPriorReceipt2={...expected.priorReceipt,files:[...expected.priorReceipt.files.filter(({path:relativePath})=>reconciliationFilePaths.has(relativePath)),...expectedManagedFiles2.filter(({path:relativePath})=>!reconciliationFilePaths.has(relativePath)).map((file5)=>{const absolutePath=path25.join(expectedDirectory,file5.path);const type2=lstatSync4(absolutePath).isSymbolicLink()?"symlink":"file";return{...file5,mode:type2==="symlink"?null:fileMode2(lstatSync4(absolutePath).mode),type:type2}})].toSorted((left,right)=>left.path.localeCompare(right.path))};const stagedChanges2=buildChanges({expectedDirectory,expectedFiles:expectedManagedFiles2.filter((file5)=>file5.kind!=="context-plan"&&file5.kind!=="projection-receipt"&&(managedClaudeCopyPaths.has(file5.path)||managedClaudeCanonicalSourcePaths.has(file5.path)||!isProjectAuthoredManagedFile({file:file5,rootDirectory}))),previousFiles,rootDirectory});return{applicationPriorReceipt:applicationPriorReceipt2,expectedManagedFileTypes:expectedManagedFileTypes2,expectedManagedFiles:expectedManagedFiles2,stagedChanges:stagedChanges2}};const{applicationPriorReceipt,expectedManagedFiles,expectedManagedFileTypes,stagedChanges}=prepareManagedState();const compileManagedChanges=()=>{const changesByPath=new Map;const applicableObservedChanges=observedComparison.changedFiles.filter(({path:relativePath})=>pathLexists(path25.join(expectedDirectory,relativePath)));mergePrioritizedChanges(changesByPath,[...stagedChanges,...applicableObservedChanges]);const changes2=[...changesByPath.values()].toSorted((left,right)=>left.path.localeCompare(right.path));const legacyRequiredToolsPromptChanges2=buildLegacyRequiredToolsPromptChanges({rootDirectory});const gitignoreChanges2=buildGitignoreCleanup({expectedDirectory,rootDirectory});const compileWikiAlignment=()=>{const shouldAlignWiki=updateFinalPacks.includes("docs")||expectedOutput.managedFiles.some((file5)=>isWikiManagedPath(file5.path));if(shouldAlignWiki){const wikiExpectedDirectory=mkdtempSync3(path25.join(tmpdir6(),"punks-wiki-update-"));wikiStagingDirectory=wikiExpectedDirectory;return buildWikiAlignment({detection,expectedDirectory:wikiExpectedDirectory,rootDirectory,...scriptEnvironment===undefined?{}:{scriptEnvironment},...scriptRuntimePath2===undefined?{}:{scriptRuntimePath:scriptRuntimePath2}})}return null};const wikiAlignment2=compileWikiAlignment();const allChangesByPath=new Map;mergePrioritizedChanges(allChangesByPath,[...changes2,...legacyRequiredToolsPromptChanges2,...gitignoreChanges2,...wikiAlignment2?.changes??[],...settingsChanges]);const allChanges2=[...allChangesByPath.values()].toSorted((left,right)=>left.path.localeCompare(right.path));const expectedPaths=new Set([...expectedManagedFiles.map((file5)=>file5.path),...wikiAlignment2?.expectedFiles.map((file5)=>file5.path)??[]]);const structuredConfigurationFiles=new Set([".claude/settings.json",".cursor/hooks.json",repoSettingsDisplayFile]);const staleFiles2=removableStaleManagedFiles({plan:reconciliationPlan,reconciliationPaths,staleFiles:[...new Set(previousFiles.filter(({path:relativePath})=>relativePath!==scaffoldManifestFile).filter((file5)=>!isProjectAuthoredManagedFile({file:file5,rootDirectory})).filter((file5)=>!consumerOwnedClaudePaths.has(file5.path)).map((file5)=>file5.path).filter((file5)=>!hasIgnoredWikiAlignmentPath(file5)).filter((file5)=>!structuredConfigurationFiles.has(file5)).filter((file5)=>!expectedPaths.has(file5)))]});const ownershipMetadata=(files,fileTypes)=>{const ownedFiles=files.filter(({path:relativePath})=>relativePath!==scaffoldManifestFile&&!reconciliationPaths.has(relativePath));const ownedPaths=new Set(ownedFiles.map(({path:relativePath})=>relativePath));return JSON.stringify({fileTypes:Object.fromEntries(Object.entries(fileTypes).filter(([relativePath])=>ownedPaths.has(relativePath)).toSorted(([left],[right])=>left.localeCompare(right))),files:ownedFiles.map(({path:relativePath,kind})=>Object.fromEntries([["path",relativePath],["kind",kind]])).toSorted((left,right)=>left.path.localeCompare(right.path))})};const hasOwnershipMetadataUpdate2=previousFiles.some(({path:relativePath})=>relativePath===scaffoldManifestFile)||manifest.managedFileTypes?.[scaffoldManifestFile]!==undefined||ownershipMetadata(previousFiles,manifest.managedFileTypes??{})!==ownershipMetadata(expectedManagedFiles,expectedManagedFileTypes);const hasManagedUpdates2=allChanges2.length>0||staleFiles2.length>0||hasOwnershipMetadataUpdate2||reconciliationPlan.actions.length>0||reconciliationPlan.conflicts.length>0||reconciliationPlan.failures.length>0;const needsAttention2=hasManagedUpdates2||packDrift||baselineDrift;const driftPrompt2=packDrift?packDriftPrompt({finalPacks,resolvedPacks,rootDirectory}):null;return{allChanges:allChanges2,changes:changes2,driftPrompt:driftPrompt2,gitignoreChanges:gitignoreChanges2,hasManagedUpdates:hasManagedUpdates2,hasOwnershipMetadataUpdate:hasOwnershipMetadataUpdate2,legacyRequiredToolsPromptChanges:legacyRequiredToolsPromptChanges2,needsAttention:needsAttention2,staleFiles:staleFiles2,wikiAlignment:wikiAlignment2}};const{allChanges,changes,driftPrompt,gitignoreChanges,hasManagedUpdates,hasOwnershipMetadataUpdate,legacyRequiredToolsPromptChanges,needsAttention,staleFiles,wikiAlignment}=compileManagedChanges();const decideApplication=()=>gen2(function*decideScaffoldApplication(){const presentUpdatePlan=()=>gen2(function*presentScaffoldUpdatePlan(){if(emitOutput&&!emitJson){yield*interaction.emit({_tag:"Detection",detection});yield*interaction.emit({_tag:"RecordedPacks",packs:finalPacks});yield*interaction.emit({_tag:"Baseline",active:baseline.summary,drift:baselineDrift,recordedVersion:typeof manifestBaseline?.version==="string"?manifestBaseline.version:null});if(packDrift){yield*interaction.emit({_tag:"PackDrift",baseline,prompt:driftPrompt??"",resolved})}yield*interaction.emit({_tag:"ManagedChanges",changes:allChanges});if(staleFiles.length>0){yield*interaction.emit({_tag:"StaleFiles",files:staleFiles})}}yield*writeHuman(renderCommandSection("Update Detection",formatDetectionSummary(detection)));yield*writeHuman("");yield*writeHuman(renderCommandSection("Recorded Packs",finalPacks.length===0?"∅":finalPacks.map((pack)=>`• ${pack}`).join(`
1536
1536
  `)));yield*writeHuman("");yield*writeHuman(renderCommandSection("Baseline",[`active: ${baseline.summary.source}/${baseline.summary.channel} ${baseline.summary.version}`,`recorded: ${typeof manifestBaseline?.version==="string"?manifestBaseline.version:"unknown"}`,`drift: ${baselineDrift?"yes":"no"}`].join(`
@@ -1538,12 +1538,12 @@ Keep this framework pinned unless the user explicitly changes it. \`punks update
1538
1538
  `)))}yield*writeHuman("");yield*writeHuman(renderCommandSection("Managed Changes",summarizeChanges2(allChanges)));if(staleFiles.length>0){yield*writeHuman("");yield*writeHuman(renderCommandSection("Stale Managed Files",summarizeStaleFiles2(staleFiles)))}});yield*presentUpdatePlan();let applyRequested2=false;if(write2||yes){applyRequested2=true}else if(!check3&&!emitJson&&hasManagedUpdates){applyRequested2=yield*interaction.confirmApply()}const unsafeBundledBaselineDrift=applyRequested2&&baselineDrift&&baseline.summary.source==="bundled"&&!allowBundledBaselineDriftApply;if(unsafeBundledBaselineDrift){return yield*fail6(new CliValidationError({message:["Refusing to apply bundled scaffold assets because the recorded scaffold baseline differs from the active bundled baseline.",`Recorded baseline: ${typeof manifestBaseline?.version==="string"?manifestBaseline.version:"unknown"}.`,`Active baseline: ${baseline.summary.source}/${baseline.summary.channel} ${baseline.summary.version}.`,"Run `hi update --baseline stable --refresh-baseline` when online, upgrade the global `hi`/`hint` CLI if it cannot resolve stable, or pass `--baseline bundled` only when you intentionally want the bundled baseline."].join(`
1539
1539
  `)}))}return applyRequested2});const applyRequested=yield*decideApplication();const shouldApply=applyRequested&&(hasManagedUpdates||baselineDrift);const bootstrapRequiredTools=()=>gen2(function*bootstrapScaffoldTools(){if(!applyRequested||!ensureTools2||settingsRequiredTools.length===0){return[]}const requiredTools=settingsRequiredTools;if(emitOutput&&!emitJson){yield*interaction.emit({_tag:"EnsuringTools",toolIds:requiredTools})}yield*writeHuman("");yield*writeHuman(renderHint(`Ensuring required tools: ${requiredTools.join(", ")}`));const statuses=ensureToolsInstalledBestEffort(requiredTools,baseline,resolvedToolRuntime,{stdio:toolStdio});yield*writeHuman(renderCommandSection("Tool bootstrap",statuses.map((entry)=>`• ${entry.toolId}: ${formatToolBootstrapStatus(entry)}`).join(`
1540
1540
  `)));const failureDetails=formatToolBootstrapFailureDetails(statuses);if(emitOutput&&!emitJson){yield*interaction.emit({_tag:"ToolBootstrap",statuses});if(failureDetails!==null){yield*interaction.emit({_tag:"ToolBootstrapWarning",statuses})}}if(failureDetails!==null){yield*writeHuman("");yield*writeHuman(renderCommandSection("Tool Bootstrap Warning",failureDetails))}return statuses});const plannedReconciliation={outcomes:scaffoldReconciliationPlanOutcomes(reconciliationPlan),plannedActions:publicReconciliationActions(reconciliationPlan),receipt:null,receiptPersisted:false,status:"planned"};const toolBootstrapStatuses=yield*bootstrapRequiredTools();const applyManagedChanges=()=>gen2(function*applyScaffoldChanges(){if(!shouldApply){return plannedReconciliation}snapshotPreExistingSkillHomes(rootDirectory);for(const change of changes.filter(({path:relativePath})=>!reconciliationPaths.has(relativePath))){copyManagedFile({fromDirectory:expectedDirectory,relativePath:change.path,toDirectory:rootDirectory})}for(const change of gitignoreChanges){copyManagedFile({fromDirectory:expectedDirectory,relativePath:change.path,toDirectory:rootDirectory})}for(const change of legacyRequiredToolsPromptChanges){rewriteLegacyRequiredToolsPrompt({relativePath:change.path,rootDirectory})}if(wikiAlignment!==null){for(const change of wikiAlignment.changes){copyManagedFile({fromDirectory:wikiAlignment.expectedDirectory,relativePath:change.path,toDirectory:rootDirectory})}}for(const change of settingsChanges.filter(({path:relativePath})=>!reconciliationPaths.has(relativePath))){copyManagedFile({fromDirectory:expectedDirectory,relativePath:change.path,toDirectory:rootDirectory})}for(const staleFile of staleFiles){rmSync6(resolveContainedReceiptPath(rootDirectory,staleFile,{followLeaf:false}),{force:true,recursive:true})}copyManagedFile({fromDirectory:expectedDirectory,relativePath:scaffoldManifestFile,toDirectory:rootDirectory});removeHarnessDirectoriesFromGitignore(rootDirectory);const application=yield*applyScaffoldReconciliation({adapters:(()=>{const defaults2=makeScaffoldReconciliationApplicators({dependencyProcess,priorReceipt:applicationPriorReceipt,rootDirectory});return reconciliationApplicators?.(defaults2)??defaults2})(),plan:reconciliationPlan,priorReceipt:applicationPriorReceipt}).pipe(catchTag2("@punks/cli/scaffold-state/ScaffoldApplicationFailures",({partialResult})=>succeed6(partialResult)));return{...application,plannedActions:publicReconciliationActions(reconciliationPlan),status:reconciliationStatus(application.outcomes)}});const reconciliation=yield*applyManagedChanges();const finalizeUpdateResult=()=>{const buildFinalResult=()=>{const toolBootstrapFailed=toolBootstrapStatuses.some((entry)=>entry.status==="failed");const operationIssues=[...toolBootstrapStatuses.filter((entry)=>entry.status==="failed").map((entry)=>({action:"bootstrap",code:entry.toolId,errorMessage:entry.errorMessage,kind:"handled-failure",subject:entry.toolId})),...reconciliation?.status==="failed"?[{action:"reconcile",code:"reconciliation-failed",kind:"handled-failure",subject:"managed-scaffold"}]:[]];const unresolvedBaselineDrift=baselineDrift&&(!shouldApply||reconciliation.status!=="succeeded");const unresolvedPackDrift=packDrift&&(!shouldApply||reconciliation.status!=="succeeded");const operationDegradations=[...check3&&hasManagedUpdates?[{code:"managed-drift",subject:"managed-scaffold"}]:[],...unresolvedPackDrift?[{code:"pack-drift",subject:"packs"}]:[],...unresolvedBaselineDrift?[{code:"baseline-drift",subject:"baseline"}]:[],...reconciliation?.status==="partial"?[{code:"reconciliation-partial",subject:"managed-scaffold"}]:[],...reconciliation.outcomes.filter((outcome)=>outcome._tag==="ScaffoldConflictPreserved").map((outcome)=>({code:"scaffold-conflict-preserved",subject:outcome.identity}))];const operationChanges=[...allChanges.filter((change)=>!reconciliationPaths.has(change.path)).map((change)=>({action:change.status,state:shouldApply?"completed":"planned",subject:change.path})),...staleFiles.filter((subject)=>!reconciliationPaths.has(subject)).map((subject)=>({action:"remove",state:shouldApply?"completed":"planned",subject})),...publicReconciliationActions(reconciliationPlan).map((action2)=>({action:action2.operation,state:shouldApply&&reconciliation.outcomes.some((outcome)=>outcome._tag==="ScaffoldActionSucceeded"&&outcome.identity===action2.identity&&outcome.item===action2.item&&outcome.operation===action2.operation)?"completed":"planned",subject:action2.identity})),...ownershipMetadataOperationChanges({allChanges,applied:shouldApply,required:hasOwnershipMetadataUpdate})];const operationStatus=(()=>{if(operationIssues.length>0){return operationChanges.some(({state})=>state==="completed")?"partial":"failed"}if(operationDegradations.length>0){return"degraded"}if(shouldApply){return"success"}return hasManagedUpdates?"planned":"no-op"})();const operationResult={changes:operationChanges,degradations:operationDegradations,issues:operationIssues,nextActions:operationStatus==="no-op"||operationStatus==="success"?[{kind:"none"}]:[...toolBootstrapFailed?[{kind:"run",subject:"hi tools ensure"}]:[],...operationDegradations.length>0||operationIssues.some((issue)=>issue.action!=="bootstrap")?[{kind:"review",subject:"managed-scaffold"}]:[]],status:operationStatus,warnings:baselineDrift?[{code:"baseline-drift",subject:"baseline"}]:[]};const result4={applied:shouldApply,baselineDrift,changedFiles:allChanges,checkFailed:check3&&needsAttention,driftPrompt,finalPacks:updateFinalPacks,operation:operationResult,packDrift,reconciliation,repoShapeMode,resolvedPacks,rootDirectory,scaffoldManifestFile,staleFiles,toolBootstrapStatuses};return result4};return gen2(function*finalizeScaffoldUpdate(){const result4=buildFinalResult();yield*writeHuman("");yield*writeHuman(renderCommandSection("Update Complete",[updateCompleteMessage({applyRequested,hasManagedUpdates}),`Changed files: ${allChanges.length}`,`Stale files: ${staleFiles.length}`,`Manifests scanned: ${manifestPaths(detection).join(", ")||"∅"}`,"Guidance: keep phase skills out of scoped `AGENTS.md` primary-skill lines; invoke them from the parent goal/handoff flow.","Guidance: update does not detect overlapping skills; follow-up agent owns skill reconciliation.","Skill homes: `.agents/skills`, `.claude/skills`, `.codex/skills`, `.cursor/skills`, `.opencode/skills`.","Exact name/id overlap: keep HI baseline active, remove active local copies or mirrors, archive evidence.","Archive target: `.devpunks/replaced-skills/<skill-id>/...`; inspect `.devpunks/pre-existing-skills` when present.","Non-overlaps stay mirrored; semantic overlap or baseline integration goes to `hi report`."].join(`
1541
- `)));if(emitOutput&&emitJson){yield*interaction.emit({_tag:"Json",result:result4})}else if(emitOutput){yield*interaction.emit({_tag:"Complete",applyRequested,changedFiles:allChanges.length,hasManagedUpdates,manifestPaths:manifestPaths(detection),staleFiles:staleFiles.length})}if(result4.applied){yield*submitCliEventEffect("cli.scaffold.update.applied",{baseline:{version:baseline.summary.version},configuration,cwd:rootDirectory})}return result4})};return yield*finalizeUpdateResult()}).pipe(ensuring2(sync2(()=>{if(updateStagingDirectory!==null){rmSync6(updateStagingDirectory,{force:true,recursive:true})}if(wikiStagingDirectory!==null){rmSync6(wikiStagingDirectory,{force:true,recursive:true})}})))};var runUpdate=(options4)=>runScaffoldOperation({...options4,operation:"update"});var failureMessage=(cause)=>cause instanceof Error?cause.message:String(cause);var silentUpdateInteraction={confirmApply:()=>succeed6(false),emit:()=>void_3};var nonBlankEnvironmentValue=(value5)=>value5!==undefined&&value5.trim().length>0?value5:undefined;var operatorSkillOperationsLayer=effect(OperatorSkillOperations,gen2(function*makeOperatorSkillOperations(){const runtime=yield*CliRuntimeConfig;const skillsCli=yield*SkillsCli;return{run:(action2,selectAgent)=>gen2(function*runOperatorSkillOperation(){const cwd=process.cwd();const detectedAgent=resolveActiveOperatorAgent(runtime.commandEnvironment);let selectedAgent;if(detectedAgent===undefined){if(selectAgent===undefined){return yield*new InvalidOperatorContext({message:"Cannot determine the active agent. Set HI_OPERATOR_AGENT to the Skills CLI agent name."})}selectedAgent=yield*selectAgent}const activeAgent=resolveActiveOperatorAgent(runtime.commandEnvironment,selectedAgent);if(activeAgent===undefined){return yield*new InvalidOperatorContext({message:"Cannot determine the active agent. Set HI_OPERATOR_AGENT to the Skills CLI agent name."})}const migrationRetryToken=nonBlankEnvironmentValue(runtime.commandEnvironment.HI_OPERATOR_MIGRATION_RETRY);const mutationRetryToken=nonBlankEnvironmentValue(runtime.commandEnvironment.HI_OPERATOR_MUTATION_RETRY);return yield*executeOperatorAction({action:action2,input:{activeAgent,activeCliVersion:version2,cwd,projectRoot:findOperatorProjectRoot(cwd)},...migrationRetryToken===undefined?{}:{migrationRetryToken},...mutationRetryToken===undefined?{}:{mutationRetryToken}})}).pipe(provideService2(SkillsCli,skillsCli))}}));var resolveFeatureBaseline=({baseline,refreshBaseline,rootDirectory,controlPlane,release,runtime,httpClient})=>resolveBaseline(baselineResolveOptions(fromNullishOr(baseline),refreshBaseline,rootDirectory,{controlPlane,release,runtime})).pipe(provideService2(HttpClient,httpClient));var reportSubmissionOperationsLayer=effect(ReportSubmissionOperations,gen2(function*makeReportSubmissionOperations(){const controlPlane=yield*CliControlPlaneConfig;const httpClient=yield*HttpClient;return{cliVersion:version2,observeRepository:observedRepository,recordSubmitted:(rootDirectory)=>submitCliEventEffect("cli.harness.report.submitted",{configuration:controlPlane,cwd:rootDirectory}).pipe(provideService2(HttpClient,httpClient),mapError3((cause)=>new ReportSubmissionOperationFailure({cause,message:failureMessage(cause),operation:"record-submitted"}))),resolveControlPlaneUrl:()=>succeed6(resolveControlPlaneUrl(undefined,controlPlane)),submit:(baseUrl2,report)=>submitHarnessReport({baseUrl:baseUrl2,report}).pipe(provideService2(HttpClient,httpClient),mapError3((cause)=>new ReportSubmissionOperationFailure({cause,message:failureMessage(cause),operation:"submit-report"})))}}));var repositoryCheckOperationsLayer=effect(RepositoryCheckOperations,gen2(function*makeRepositoryCheckOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const projectSettings=yield*ProjectSettings;return{...release.baseline===undefined?{}:{configuredBaseline:release.baseline},checkUpdate:(input2)=>gen2(function*checkUpdate(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.rootDirectory,runtime});const update3=yield*runUpdate({baseline,check:true,configuration:controlPlane,emitJson:false,emitOutput:false,interaction:silentUpdateInteraction,rootDirectory:input2.rootDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,write:false,yes:false}).pipe(provideService2(HttpClient,httpClient));const{operation:_operation,reconciliation:_reconciliation,...publicUpdate}=update3;return{baselineVersion:baseline.summary.version,update:publicUpdate}}).pipe(provideService2(ProjectSettings,projectSettings),mapError3((cause)=>new RepositoryCheckOperationFailure({cause,message:failureMessage(cause),operation:"check-repository-update"}))),cliVersion:version2,updateTag:release.updateTag}}));var repositoryScaffoldingResult=(result4)=>({machinePayload:{...result4,toolBootstrapStatuses:(result4.toolBootstrapStatuses??[]).map((tool)=>({...tool.status==="failed"?{errorMessage:`Required tool '${tool.toolId}' is unavailable after bootstrap.`}:{},status:tool.status,toolId:tool.toolId}))},outputDirectory:result4.outputDirectory,projectionStatus:result4.projectionStatus,toolBootstrapStatuses:(result4.toolBootstrapStatuses??[]).map((tool)=>({...tool.status==="failed"?{errorMessage:`Required tool '${tool.toolId}' is unavailable after bootstrap.`}:{},status:tool.status,toolId:tool.toolId}))});var repositoryScaffoldingOperationsLayer=effect(RepositoryScaffoldingOperations,gen2(function*makeRepositoryScaffoldingOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const projectSettings=yield*ProjectSettings;const scaffoldCapabilities=yield*ScaffoldCapabilities;return{run:(input2,interaction)=>gen2(function*run6(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.kind==="init"?input2.outputDirectory:input2.scanDirectory,runtime});if(input2.kind==="init"){const result5=yield*runStageScaffold({baseline,commandId:"init",configuration:controlPlane,interaction,outputDirectory:input2.outputDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath}).pipe(provideService2(HttpClient,httpClient),provideService2(ProjectSettings,projectSettings));return repositoryScaffoldingResult(result5)}const result4=yield*runScaffold({assumeYes:input2.assumeYes,baseline,configuration:controlPlane,emitJson:input2.emitJson,interaction,...input2.outputDirectory===undefined?{}:{outputDirectory:input2.outputDirectory},repoShapeMode:input2.repoShape,scanDirectory:input2.scanDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,toolStdio:input2.toolStdio}).pipe(provideService2(HttpClient,httpClient),provideService2(ProjectSettings,projectSettings),provideService2(ScaffoldCapabilities,scaffoldCapabilities));return repositoryScaffoldingResult(result4)}).pipe(mapError3((cause)=>new RepositoryScaffoldingOperationFailure({cause,message:failureMessage(cause),operation:input2.kind==="init"?"initialize-repository":"setup-repository"})))}}));var scaffoldUpdateOperationsLayer=effect(ScaffoldUpdateOperations,gen2(function*makeScaffoldUpdateOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const projectSettings=yield*ProjectSettings;return{run:(input2,interaction)=>gen2(function*run6(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.rootDirectory,runtime});return yield*runUpdate({allowBundledBaselineDriftApply:input2.baseline==="bundled"||release.baseline==="bundled",baseline,check:input2.check,configuration:controlPlane,emitJson:input2.emitJson,emitOutput:false,interaction,rootDirectory:input2.rootDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,toolStdio:input2.toolStdio,write:input2.write,yes:input2.yes}).pipe(provideService2(HttpClient,httpClient),provideService2(ProjectSettings,projectSettings))}).pipe(mapError3((cause)=>new ScaffoldUpdateOperationFailure({cause,message:failureMessage(cause),operation:"update-scaffold"})))}}));var toolEnsureOperationsLayer=effect(ToolEnsureOperations,gen2(function*makeToolEnsureOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const scaffoldCapabilities=yield*ScaffoldCapabilities;return{run:(input2)=>gen2(function*run6(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.rootDirectory,runtime});return ensureTools({baseline,capabilities:scaffoldCapabilities,rootDirectory:input2.rootDirectory,stdio:input2.stdio})}).pipe(mapError3((cause)=>new ToolEnsureOperationFailure({cause,message:failureMessage(cause),operation:"ensure-tools"})))}}));var featureApplicationOperationsLayer=mergeAll2(operatorSkillOperationsLayer,reportSubmissionOperationsLayer,repositoryCheckOperationsLayer,repositoryScaffoldingOperationsLayer,scaffoldUpdateOperationsLayer,toolEnsureOperationsLayer);var encodeJson5=encodeSync2(fromJsonString2(Unknown2));var encodePrettyJson4=(value5)=>JSON.stringify(JSON.parse(encodeJson5(value5)),null,2);var yesValues=new Set(["","y","yes"]);var writeLines=(prompt,lines2)=>forEach2(lines2,prompt.writeLine,{discard:true});var renderToolBootstrap=(event)=>{const failureDetails=formatToolBootstrapFailureDetails(event.statuses);return[renderCommandSection(event.phase==="base"?"Base tool check":"Tool bootstrap",event.statuses.map((entry)=>`• ${entry.toolId}: ${formatToolBootstrapStatus(entry)}`).join(`
1541
+ `)));if(emitOutput&&emitJson){yield*interaction.emit({_tag:"Json",result:result4})}else if(emitOutput){yield*interaction.emit({_tag:"Complete",applyRequested,changedFiles:allChanges.length,hasManagedUpdates,manifestPaths:manifestPaths(detection),staleFiles:staleFiles.length})}if(result4.applied){yield*submitCliEventEffect("cli.scaffold.update.applied",{baseline:{version:baseline.summary.version},configuration,cwd:rootDirectory})}return result4})};return yield*finalizeUpdateResult()}).pipe(ensuring2(sync2(()=>{if(updateStagingDirectory!==null){rmSync6(updateStagingDirectory,{force:true,recursive:true})}if(wikiStagingDirectory!==null){rmSync6(wikiStagingDirectory,{force:true,recursive:true})}})))};var runUpdate=(options4)=>runScaffoldOperation({...options4,operation:"update"});var failureMessage=(cause)=>cause instanceof Error?cause.message:String(cause);var silentUpdateInteraction={confirmApply:()=>succeed6(false),emit:()=>void_3};var nonBlankEnvironmentValue=(value5)=>value5!==undefined&&value5.trim().length>0?value5:undefined;var operatorSkillOperationsLayer=effect(OperatorSkillOperations,gen2(function*makeOperatorSkillOperations(){const runtime=yield*CliRuntimeConfig;const skillsCli=yield*SkillsCli;return{run:(action2,selectAgent)=>gen2(function*runOperatorSkillOperation(){const cwd=process.cwd();const detectedAgent=resolveActiveOperatorAgent(runtime.commandEnvironment);let selectedAgent;if(detectedAgent===undefined){if(selectAgent===undefined){return yield*new InvalidOperatorContext({message:"Cannot determine the active agent. Set HI_OPERATOR_AGENT to the Skills CLI agent name."})}selectedAgent=yield*selectAgent}const activeAgent=resolveActiveOperatorAgent(runtime.commandEnvironment,selectedAgent);if(activeAgent===undefined){return yield*new InvalidOperatorContext({message:"Cannot determine the active agent. Set HI_OPERATOR_AGENT to the Skills CLI agent name."})}const migrationRetryToken=nonBlankEnvironmentValue(runtime.commandEnvironment.HI_OPERATOR_MIGRATION_RETRY);const mutationRetryToken=nonBlankEnvironmentValue(runtime.commandEnvironment.HI_OPERATOR_MUTATION_RETRY);return yield*executeOperatorAction({action:action2,input:{activeAgent,activeCliVersion:version2,cwd,projectRoot:findOperatorProjectRoot(cwd)},...migrationRetryToken===undefined?{}:{migrationRetryToken},...mutationRetryToken===undefined?{}:{mutationRetryToken}})}).pipe(provideService2(SkillsCli,skillsCli))}}));var resolveFeatureBaseline=({baseline,refreshBaseline,rootDirectory,controlPlane,release,runtime,httpClient})=>resolveBaseline(baselineResolveOptions(fromNullishOr(baseline),refreshBaseline,rootDirectory,{controlPlane,release,runtime})).pipe(provideService2(HttpClient,httpClient));var reportSubmissionOperationsLayer=effect(ReportSubmissionOperations,gen2(function*makeReportSubmissionOperations(){const controlPlane=yield*CliControlPlaneConfig;const httpClient=yield*HttpClient;return{cliVersion:version2,observeRepository:observedRepository,recordSubmitted:(rootDirectory)=>submitCliEventEffect("cli.harness.report.submitted",{configuration:controlPlane,cwd:rootDirectory}).pipe(provideService2(HttpClient,httpClient),mapError3((cause)=>new ReportSubmissionOperationFailure({cause,message:failureMessage(cause),operation:"record-submitted"}))),resolveControlPlaneUrl:()=>succeed6(resolveControlPlaneUrl(undefined,controlPlane)),submit:(baseUrl2,report)=>submitHarnessReport({baseUrl:baseUrl2,report}).pipe(provideService2(HttpClient,httpClient),mapError3((cause)=>new ReportSubmissionOperationFailure({cause,message:failureMessage(cause),operation:"submit-report"})))}}));var repositoryCheckOperationsLayer=effect(RepositoryCheckOperations,gen2(function*makeRepositoryCheckOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const projectSettings=yield*ProjectSettings;return{...release.baseline===undefined?{}:{configuredBaseline:release.baseline},checkUpdate:(input2)=>gen2(function*checkUpdate(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.rootDirectory,runtime});const update3=yield*runUpdate({baseline,check:true,configuration:controlPlane,emitJson:false,emitOutput:false,interaction:silentUpdateInteraction,rootDirectory:input2.rootDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,write:false,yes:false}).pipe(provideService2(HttpClient,httpClient));const{operation:_operation,reconciliation:_reconciliation,...publicUpdate}=update3;return{baselineVersion:baseline.summary.version,update:publicUpdate}}).pipe(provideService2(ProjectSettings,projectSettings),mapError3((cause)=>new RepositoryCheckOperationFailure({cause,message:failureMessage(cause),operation:"check-repository-update"}))),cliVersion:version2,updateTag:release.updateTag}}));var repositoryScaffoldingResult=(result4)=>({machinePayload:{...result4,toolBootstrapStatuses:(result4.toolBootstrapStatuses??[]).map((tool)=>({...tool.status==="failed"?{errorMessage:`Required tool '${tool.toolId}' is unavailable after bootstrap.`}:{},status:tool.status,toolId:tool.toolId}))},outputDirectory:result4.outputDirectory,projectionStatus:result4.projectionStatus,toolBootstrapStatuses:(result4.toolBootstrapStatuses??[]).map((tool)=>({...tool.status==="failed"?{errorMessage:`Required tool '${tool.toolId}' is unavailable after bootstrap.`}:{},status:tool.status,toolId:tool.toolId}))});var repositoryScaffoldingOperationsLayer=effect(RepositoryScaffoldingOperations,gen2(function*makeRepositoryScaffoldingOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const projectSettings=yield*ProjectSettings;const scaffoldCapabilities=yield*ScaffoldCapabilities;return{run:(input2,interaction)=>gen2(function*run(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.kind==="init"?input2.outputDirectory:input2.scanDirectory,runtime});if(input2.kind==="init"){const result5=yield*runStageScaffold({baseline,commandId:"init",configuration:controlPlane,interaction,outputDirectory:input2.outputDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath}).pipe(provideService2(HttpClient,httpClient),provideService2(ProjectSettings,projectSettings));return repositoryScaffoldingResult(result5)}const result4=yield*runScaffold({assumeYes:input2.assumeYes,baseline,configuration:controlPlane,emitJson:input2.emitJson,interaction,...input2.outputDirectory===undefined?{}:{outputDirectory:input2.outputDirectory},repoShapeMode:input2.repoShape,scanDirectory:input2.scanDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,toolStdio:input2.toolStdio}).pipe(provideService2(HttpClient,httpClient),provideService2(ProjectSettings,projectSettings),provideService2(ScaffoldCapabilities,scaffoldCapabilities));return repositoryScaffoldingResult(result4)}).pipe(mapError3((cause)=>new RepositoryScaffoldingOperationFailure({cause,message:failureMessage(cause),operation:input2.kind==="init"?"initialize-repository":"setup-repository"})))}}));var scaffoldUpdateOperationsLayer=effect(ScaffoldUpdateOperations,gen2(function*makeScaffoldUpdateOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const projectSettings=yield*ProjectSettings;return{run:(input2,interaction)=>gen2(function*run(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.rootDirectory,runtime});return yield*runUpdate({allowBundledBaselineDriftApply:input2.baseline==="bundled"||release.baseline==="bundled",baseline,check:input2.check,configuration:controlPlane,emitJson:input2.emitJson,emitOutput:false,interaction,rootDirectory:input2.rootDirectory,scriptEnvironment:runtime.commandEnvironment,scriptRuntimePath:runtime.scriptRuntimePath,toolStdio:input2.toolStdio,write:input2.write,yes:input2.yes}).pipe(provideService2(HttpClient,httpClient),provideService2(ProjectSettings,projectSettings))}).pipe(mapError3((cause)=>new ScaffoldUpdateOperationFailure({cause,message:failureMessage(cause),operation:"update-scaffold"})))}}));var toolEnsureOperationsLayer=effect(ToolEnsureOperations,gen2(function*makeToolEnsureOperations(){const controlPlane=yield*CliControlPlaneConfig;const release=yield*CliReleaseConfig;const runtime=yield*CliRuntimeConfig;const httpClient=yield*HttpClient;const scaffoldCapabilities=yield*ScaffoldCapabilities;return{run:(input2)=>gen2(function*run(){const baseline=yield*resolveFeatureBaseline({baseline:input2.baseline,controlPlane,httpClient,refreshBaseline:input2.refreshBaseline,release,rootDirectory:input2.rootDirectory,runtime});return ensureTools({baseline,capabilities:scaffoldCapabilities,rootDirectory:input2.rootDirectory,stdio:input2.stdio})}).pipe(mapError3((cause)=>new ToolEnsureOperationFailure({cause,message:failureMessage(cause),operation:"ensure-tools"})))}}));var featureApplicationOperationsLayer=mergeAll2(operatorSkillOperationsLayer,reportSubmissionOperationsLayer,repositoryCheckOperationsLayer,repositoryScaffoldingOperationsLayer,scaffoldUpdateOperationsLayer,toolEnsureOperationsLayer);var encodeJson5=encodeSync2(fromJsonString2(Unknown2));var encodePrettyJson4=(value5)=>JSON.stringify(JSON.parse(encodeJson5(value5)),null,2);var yesValues=new Set(["","y","yes"]);var writeLines=(prompt,lines2)=>forEach2(lines2,prompt.writeLine,{discard:true});var renderToolBootstrap=(event)=>{const failureDetails=formatToolBootstrapFailureDetails(event.statuses);return[renderCommandSection(event.phase==="base"?"Base tool check":"Tool bootstrap",event.statuses.map((entry)=>`• ${entry.toolId}: ${formatToolBootstrapStatus(entry)}`).join(`
1542
1542
  `)),...failureDetails===null?[]:["",renderCommandSection("Tool Bootstrap Warning",failureDetails)]]};var renderEvent=(event)=>{switch(event._tag){case"SetupStarted":{return[renderScaffoldTitle(),"",renderSetupIntro()]}case"ToolCheck":{return["",renderHint(`${event.phase==="base"?"Checking base scaffold tools":"Ensuring selected-pack tools"}: ${event.toolIds.join(", ")}`)]}case"ToolBootstrap":{return renderToolBootstrap(event)}case"Detection":{return["",renderCommandSection("Detection",formatDetectionSummary(event.detection))]}case"ResolvedPacks":{return["",renderCommandSection("Resolved packs",formatResolvedPackSummary({...event.resolved,baseline:event.baseline}))]}case"SelectionAccepted":{return["",renderHint("Non-interactive mode: accepting prefilled pack selection.")]}case"SelectionPreview":{return["",renderCommandSection("Selection preview",formatSelectionPreview({addedPacks:event.addedPacks,baseline:event.baseline,finalPacks:event.finalPacks,outputDirectory:event.outputDirectory,preselectedPacks:event.preselectedPacks,removedPacks:event.removedPacks}))]}case"SelectionReopened":{return["",renderHint("Reopening pack selection editor.")]}case"SetupComplete":{const{result:result4}=event;return["",renderCommandSection("Scaffold Complete",["Scaffold files were written successfully.",`Output directory: \`${result4.outputDirectory}\``,`Prompt file: \`${result4.agentSystemPromptFile}\``].join(`
1543
1543
  `)),"",renderCommandSection("Selection",formatConfirmationSummary(result4,event.baseline)),"",renderNotes([`Output directory: ${result4.outputDirectory}`]),...result4.hiddenOutputDirectories.length>0?[renderNotes([`Hidden output directories: ${result4.hiddenOutputDirectories.join(", ")}`])]:[],"",renderCommandSection("Paste Into Your Next Agent",[event.clipboard.ok?`Agent prompt copied to clipboard via \`${event.clipboard.command}\`.`:"Clipboard copy failed. Open the generated prompt file and paste it manually.",`Prompt file: \`${result4.agentSystemPromptFile}\``,`Agent handoff file: \`${result4.agentHandoffFile}\``,`If you are an agent in this terminal, open \`${result4.agentSystemPromptFile}\` and follow it now.`,"Paste the generated agent prompt into your next agent now."].join(`
1544
1544
  `)),...event.emitJson?["",renderDivider(),renderJsonLabel(),encodePrettyJson4(result4)]:[]]}case"InitComplete":{const backlogProviderLabels3={"azure-devops":"Azure DevOps",github:"GitHub Projects and Issues",linear:"Linear",monday:"monday.com"};const wikiFrameworkLabels3={next:"Next.js","tanstack-start":"TanStack Start"};const repositoryManagerLabels={"azure-devops":"Azure DevOps",bitbucket:"Bitbucket",github:"GitHub",gitlab:"GitLab"};return[renderScaffoldTitle(),"",renderStageIntro({body:event.summary,title:"Requirements"}),"",renderCommandSection("Scaffolded skills",event.skillFiles.map((file5)=>`• ${file5}`).join(`
1545
1545
  `)),...event.wikiFiles.length>0?["",renderCommandSection("Scaffolded wiki files",event.wikiFiles.map((file5)=>`• ${file5}`).join(`
1546
1546
  `))]:[],"","",renderNotes([`Output directory: ${event.outputDirectory}`,`Hidden output directories: ${event.hiddenOutputDirectories.join(", ")}`]),"",renderCommandSection("Backlog provider",`${backlogProviderLabels3[event.settings.backlogProvider]} (${event.settings.backlogProvider})`),"",renderCommandSection("Wiki framework",`${wikiFrameworkLabels3[event.wikiFramework]} (${event.wikiFramework})`),"",renderCommandSection("Repository manager",`selected repository manager: ${repositoryManagerLabels[event.settings.repositoryManager]} (\`${event.settings.repositoryManager}\`)`),"",renderCommandSection("Operator prompt",event.operatorPrompt)]}}};var selectPacks=(prompt,request3)=>{const add4=request3.kind==="add";return writeLines(prompt,["",renderCommandSection(add4?"Add optional packs":"Edit prefilled packs",[add4?"Select any extra packs you want to include beyond the prefilled scaffold set.":"Select any removable packs you want to drop from the prefilled scaffold set.","",`available packs: ${request3.allowed.length}`].join(`
1547
- `))]).pipe(andThen2(prompt.multiSelect({choices:request3.allowed.map((packId)=>{const description=request3.descriptions?.[packId];return description===undefined?{title:packId,value:packId}:{description,title:packId,value:packId}}),message:add4?"Select optional packs to add. Press enter with no selection to add nothing.":"Select prefilled packs to remove. Press enter with no selection to keep all prefilled packs.",selectAll:add4?"Select all optional packs":"Select all removable packs",selectNone:add4?"Add nothing":"Remove nothing (keep all)"})))};var makeRepositoryScaffoldingInteraction=(prompt)=>({confirmSelection:()=>map7(prompt.readLine(renderQuestion("Apply this scaffold selection? [Y/n]: ")),(answer)=>yesValues.has(answer.trim().toLowerCase())),emit:(event)=>writeLines(prompt,renderEvent(event)),keepPrefilledSelection:()=>map7(prompt.readLine(renderQuestion("Keep the prefilled pack selection as-is? [Y/n]: ")),(answer)=>yesValues.has(answer.trim().toLowerCase())),selectPacks:(request3)=>selectPacks(prompt,request3),selectRepoSettings:()=>selectRepoSettings({prompt,retryCommand:"hi init"}),selectWikiFramework:()=>map7(prompt.singleSelect({choices:[{description:"default",title:"Next.js",value:"next"},{title:"TanStack Start",value:"tanstack-start"}],defaultValue:"next",message:"Select wiki framework"}),(answer)=>answer)});var repositoryScaffoldingInteractionLayer=effect(RepositoryScaffoldingInteraction,map7(CliPrompt,makeRepositoryScaffoldingInteraction));import{execFileSync as execFileSync5}from"node:child_process";import{existsSync as existsSync15,linkSync,mkdirSync as mkdirSync9,mkdtempSync as mkdtempSync4,readFileSync as readFileSync14,renameSync as renameSync3,rmdirSync,unlinkSync,writeFileSync as writeFileSync9}from"node:fs";import path26 from"node:path";var isMissingFile2=(cause)=>typeof cause==="object"&&cause!==null&&("code"in cause)&&cause.code==="ENOENT";var hasErrorCode=(cause,code)=>typeof cause==="object"&&cause!==null&&("code"in cause)&&cause.code===code;var hasExitStatus=(cause,status2)=>typeof cause==="object"&&cause!==null&&("status"in cause)&&cause.status===status2;var hasRepositoryGitDirectory=(rootDirectory)=>{let currentDirectory=path26.resolve(rootDirectory);while(true){const gitMarker=path26.join(currentDirectory,".git");if(existsSync15(gitMarker)){execFileSync5("git",["rev-parse","--resolve-git-dir",gitMarker],{encoding:"utf-8",stdio:["ignore","pipe","pipe"]});return true}const parentDirectory=path26.dirname(currentDirectory);if(parentDirectory===currentDirectory){return false}currentDirectory=parentDirectory}};var cleanupFailure=(filePath,cause,message)=>new ProjectSettingsAccessFailure({cause,message,operation:"write",path:filePath});var repositoryGitConfigFailure=(rootDirectory,cause)=>new ProjectSettingsAccessFailure({cause,message:`Failed to read repository git config for ${rootDirectory}.`,operation:"read",path:rootDirectory});var ProjectSettingsFileSystemLive=succeed5(ProjectSettingsFileSystem,{createTextFile:(filePath,content)=>suspend2(()=>{try{mkdirSync9(path26.dirname(filePath),{recursive:true});writeFileSync9(filePath,content,{flag:"wx"});return succeed6(true)}catch(error2){return hasErrorCode(error2,"EEXIST")?succeed6(false):fail6(new ProjectSettingsAccessFailure({cause:error2,message:`Failed to create ${filePath}.`,operation:"write",path:filePath}))}}),directoryExists:(directoryPath)=>sync2(()=>existsSync15(directoryPath)),joinPath:(...segments)=>path26.join(...segments),readRepositoryGitConfig:(rootDirectory)=>suspend2(()=>{try{if(!hasRepositoryGitDirectory(rootDirectory)){return succeed6(none2())}return succeed6(some2(execFileSync5("git",["-C",rootDirectory,"config","--local","--get-regexp","^remote\\..*\\.url$"],{encoding:"utf-8",stdio:["ignore","pipe","pipe"]})))}catch(error2){return hasExitStatus(error2,1)?succeed6(none2()):fail6(repositoryGitConfigFailure(rootDirectory,error2))}}),readTextFile:(filePath)=>suspend2(()=>{try{return succeed6(some2(readFileSync14(filePath,"utf-8")))}catch(error2){return isMissingFile2(error2)?succeed6(none2()):fail6(new ProjectSettingsAccessFailure({cause:error2,message:`Failed to read ${filePath}.`,operation:"read",path:filePath}))}}),removeEmptyDirectory:(directoryPath)=>suspend2(()=>{try{rmdirSync(directoryPath);return void_3}catch(error2){return hasErrorCode(error2,"ENOENT")||hasErrorCode(error2,"ENOTEMPTY")?void_3:fail6(new ProjectSettingsAccessFailure({cause:error2,message:`Failed to remove empty directory ${directoryPath}.`,operation:"write",path:directoryPath}))}}),removeTextFileIfContent:(filePath,expectedContent)=>suspend2(()=>{let recoveryDirectory;try{recoveryDirectory=mkdtempSync4(path26.join(path26.dirname(filePath),`.${path26.basename(filePath)}.hi-cleanup-`))}catch(error2){return isMissingFile2(error2)?succeed6(false):fail6(cleanupFailure(filePath,error2,`Failed to reserve cleanup recovery for ${filePath}.`))}const recoveryPath=path26.join(recoveryDirectory,"claimed");try{renameSync3(filePath,recoveryPath)}catch(error2){try{rmdirSync(recoveryDirectory)}catch{}return isMissingFile2(error2)?succeed6(false):fail6(cleanupFailure(filePath,error2,`Failed to claim ${filePath} for unchanged-content cleanup.`))}let content;try{content=readFileSync14(recoveryPath,"utf-8")}catch(error2){try{linkSync(recoveryPath,filePath)}catch{}return fail6(cleanupFailure(filePath,error2,`Failed to inspect claimed ${filePath}; claimed bytes remain at ${recoveryPath}.`))}if(content===expectedContent){try{unlinkSync(recoveryPath)}catch(error2){return fail6(cleanupFailure(filePath,error2,`Failed to remove unchanged ${filePath}; claimed bytes remain at ${recoveryPath}.`))}try{rmdirSync(recoveryDirectory);return succeed6(true)}catch(error2){return fail6(cleanupFailure(filePath,error2,`Removed unchanged ${filePath}, but failed to remove empty cleanup directory ${recoveryDirectory}.`))}}try{linkSync(recoveryPath,filePath);return succeed6(false)}catch(error2){return fail6(cleanupFailure(filePath,error2,`Failed to restore changed ${filePath}; claimed bytes remain at ${recoveryPath}.`))}}),writeTextFile:(filePath,content)=>try_3({catch:(cause)=>new ProjectSettingsAccessFailure({cause,message:`Failed to write ${filePath}.`,operation:"write",path:filePath}),try:()=>{mkdirSync9(path26.dirname(filePath),{recursive:true});writeFileSync9(filePath,content)}})});import{spawn as spawn2}from"node:child_process";import{createHash as createHash8}from"node:crypto";import{readFileSync as readFileSync15,realpathSync as realpathSync4}from"node:fs";import{mkdtemp as mkdtemp2,rm as rm2}from"node:fs/promises";import{tmpdir as tmpdir7}from"node:os";import path27 from"node:path";var minimumSkillsCliVersion="1.5.20";var operatorSkillOrigin="https://github.com/wearedevpunks/skills.git";var operatorSkillRelativePath=path27.join("skills","agnostic","cli","hi-cli");var sha256Pattern=/^[0-9a-f]{64}$/u;var terminationGraceMs=250;class SkillsCliProcessTreeCleanupDefectError extends Error{_tag="SkillsCliProcessTreeCleanupDefect";constructor(message){super(message);this.name="SkillsCliProcessTreeCleanupDefectError"}}var defaultProcessTreeOptions={platform:process.platform,taskkillExecutable:"taskkill"};var listedSkillSchema=ArraySchema(Struct({agents:ArraySchema(String5),name:String5,path:String5,scope:Literals(["project","global"])}));var normalizeAgent=(agent)=>agent.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");var scopeArguments=(scope3)=>scope3==="global"?["--global"]:[];var failureContext=(operation2,request3)=>({agent:request3.agent,operation:operation2,scope:request3.scope});var parseVersion2=(value5)=>{const match8=/^v?(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)$/u.exec(value5.trim());return match8===null?undefined:[Number(match8[1]),Number(match8[2]),Number(match8[3])]};var compareVersions3=(left,right)=>{for(const index2 of[0,1,2]){const difference3=left[index2]-right[index2];if(difference3!==0){return difference3}}return 0};var isContainedPath=(root,candidate)=>{const relative=path27.relative(root,candidate);return relative!==".."&&!relative.startsWith(`..${path27.sep}`)&&!path27.isAbsolute(relative)};var terminateProcessTree=(child,options4,onTerminated)=>{const{pid}=child;if(pid===undefined){child.kill("SIGKILL");onTerminated({_tag:"CleanupFailed",message:"Skills CLI process cleanup could not identify the direct child"});return()=>{}}if(options4.platform==="win32"){let completed2=false;let fallback;let taskkill;const listeners={stopChild:()=>{},stopTaskkill:()=>{}};const cleanup=()=>{listeners.stopChild();listeners.stopTaskkill();if(fallback!==undefined){clearTimeout(fallback)}};const finish2=(termination)=>{if(completed2){return}completed2=true;cleanup();onTerminated(termination)};const onDirectChildClose=()=>{finish2({_tag:"CleanupFailed",message:"Windows process-tree cleanup failed; only the direct child exit was verified"})};const terminateDirectChild=(reason)=>{listeners.stopTaskkill();if(child.exitCode!==null||child.signalCode!==null){finish2({_tag:"CleanupFailed",message:`${reason}; only the direct child exit was verified`});return}child.once("close",onDirectChildClose);listeners.stopChild=()=>{child.removeListener("close",onDirectChildClose)};child.kill("SIGKILL");fallback=setTimeout(()=>{finish2({_tag:"CleanupFailed",message:`${reason}; direct child exit could not be verified`})},terminationGraceMs)};const onTaskkillError=(error2)=>{terminateDirectChild(`Windows process-tree cleanup failed: ${error2.message}`)};const onTaskkillClose=(status2)=>{if(status2===0){finish2({_tag:"TreeTerminated"});return}terminateDirectChild(`Windows process-tree cleanup exited with status ${status2??-1}`)};try{taskkill=spawn2(options4.taskkillExecutable,["/pid",String(pid),"/T","/F"],{shell:false,stdio:"ignore",windowsHide:true});taskkill.once("error",onTaskkillError);taskkill.once("close",onTaskkillClose);listeners.stopTaskkill=()=>{taskkill?.removeListener("error",onTaskkillError);taskkill?.removeListener("close",onTaskkillClose)}}catch(error2){terminateDirectChild(`Windows process-tree cleanup failed: ${error2 instanceof Error?error2.message:String(error2)}`)}return()=>{completed2=true;cleanup()}}let completed=false;let poll;const isRunning=()=>{try{process.kill(-pid,0);return true}catch(error2){return error2.code!=="ESRCH"}};const signal=(value5)=>{try{process.kill(-pid,value5)}catch(error2){if(error2.code!=="ESRCH"){child.kill(value5)}}};signal("SIGTERM");const escalation=setTimeout(()=>{signal("SIGKILL")},terminationGraceMs);const timers={};const finish=(termination)=>{if(completed){return}completed=true;clearTimeout(escalation);if(timers.deadline!==undefined){clearTimeout(timers.deadline)}if(poll!==undefined){clearImmediate(poll)}onTerminated(termination)};const awaitExit=()=>{if(!isRunning()){finish({_tag:"TreeTerminated"});return}poll=setImmediate(awaitExit)};timers.deadline=setTimeout(()=>{signal("SIGKILL");finish(isRunning()?{_tag:"CleanupFailed",message:"POSIX process-group cleanup did not complete before the termination deadline"}:{_tag:"TreeTerminated"})},terminationGraceMs*2);awaitExit();return()=>{completed=true;clearTimeout(escalation);if(timers.deadline!==undefined){clearTimeout(timers.deadline)}if(poll!==undefined){clearImmediate(poll)}}};var terminateChild=(child,processTree)=>callback2((resume)=>{const cancel=terminateProcessTree(child,processTree,(termination)=>{resume(succeed6(termination))});return sync2(cancel)}).pipe(flatMap4((termination)=>termination._tag==="CleanupFailed"?failCause3(combine2(interrupt2(),die2(new SkillsCliProcessTreeCleanupDefectError(termination.message)))):void_3));var makeSkillsCliLive=(options4)=>{const executable=options4.executable??"skills";const gitExecutable=options4.gitExecutable??"git";const timeoutEnabled=options4.timeoutMs!==false;const timeoutMs=typeof options4.timeoutMs==="number"?options4.timeoutMs:30000;const{environment}=options4;const processTree=options4.processTree??defaultProcessTreeOptions;const removeTemporaryDirectory=options4.removeTemporaryDirectory??((directory3)=>rm2(directory3,{force:true,recursive:true}));const temporaryDirectoryRoot=options4.temporaryDirectoryRoot??tmpdir7();const runCommand=fn2("SkillsCli.runCommand")(function*runCommand2(operation2,request3,command,args2,cwd,commandLabel){const result4=yield*callback2((resume)=>{let child;try{child=spawn2(command,args2,{cwd,detached:true,env:environment,shell:false,stdio:["ignore","pipe","pipe"],windowsHide:true})}catch(error2){resume(succeed6({error:error2,status:null,stderr:"",stdout:""}));return}let completed=false;let timedOut=false;let stderr="";let stdout="";let cancelTermination;const finish=(processResult)=>{if(completed){return}completed=true;cancelTermination?.();resume(succeed6(processResult))};const timeout3=timeoutEnabled?setTimeout(()=>{timedOut=true;cancelTermination=terminateProcessTree(child,processTree,(termination)=>{const cleanupFailed=termination._tag==="CleanupFailed";finish({error:Object.assign(new Error(cleanupFailed?termination.message:`${commandLabel} ${operation2} timed out`),{code:cleanupFailed?"EPROCESSTREE":"ETIMEDOUT"}),status:null,stderr,stdout})})},timeoutMs):undefined;child.stdout?.setEncoding("utf-8");child.stderr?.setEncoding("utf-8");child.stdout?.on("data",(chunk)=>{stdout+=chunk});child.stderr?.on("data",(chunk)=>{stderr+=chunk});child.once("error",(error2)=>{if(timeout3!==undefined){clearTimeout(timeout3)}finish({error:error2,status:null,stderr,stdout})});child.once("close",(status2)=>{if(!timedOut){if(timeout3!==undefined){clearTimeout(timeout3)}finish({status:status2,stderr,stdout})}});return sync2(()=>{if(timeout3!==undefined){clearTimeout(timeout3)}}).pipe(andThen2(terminateChild(child,processTree)))});const context4=failureContext(operation2,request3);const code=result4.error?.code;if(code==="ENOENT"){return yield*new SkillsCliUnavailable({...context4,executable:command,message:`${commandLabel} executable is unavailable: ${command}`})}if(code==="ETIMEDOUT"){return yield*new SkillsCliTimeout({...context4,message:`${commandLabel} ${operation2} timed out after ${timeoutMs}ms`,timeoutMs})}if(code==="EPROCESSTREE"){return yield*new SkillsCliExit({...context4,exitCode:-1,message:`${commandLabel} ${operation2} process cleanup failed`,stderr:result4.error?.message??""})}if(result4.error!==undefined||result4.status!==0){return yield*new SkillsCliExit({...context4,exitCode:result4.status??-1,message:`${commandLabel} ${operation2} exited unsuccessfully`,stderr:result4.stderr||result4.error?.message||""})}return result4.stdout});const run6=(operation2,request3,args2)=>runCommand(operation2,request3,executable,args2,request3.cwd,"Skills CLI");const runGit=(request3,args2,cwd)=>runCommand("install",request3,gitExecutable,args2,cwd,"Git");const temporaryDirectoryFailure=(request3,message,cause)=>new SkillsCliExit({...failureContext("install",request3),exitCode:-1,message,stderr:cause instanceof Error?cause.message:String(cause)});const withMaterializedTarget=(request3,use)=>acquireUseRelease2(tryPromise2({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot create a temporary operator-skill checkout",cause),try:()=>mkdtemp2(path27.join(temporaryDirectoryRoot,"hi-operator-skill-"))}),(temporaryRoot)=>gen2(function*materializeTarget(){const checkoutRoot=path27.join(temporaryRoot,"source");yield*runGit(request3,["init",checkoutRoot],request3.cwd);yield*runGit(request3,["remote","add","origin",operatorSkillOrigin],checkoutRoot);yield*runGit(request3,["fetch","--depth=1","origin",request3.target.revision],checkoutRoot);const fetchedRevision=(yield*runGit(request3,["rev-parse","FETCH_HEAD^{commit}"],checkoutRoot)).trim();if(fetchedRevision!==request3.target.revision){return yield*new SkillsCliMalformedOutput({...failureContext("install",request3),message:"Git fetched an unexpected operator-skill revision",stdout:fetchedRevision})}yield*runGit(request3,["checkout","--detach","FETCH_HEAD"],checkoutRoot);const canonicalCheckout=yield*try_3({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot resolve the temporary operator-skill checkout",cause),try:()=>realpathSync4(checkoutRoot)});const localSource=yield*try_3({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot resolve the materialized operator-skill source",cause),try:()=>realpathSync4(path27.join(canonicalCheckout,operatorSkillRelativePath))});if(!isContainedPath(canonicalCheckout,localSource)){return yield*new SkillsCliMalformedOutput({...failureContext("install",request3),message:"Materialized operator-skill source escapes the checkout",stdout:localSource})}return yield*use(localSource)}),(temporaryRoot)=>tryPromise2({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot clean up the temporary operator-skill checkout",cause),try:()=>removeTemporaryDirectory(temporaryRoot)}));const ensureSupportedVersion=fn2("SkillsCli.ensureSupportedVersion")(function*ensureSupportedVersion2(operation2,request3){const stdout=yield*run6(operation2,request3,["--version"]);const version3=parseVersion2(stdout);if(version3===undefined){return yield*new SkillsCliMalformedOutput({...failureContext(operation2,request3),message:"Skills CLI returned a malformed version",stdout})}const minimumVersion=parseVersion2(minimumSkillsCliVersion);if(compareVersions3(version3,minimumVersion)<0){return yield*new SkillsCliUnsupportedVersion({...failureContext(operation2,request3),message:`Skills CLI ${minimumSkillsCliVersion} or newer is required`,minimumVersion:minimumSkillsCliVersion,version:stdout.trim()})}});const verifyListedSkill=(request3,skill,verifiedSkills)=>{const fail12=(reason,message)=>new SkillsCliVerificationFailure({...failureContext("list",request3),message,reason,skillName:skill.name,skillPath:skill.path,verifiedSkills});return gen2(function*verifySkillIdentity(){if(!path27.isAbsolute(skill.path)||path27.parse(skill.path).root===path27.normalize(skill.path)){return yield*fail12("unsafe-path",`Skills CLI reported an unsafe path for ${skill.name}`)}if(request3.target.contentManifest.length===0){return yield*fail12("malformed","Operator-skill content manifest is empty")}let canonicalRoot;try{canonicalRoot=realpathSync4(skill.path)}catch(error2){const{code}=error2;return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot resolve the CLI-reported ${skill.name} copy`)}const seenPaths=new Set;for(const entry of request3.target.contentManifest){const normalizedRelativePath=path27.normalize(entry.path);if(entry.path===""||path27.isAbsolute(entry.path)||normalizedRelativePath===".."||normalizedRelativePath.startsWith(`..${path27.sep}`)||!sha256Pattern.test(entry.sha256)||seenPaths.has(normalizedRelativePath)){return yield*fail12("malformed","Operator-skill content manifest is malformed")}seenPaths.add(normalizedRelativePath);const filePath=path27.resolve(skill.path,normalizedRelativePath);if(!isContainedPath(path27.resolve(skill.path),filePath)){return yield*fail12("unsafe-path","Operator-skill manifest escapes the reported path")}let canonicalFilePath;try{canonicalFilePath=realpathSync4(filePath)}catch(error2){const{code}=error2;return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot resolve ${entry.path} from the CLI-reported ${skill.name} copy`)}if(!isContainedPath(canonicalRoot,canonicalFilePath)){return yield*fail12("unsafe-path",`${entry.path} escapes the CLI-reported copy`)}let content;try{content=readFileSync15(canonicalFilePath)}catch(error2){const{code}=error2;return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot read ${entry.path} from the CLI-reported ${skill.name} copy`)}const actualSha256=createHash8("sha256").update(content).digest("hex");if(actualSha256!==entry.sha256){return yield*fail12("identity-mismatch",`CLI-reported ${skill.name} content does not match the immutable target`)}}return{...skill,cliCompatibility:request3.target.cliCompatibility,revision:request3.target.revision,source:request3.target.source,version:request3.target.version}})};const list2=fn2("SkillsCli.list")(function*list3(request3){yield*ensureSupportedVersion("list",request3);const stdout=yield*run6("list",request3,["list",...scopeArguments(request3.scope),"--agent",request3.agent,"--json"]);const decoded=yield*try_3({catch:()=>new SkillsCliMalformedOutput({...failureContext("list",request3),message:"Skills CLI list returned malformed JSON",stdout}),try:()=>decodeUnknownSync2(listedSkillSchema)(JSON.parse(stdout))});const normalized=decoded.map((skill)=>({...skill,agents:skill.agents.map(normalizeAgent).toSorted()}));if(normalized.some((skill)=>skill.scope!==request3.scope)){return yield*new SkillsCliMalformedOutput({...failureContext("list",request3),message:`Skills CLI list returned a scope other than ${request3.scope}`,stdout})}const requestedAgent=normalizeAgent(request3.agent);const listed=[];const verified=()=>listed.filter((skill)=>("version"in skill));let unbound;for(const skill of normalized){if(skill.name!=="hi-cli"){listed.push(skill);continue}if(!skill.agents.includes(requestedAgent)){unbound??=skill;continue}listed.push(yield*verifyListedSkill(request3,skill,verified()))}if(unbound!==undefined){return yield*new SkillsCliBindingFailure({...failureContext("list",request3),message:`Skills CLI listed ${unbound.name} without the active agent binding`,reportedAgents:unbound.agents,skillName:unbound.name,verifiedSkills:verified()})}return listed});const install=fn2("SkillsCli.install")(function*install2(request3){yield*ensureSupportedVersion("install",request3);yield*withMaterializedTarget(request3,(localSource)=>run6("install",request3,["add",localSource,"--skill","hi-cli",...scopeArguments(request3.scope),"--agent",request3.agent,"--yes","--copy"]))});const remove7=fn2("SkillsCli.remove")(function*remove8(request3){yield*ensureSupportedVersion("remove",request3);yield*run6("remove",request3,["remove",request3.name,...scopeArguments(request3.scope),"--agent",request3.agent,"--yes"])});return succeed5(SkillsCli,{install,list:list2,remove:remove7})};var startupCheckWorkerEnv="HI_STARTUP_CHECK_WORKER";var startupCheckCliEnv="HI_STARTUP_CHECK_CLI";var startupCheckSkillEnv="HI_STARTUP_CHECK_SKILL";var processEnvironment=process.env;var processProvider=makeEnvironmentProvider(processEnvironment);var startupCheckCacheFile=path28.join(homedir3(),".cache","hi","startup-check.json");var effectBuiltIns=exports_GlobalFlag.BuiltIns.filter((flag)=>flag!==exports_GlobalFlag.Wizard);var rootCommands=commandRegistry.command.subcommands.flatMap(({commands:commands2})=>commands2);var rootCommandNames=rootCommands.map(({name:commandName})=>commandName);var forceColorEnvironment=(runtime)=>{if(runtime.commandEnvironment.FORCE_COLOR==="0"){return{FORCE_COLOR:"0"}}if(runtime.forceColor){return{FORCE_COLOR:"1"}}return{}};var makeRootRenderEnvironment=(runtime,mode)=>makeHumanRenderEnvironment({columns:process.stdout.columns,environment:{...runtime.colorForegroundBackground===undefined?{}:{COLORFGBG:runtime.colorForegroundBackground},...forceColorEnvironment(runtime),...runtime.noColor?{NO_COLOR:"1"}:{},...runtime.terminalTheme===undefined?{}:{HI_THEME:runtime.terminalTheme}},mode,stdoutIsTTY:process.stdout.isTTY===true});var renderRootCommandGuide=(runtime,mode)=>renderRootScreen(renderCommandGuide(commandRegistry.discovery),makeRootRenderEnvironment(runtime,mode));var makeWizardGlobalFlag=(runtime)=>exports_GlobalFlag.action({flag:exports_Flag.boolean("wizard").pipe(exports_Flag.withDescription("Show the interactive command guide")),run:()=>sync2(()=>{const mode=selectOutputMode({jsonSelected:false,stdinIsTTY:process.stdin.isTTY===true,stdoutIsTTY:process.stdout.isTTY===true});process.stdout.write(renderRootCommandGuide(runtime,mode==="interactive"?mode:"plain"))})});var makeRootCommand=(runtime)=>commandRegistry.command.pipe(exports_Command.withGlobalFlags([makeWizardGlobalFlag(runtime)]));var isRootHelpAction=(nativeAction)=>nativeAction==="--help"||nativeAction==="-h";var isHelpArgument=(argument)=>argument==="--help"||argument.startsWith("--help=")||/^-[^-]*h/u.test(argument)&&argument!=="-";var classifyRootHelp=(commandArguments,nativeAction)=>{if(!isRootHelpAction(nativeAction)){return"none"}if(commandArguments.length===1&&(commandArguments[0]==="--help"||commandArguments[0]==="-h")){return"exact"}const helpIndex=commandArguments.findIndex(isHelpArgument);const rootCommandIndex=commandArguments.findIndex((argument)=>rootCommandNames.includes(argument));return rootCommandIndex!==-1&&rootCommandIndex<helpIndex?"nested":"invalid"};var defaultCliFormatter=exports_CliOutput.defaultFormatter();var cliOutputLayer=exports_CliOutput.layer({...defaultCliFormatter,formatVersion:(_name,currentVersion)=>`${currentVersion}
1547
+ `))]).pipe(andThen2(prompt.multiSelect({choices:request3.allowed.map((packId)=>{const description=request3.descriptions?.[packId];return description===undefined?{title:packId,value:packId}:{description,title:packId,value:packId}}),message:add4?"Select optional packs to add. Press enter with no selection to add nothing.":"Select prefilled packs to remove. Press enter with no selection to keep all prefilled packs.",selectAll:add4?"Select all optional packs":"Select all removable packs",selectNone:add4?"Add nothing":"Remove nothing (keep all)"})))};var makeRepositoryScaffoldingInteraction=(prompt)=>({confirmSelection:()=>map7(prompt.readLine(renderQuestion("Apply this scaffold selection? [Y/n]: ")),(answer)=>yesValues.has(answer.trim().toLowerCase())),emit:(event)=>writeLines(prompt,renderEvent(event)),keepPrefilledSelection:()=>map7(prompt.readLine(renderQuestion("Keep the prefilled pack selection as-is? [Y/n]: ")),(answer)=>yesValues.has(answer.trim().toLowerCase())),selectPacks:(request3)=>selectPacks(prompt,request3),selectRepoSettings:()=>selectRepoSettings({prompt,retryCommand:"hi init"}),selectWikiFramework:()=>map7(prompt.singleSelect({choices:[{description:"default",title:"Next.js",value:"next"},{title:"TanStack Start",value:"tanstack-start"}],defaultValue:"next",message:"Select wiki framework"}),(answer)=>answer)});var repositoryScaffoldingInteractionLayer=effect(RepositoryScaffoldingInteraction,map7(CliPrompt,makeRepositoryScaffoldingInteraction));import{execFileSync as execFileSync5}from"node:child_process";import{existsSync as existsSync15,linkSync,mkdirSync as mkdirSync9,mkdtempSync as mkdtempSync4,readFileSync as readFileSync14,renameSync as renameSync3,rmdirSync,unlinkSync,writeFileSync as writeFileSync9}from"node:fs";import path26 from"node:path";var isMissingFile2=(cause)=>typeof cause==="object"&&cause!==null&&("code"in cause)&&cause.code==="ENOENT";var hasErrorCode=(cause,code)=>typeof cause==="object"&&cause!==null&&("code"in cause)&&cause.code===code;var hasExitStatus=(cause,status2)=>typeof cause==="object"&&cause!==null&&("status"in cause)&&cause.status===status2;var hasRepositoryGitDirectory=(rootDirectory)=>{let currentDirectory=path26.resolve(rootDirectory);while(true){const gitMarker=path26.join(currentDirectory,".git");if(existsSync15(gitMarker)){execFileSync5("git",["rev-parse","--resolve-git-dir",gitMarker],{encoding:"utf-8",stdio:["ignore","pipe","pipe"]});return true}const parentDirectory=path26.dirname(currentDirectory);if(parentDirectory===currentDirectory){return false}currentDirectory=parentDirectory}};var cleanupFailure=(filePath,cause,message)=>new ProjectSettingsAccessFailure({cause,message,operation:"write",path:filePath});var repositoryGitConfigFailure=(rootDirectory,cause)=>new ProjectSettingsAccessFailure({cause,message:`Failed to read repository git config for ${rootDirectory}.`,operation:"read",path:rootDirectory});var ProjectSettingsFileSystemLive=succeed5(ProjectSettingsFileSystem,{createTextFile:(filePath,content)=>suspend2(()=>{try{mkdirSync9(path26.dirname(filePath),{recursive:true});writeFileSync9(filePath,content,{flag:"wx"});return succeed6(true)}catch(error2){return hasErrorCode(error2,"EEXIST")?succeed6(false):fail6(new ProjectSettingsAccessFailure({cause:error2,message:`Failed to create ${filePath}.`,operation:"write",path:filePath}))}}),directoryExists:(directoryPath)=>sync2(()=>existsSync15(directoryPath)),joinPath:(...segments)=>path26.join(...segments),readRepositoryGitConfig:(rootDirectory)=>suspend2(()=>{try{if(!hasRepositoryGitDirectory(rootDirectory)){return succeed6(none2())}return succeed6(some2(execFileSync5("git",["-C",rootDirectory,"config","--local","--get-regexp","^remote\\..*\\.url$"],{encoding:"utf-8",stdio:["ignore","pipe","pipe"]})))}catch(error2){return hasExitStatus(error2,1)?succeed6(none2()):fail6(repositoryGitConfigFailure(rootDirectory,error2))}}),readTextFile:(filePath)=>suspend2(()=>{try{return succeed6(some2(readFileSync14(filePath,"utf-8")))}catch(error2){return isMissingFile2(error2)?succeed6(none2()):fail6(new ProjectSettingsAccessFailure({cause:error2,message:`Failed to read ${filePath}.`,operation:"read",path:filePath}))}}),removeEmptyDirectory:(directoryPath)=>suspend2(()=>{try{rmdirSync(directoryPath);return void_3}catch(error2){return hasErrorCode(error2,"ENOENT")||hasErrorCode(error2,"ENOTEMPTY")?void_3:fail6(new ProjectSettingsAccessFailure({cause:error2,message:`Failed to remove empty directory ${directoryPath}.`,operation:"write",path:directoryPath}))}}),removeTextFileIfContent:(filePath,expectedContent)=>suspend2(()=>{let recoveryDirectory;try{recoveryDirectory=mkdtempSync4(path26.join(path26.dirname(filePath),`.${path26.basename(filePath)}.hi-cleanup-`))}catch(error2){return isMissingFile2(error2)?succeed6(false):fail6(cleanupFailure(filePath,error2,`Failed to reserve cleanup recovery for ${filePath}.`))}const recoveryPath=path26.join(recoveryDirectory,"claimed");try{renameSync3(filePath,recoveryPath)}catch(error2){try{rmdirSync(recoveryDirectory)}catch{}return isMissingFile2(error2)?succeed6(false):fail6(cleanupFailure(filePath,error2,`Failed to claim ${filePath} for unchanged-content cleanup.`))}let content;try{content=readFileSync14(recoveryPath,"utf-8")}catch(error2){try{linkSync(recoveryPath,filePath)}catch{}return fail6(cleanupFailure(filePath,error2,`Failed to inspect claimed ${filePath}; claimed bytes remain at ${recoveryPath}.`))}if(content===expectedContent){try{unlinkSync(recoveryPath)}catch(error2){return fail6(cleanupFailure(filePath,error2,`Failed to remove unchanged ${filePath}; claimed bytes remain at ${recoveryPath}.`))}try{rmdirSync(recoveryDirectory);return succeed6(true)}catch(error2){return fail6(cleanupFailure(filePath,error2,`Removed unchanged ${filePath}, but failed to remove empty cleanup directory ${recoveryDirectory}.`))}}try{linkSync(recoveryPath,filePath);return succeed6(false)}catch(error2){return fail6(cleanupFailure(filePath,error2,`Failed to restore changed ${filePath}; claimed bytes remain at ${recoveryPath}.`))}}),writeTextFile:(filePath,content)=>try_3({catch:(cause)=>new ProjectSettingsAccessFailure({cause,message:`Failed to write ${filePath}.`,operation:"write",path:filePath}),try:()=>{mkdirSync9(path26.dirname(filePath),{recursive:true});writeFileSync9(filePath,content)}})});import{spawn as spawn2}from"node:child_process";import{createHash as createHash8}from"node:crypto";import{readFileSync as readFileSync15,realpathSync as realpathSync4}from"node:fs";import{mkdtemp as mkdtemp2,rm as rm2}from"node:fs/promises";import{tmpdir as tmpdir7}from"node:os";import path27 from"node:path";var minimumSkillsCliVersion="1.5.20";var operatorSkillOrigin="https://github.com/wearedevpunks/skills.git";var operatorSkillRelativePath=path27.join("skills","agnostic","cli","hi-cli");var sha256Pattern=/^[0-9a-f]{64}$/u;var terminationGraceMs=250;class SkillsCliProcessTreeCleanupDefectError extends Error{_tag="SkillsCliProcessTreeCleanupDefect";constructor(message){super(message);this.name="SkillsCliProcessTreeCleanupDefectError"}}var defaultProcessTreeOptions={platform:process.platform,taskkillExecutable:"taskkill"};var listedSkillSchema=ArraySchema(Struct({agents:ArraySchema(String5),name:String5,path:String5,scope:Literals(["project","global"])}));var normalizeAgent=(agent)=>agent.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");var scopeArguments=(scope3)=>scope3==="global"?["--global"]:[];var failureContext=(operation2,request3)=>({agent:request3.agent,operation:operation2,scope:request3.scope});var parseVersion2=(value5)=>{const match8=/^v?(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)$/u.exec(value5.trim());return match8===null?undefined:[Number(match8[1]),Number(match8[2]),Number(match8[3])]};var compareVersions3=(left,right)=>{for(const index2 of[0,1,2]){const difference3=left[index2]-right[index2];if(difference3!==0){return difference3}}return 0};var isContainedPath=(root,candidate)=>{const relative=path27.relative(root,candidate);return relative!==".."&&!relative.startsWith(`..${path27.sep}`)&&!path27.isAbsolute(relative)};var terminateProcessTree=(child,options4,onTerminated)=>{const{pid}=child;if(pid===undefined){child.kill("SIGKILL");onTerminated({_tag:"CleanupFailed",message:"Skills CLI process cleanup could not identify the direct child"});return()=>{}}if(options4.platform==="win32"){let completed2=false;let fallback;let taskkill;const listeners={stopChild:()=>{},stopTaskkill:()=>{}};const cleanup=()=>{listeners.stopChild();listeners.stopTaskkill();if(fallback!==undefined){clearTimeout(fallback)}};const finish2=(termination)=>{if(completed2){return}completed2=true;cleanup();onTerminated(termination)};const onDirectChildClose=()=>{finish2({_tag:"CleanupFailed",message:"Windows process-tree cleanup failed; only the direct child exit was verified"})};const terminateDirectChild=(reason)=>{listeners.stopTaskkill();if(child.exitCode!==null||child.signalCode!==null){finish2({_tag:"CleanupFailed",message:`${reason}; only the direct child exit was verified`});return}child.once("close",onDirectChildClose);listeners.stopChild=()=>{child.removeListener("close",onDirectChildClose)};child.kill("SIGKILL");fallback=setTimeout(()=>{finish2({_tag:"CleanupFailed",message:`${reason}; direct child exit could not be verified`})},terminationGraceMs)};const onTaskkillError=(error2)=>{terminateDirectChild(`Windows process-tree cleanup failed: ${error2.message}`)};const onTaskkillClose=(status2)=>{if(status2===0){finish2({_tag:"TreeTerminated"});return}terminateDirectChild(`Windows process-tree cleanup exited with status ${status2??-1}`)};try{taskkill=spawn2(options4.taskkillExecutable,["/pid",String(pid),"/T","/F"],{shell:false,stdio:"ignore",windowsHide:true});taskkill.once("error",onTaskkillError);taskkill.once("close",onTaskkillClose);listeners.stopTaskkill=()=>{taskkill?.removeListener("error",onTaskkillError);taskkill?.removeListener("close",onTaskkillClose)}}catch(error2){terminateDirectChild(`Windows process-tree cleanup failed: ${error2 instanceof Error?error2.message:String(error2)}`)}return()=>{completed2=true;cleanup()}}let completed=false;let poll;const isRunning=()=>{try{process.kill(-pid,0);return true}catch(error2){return error2.code!=="ESRCH"}};const signal=(value5)=>{try{process.kill(-pid,value5)}catch(error2){if(error2.code!=="ESRCH"){child.kill(value5)}}};signal("SIGTERM");const escalation=setTimeout(()=>{signal("SIGKILL")},terminationGraceMs);const timers={};const finish=(termination)=>{if(completed){return}completed=true;clearTimeout(escalation);if(timers.deadline!==undefined){clearTimeout(timers.deadline)}if(poll!==undefined){clearImmediate(poll)}onTerminated(termination)};const awaitExit=()=>{if(!isRunning()){finish({_tag:"TreeTerminated"});return}poll=setImmediate(awaitExit)};timers.deadline=setTimeout(()=>{signal("SIGKILL");finish(isRunning()?{_tag:"CleanupFailed",message:"POSIX process-group cleanup did not complete before the termination deadline"}:{_tag:"TreeTerminated"})},terminationGraceMs*2);awaitExit();return()=>{completed=true;clearTimeout(escalation);if(timers.deadline!==undefined){clearTimeout(timers.deadline)}if(poll!==undefined){clearImmediate(poll)}}};var terminateChild=(child,processTree)=>callback2((resume)=>{const cancel=terminateProcessTree(child,processTree,(termination)=>{resume(succeed6(termination))});return sync2(cancel)}).pipe(flatMap4((termination)=>termination._tag==="CleanupFailed"?failCause3(combine2(interrupt2(),die2(new SkillsCliProcessTreeCleanupDefectError(termination.message)))):void_3));var makeSkillsCliLive=(options4)=>{const executable=options4.executable??"skills";const gitExecutable=options4.gitExecutable??"git";const timeoutEnabled=options4.timeoutMs!==false;const timeoutMs=typeof options4.timeoutMs==="number"?options4.timeoutMs:30000;const{environment}=options4;const processTree=options4.processTree??defaultProcessTreeOptions;const removeTemporaryDirectory=options4.removeTemporaryDirectory??((directory3)=>rm2(directory3,{force:true,recursive:true}));const temporaryDirectoryRoot=options4.temporaryDirectoryRoot??tmpdir7();const runCommand=fn2("SkillsCli.runCommand")(function*runCommand(operation2,request3,command,args2,cwd,commandLabel){const result4=yield*callback2((resume)=>{let child;try{child=spawn2(command,args2,{cwd,detached:true,env:environment,shell:false,stdio:["ignore","pipe","pipe"],windowsHide:true})}catch(error2){resume(succeed6({error:error2,status:null,stderr:"",stdout:""}));return}let completed=false;let timedOut=false;let stderr="";let stdout="";let cancelTermination;const finish=(processResult)=>{if(completed){return}completed=true;cancelTermination?.();resume(succeed6(processResult))};const timeout3=timeoutEnabled?setTimeout(()=>{timedOut=true;cancelTermination=terminateProcessTree(child,processTree,(termination)=>{const cleanupFailed=termination._tag==="CleanupFailed";finish({error:Object.assign(new Error(cleanupFailed?termination.message:`${commandLabel} ${operation2} timed out`),{code:cleanupFailed?"EPROCESSTREE":"ETIMEDOUT"}),status:null,stderr,stdout})})},timeoutMs):undefined;child.stdout?.setEncoding("utf-8");child.stderr?.setEncoding("utf-8");child.stdout?.on("data",(chunk)=>{stdout+=chunk});child.stderr?.on("data",(chunk)=>{stderr+=chunk});child.once("error",(error2)=>{if(timeout3!==undefined){clearTimeout(timeout3)}finish({error:error2,status:null,stderr,stdout})});child.once("close",(status2)=>{if(!timedOut){if(timeout3!==undefined){clearTimeout(timeout3)}finish({status:status2,stderr,stdout})}});return sync2(()=>{if(timeout3!==undefined){clearTimeout(timeout3)}}).pipe(andThen2(terminateChild(child,processTree)))});const context4=failureContext(operation2,request3);const code=result4.error?.code;if(code==="ENOENT"){return yield*new SkillsCliUnavailable({...context4,executable:command,message:`${commandLabel} executable is unavailable: ${command}`})}if(code==="ETIMEDOUT"){return yield*new SkillsCliTimeout({...context4,message:`${commandLabel} ${operation2} timed out after ${timeoutMs}ms`,timeoutMs})}if(code==="EPROCESSTREE"){return yield*new SkillsCliExit({...context4,exitCode:-1,message:`${commandLabel} ${operation2} process cleanup failed`,stderr:result4.error?.message??""})}if(result4.error!==undefined||result4.status!==0){return yield*new SkillsCliExit({...context4,exitCode:result4.status??-1,message:`${commandLabel} ${operation2} exited unsuccessfully`,stderr:result4.stderr||result4.error?.message||""})}return result4.stdout});const run6=(operation2,request3,args2)=>runCommand(operation2,request3,executable,args2,request3.cwd,"Skills CLI");const runGit=(request3,args2,cwd)=>runCommand("install",request3,gitExecutable,args2,cwd,"Git");const temporaryDirectoryFailure=(request3,message,cause)=>new SkillsCliExit({...failureContext("install",request3),exitCode:-1,message,stderr:cause instanceof Error?cause.message:String(cause)});const withMaterializedTarget=(request3,use)=>acquireUseRelease2(tryPromise2({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot create a temporary operator-skill checkout",cause),try:()=>mkdtemp2(path27.join(temporaryDirectoryRoot,"hi-operator-skill-"))}),(temporaryRoot)=>gen2(function*materializeTarget(){const checkoutRoot=path27.join(temporaryRoot,"source");yield*runGit(request3,["init",checkoutRoot],request3.cwd);yield*runGit(request3,["remote","add","origin",operatorSkillOrigin],checkoutRoot);yield*runGit(request3,["fetch","--depth=1","origin",request3.target.revision],checkoutRoot);const fetchedRevision=(yield*runGit(request3,["rev-parse","FETCH_HEAD^{commit}"],checkoutRoot)).trim();if(fetchedRevision!==request3.target.revision){return yield*new SkillsCliMalformedOutput({...failureContext("install",request3),message:"Git fetched an unexpected operator-skill revision",stdout:fetchedRevision})}yield*runGit(request3,["checkout","--detach","FETCH_HEAD"],checkoutRoot);const canonicalCheckout=yield*try_3({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot resolve the temporary operator-skill checkout",cause),try:()=>realpathSync4(checkoutRoot)});const localSource=yield*try_3({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot resolve the materialized operator-skill source",cause),try:()=>realpathSync4(path27.join(canonicalCheckout,operatorSkillRelativePath))});if(!isContainedPath(canonicalCheckout,localSource)){return yield*new SkillsCliMalformedOutput({...failureContext("install",request3),message:"Materialized operator-skill source escapes the checkout",stdout:localSource})}return yield*use(localSource)}),(temporaryRoot)=>tryPromise2({catch:(cause)=>temporaryDirectoryFailure(request3,"Cannot clean up the temporary operator-skill checkout",cause),try:()=>removeTemporaryDirectory(temporaryRoot)}));const ensureSupportedVersion=fn2("SkillsCli.ensureSupportedVersion")(function*ensureSupportedVersion(operation2,request3){const stdout=yield*run6(operation2,request3,["--version"]);const version3=parseVersion2(stdout);if(version3===undefined){return yield*new SkillsCliMalformedOutput({...failureContext(operation2,request3),message:"Skills CLI returned a malformed version",stdout})}const minimumVersion=parseVersion2(minimumSkillsCliVersion);if(compareVersions3(version3,minimumVersion)<0){return yield*new SkillsCliUnsupportedVersion({...failureContext(operation2,request3),message:`Skills CLI ${minimumSkillsCliVersion} or newer is required`,minimumVersion:minimumSkillsCliVersion,version:stdout.trim()})}});const verifyListedSkill=(request3,skill,verifiedSkills)=>{const fail12=(reason,message)=>new SkillsCliVerificationFailure({...failureContext("list",request3),message,reason,skillName:skill.name,skillPath:skill.path,verifiedSkills});return gen2(function*verifySkillIdentity(){if(!path27.isAbsolute(skill.path)||path27.parse(skill.path).root===path27.normalize(skill.path)){return yield*fail12("unsafe-path",`Skills CLI reported an unsafe path for ${skill.name}`)}if(request3.target.contentManifest.length===0){return yield*fail12("malformed","Operator-skill content manifest is empty")}let canonicalRoot;try{canonicalRoot=realpathSync4(skill.path)}catch(error2){const{code}=error2;return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot resolve the CLI-reported ${skill.name} copy`)}const seenPaths=new Set;for(const entry of request3.target.contentManifest){const normalizedRelativePath=path27.normalize(entry.path);if(entry.path===""||path27.isAbsolute(entry.path)||normalizedRelativePath===".."||normalizedRelativePath.startsWith(`..${path27.sep}`)||!sha256Pattern.test(entry.sha256)||seenPaths.has(normalizedRelativePath)){return yield*fail12("malformed","Operator-skill content manifest is malformed")}seenPaths.add(normalizedRelativePath);const filePath=path27.resolve(skill.path,normalizedRelativePath);if(!isContainedPath(path27.resolve(skill.path),filePath)){return yield*fail12("unsafe-path","Operator-skill manifest escapes the reported path")}let canonicalFilePath;try{canonicalFilePath=realpathSync4(filePath)}catch(error2){const{code}=error2;return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot resolve ${entry.path} from the CLI-reported ${skill.name} copy`)}if(!isContainedPath(canonicalRoot,canonicalFilePath)){return yield*fail12("unsafe-path",`${entry.path} escapes the CLI-reported copy`)}let content;try{content=readFileSync15(canonicalFilePath)}catch(error2){const{code}=error2;return yield*fail12(code==="ENOENT"?"missing":"unreadable",`Cannot read ${entry.path} from the CLI-reported ${skill.name} copy`)}const actualSha256=createHash8("sha256").update(content).digest("hex");if(actualSha256!==entry.sha256){return yield*fail12("identity-mismatch",`CLI-reported ${skill.name} content does not match the immutable target`)}}return{...skill,cliCompatibility:request3.target.cliCompatibility,revision:request3.target.revision,source:request3.target.source,version:request3.target.version}})};const list2=fn2("SkillsCli.list")(function*list(request3){yield*ensureSupportedVersion("list",request3);const stdout=yield*run6("list",request3,["list",...scopeArguments(request3.scope),"--agent",request3.agent,"--json"]);const decoded=yield*try_3({catch:()=>new SkillsCliMalformedOutput({...failureContext("list",request3),message:"Skills CLI list returned malformed JSON",stdout}),try:()=>decodeUnknownSync2(listedSkillSchema)(JSON.parse(stdout))});const normalized=decoded.map((skill)=>({...skill,agents:skill.agents.map(normalizeAgent).toSorted()}));if(normalized.some((skill)=>skill.scope!==request3.scope)){return yield*new SkillsCliMalformedOutput({...failureContext("list",request3),message:`Skills CLI list returned a scope other than ${request3.scope}`,stdout})}const requestedAgent=normalizeAgent(request3.agent);const listed=[];const verified=()=>listed.filter((skill)=>("version"in skill));let unbound;for(const skill of normalized){if(skill.name!=="hi-cli"){listed.push(skill);continue}if(!skill.agents.includes(requestedAgent)){unbound??=skill;continue}const verification=yield*result2(verifyListedSkill(request3,skill,verified()));if(isFailure2(verification)){if(verification.failure.reason==="identity-mismatch"){listed.push({...skill,name:"hi-cli",verification:"outdated"});continue}return yield*verification.failure}listed.push(verification.success)}if(unbound!==undefined){return yield*new SkillsCliBindingFailure({...failureContext("list",request3),message:`Skills CLI listed ${unbound.name} without the active agent binding`,reportedAgents:unbound.agents,skillName:unbound.name,verifiedSkills:verified()})}return listed});const install=fn2("SkillsCli.install")(function*install(request3){yield*ensureSupportedVersion("install",request3);yield*withMaterializedTarget(request3,(localSource)=>run6("install",request3,["add",localSource,"--skill","hi-cli",...scopeArguments(request3.scope),"--agent",request3.agent,"--yes","--copy"]))});const remove7=fn2("SkillsCli.remove")(function*remove(request3){yield*ensureSupportedVersion("remove",request3);yield*run6("remove",request3,["remove",request3.name,...scopeArguments(request3.scope),"--agent",request3.agent,"--yes"])});return succeed5(SkillsCli,{install,list:list2,remove:remove7})};var startupCheckWorkerEnv="HI_STARTUP_CHECK_WORKER";var startupCheckCliEnv="HI_STARTUP_CHECK_CLI";var startupCheckSkillEnv="HI_STARTUP_CHECK_SKILL";var processEnvironment=process.env;var processProvider=makeEnvironmentProvider(processEnvironment);var startupCheckCacheFile=path28.join(homedir3(),".cache","hi","startup-check.json");var effectBuiltIns=exports_GlobalFlag.BuiltIns.filter((flag)=>flag!==exports_GlobalFlag.Wizard);var rootCommands=commandRegistry.command.subcommands.flatMap(({commands:commands2})=>commands2);var rootCommandNames=rootCommands.map(({name:commandName})=>commandName);var forceColorEnvironment=(runtime)=>{if(runtime.commandEnvironment.FORCE_COLOR==="0"){return{FORCE_COLOR:"0"}}if(runtime.forceColor){return{FORCE_COLOR:"1"}}return{}};var makeRootRenderEnvironment=(runtime,mode)=>makeHumanRenderEnvironment({columns:process.stdout.columns,environment:{...runtime.colorForegroundBackground===undefined?{}:{COLORFGBG:runtime.colorForegroundBackground},...forceColorEnvironment(runtime),...runtime.noColor?{NO_COLOR:"1"}:{},...runtime.terminalTheme===undefined?{}:{HI_THEME:runtime.terminalTheme}},mode,stdoutIsTTY:process.stdout.isTTY===true});var renderRootCommandGuide=(runtime,mode)=>renderRootScreen(renderCommandGuide(commandRegistry.discovery),makeRootRenderEnvironment(runtime,mode));var makeWizardGlobalFlag=(runtime)=>exports_GlobalFlag.action({flag:exports_Flag.boolean("wizard").pipe(exports_Flag.withDescription("Show the interactive command guide")),run:()=>sync2(()=>{const mode=selectOutputMode({jsonSelected:false,stdinIsTTY:process.stdin.isTTY===true,stdoutIsTTY:process.stdout.isTTY===true});process.stdout.write(renderRootCommandGuide(runtime,mode==="interactive"?mode:"plain"))})});var makeRootCommand=(runtime)=>commandRegistry.command.pipe(exports_Command.withGlobalFlags([makeWizardGlobalFlag(runtime)]));var isRootHelpAction=(nativeAction)=>nativeAction==="--help"||nativeAction==="-h";var isHelpArgument=(argument)=>argument==="--help"||argument.startsWith("--help=")||/^-[^-]*h/u.test(argument)&&argument!=="-";var classifyRootHelp=(commandArguments,nativeAction)=>{if(!isRootHelpAction(nativeAction)){return"none"}if(commandArguments.length===1&&(commandArguments[0]==="--help"||commandArguments[0]==="-h")){return"exact"}const helpIndex=commandArguments.findIndex(isHelpArgument);const rootCommandIndex=commandArguments.findIndex((argument)=>rootCommandNames.includes(argument));return rootCommandIndex!==-1&&rootCommandIndex<helpIndex?"nested":"invalid"};var defaultCliFormatter=exports_CliOutput.defaultFormatter();var cliOutputLayer=exports_CliOutput.layer({...defaultCliFormatter,formatVersion:(_name,currentVersion)=>`${currentVersion}
1548
1548
  `});var jsonCliFormatter={...defaultCliFormatter,formatCliError:()=>"",formatError:()=>"",formatErrors:()=>"",formatHelpDoc:()=>""};var jsonCliConsole=Object.assign(Object.create(globalThis.console),{error:(...args2)=>{if(args2.length!==1||args2[0]!==""){globalThis.console.error(...args2)}},log:(...args2)=>{if(args2.length!==1||args2[0]!==""){globalThis.console.log(...args2)}}});var cliArgv=process.argv.length===3&&process.argv[2]==="-v"?[...process.argv.slice(0,2),"--version"]:process.argv;var flattenCommandRegistrations=(registrations)=>registrations.flatMap((registration2)=>[registration2,...flattenCommandRegistrations(registration2.children)]);var commandOptionDescriptors=new Map(flattenCommandRegistrations(commandRegistry.registrations).map(({command,metadata})=>{const help=command.buildHelpDoc(metadata.path);return[metadata.path.join(" "),new Map(help.flags.flatMap(({aliases,name:optionName2,type:type2})=>{const canonicalOption=`--${optionName2}`;const descriptor={canonicalOption,takesValue:type2!=="boolean"};return[[canonicalOption,descriptor],...aliases.map((alias)=>[alias,descriptor])]}))]}));var rootOptionDescriptors=(rootCommand2)=>{const declaredFlags=rootCommand2.globalFlags;const globalFlags=[...new Set([...effectBuiltIns,...declaredFlags])];return new Map(globalFlags.flatMap((globalFlag)=>{const help=exports_Command.make("global-option-metadata",{value:globalFlag.flag}).buildHelpDoc([]);return help.flags.flatMap(({aliases,name:optionName2,type:type2})=>{const canonicalOption=`--${optionName2}`;const descriptor={canonicalOption,...globalFlag._tag==="Action"?{nativeAction:true}:{},takesValue:type2!=="boolean"};return[[canonicalOption,descriptor],...aliases.map((alias)=>[alias,descriptor])]})}))};var commandOptionsForArguments=(arguments_)=>{const[command]=commandRegistry.reference.filter(({path:registeredPath})=>registeredPath.every((segment,index2)=>arguments_[index2]===segment)).toSorted((left,right)=>right.path.length-left.path.length);return command===undefined?new Map:commandOptionDescriptors.get(command.path.join(" "))??new Map};var commandHelpForArguments=(arguments_)=>{const[commandPath]=commandRegistry.reference.map(({path:registeredPath})=>registeredPath).filter((registeredPath)=>registeredPath.every((segment,index2)=>arguments_[index2]===segment)).toSorted((left,right)=>right.length-left.length);return`${commandPath===undefined?"hi":commandPath.join(" ")} --help`};var shouldCheckSelfUpdate=(runtime)=>runtime.updateChecksEnabled&&process.argv.includes("--help")===false&&process.argv.includes("-h")===false&&process.argv.includes("--version")===false&&process.argv.includes("-v")===false;var shouldCheckHiCliSkillUpdate=(runtime)=>runtime.skillUpdateChecksEnabled&&process.argv.includes("--help")===false&&process.argv.includes("-h")===false&&process.argv.includes("--version")===false&&process.argv.includes("-v")===false;var shouldAskForSelfUpdate=(runtime,outputMode)=>shouldCheckSelfUpdate(runtime)&&process.argv.slice(2).includes("upgrade")===false&&outputMode!=="json"&&process.stdin.isTTY===true&&process.stdout.isTTY===true;var formatCommand=({command,environment})=>{const envPrefix=environment===undefined?[]:Object.entries(environment).map(([key,value5])=>`${key}=${value5}`);return[...envPrefix,...command].join(" ")};var askYesNo=async(question)=>{const readline2=createInterface3({input:process.stdin,output:process.stdout});try{const response=await readline2.question(renderQuestion(`${question} [y/N]: `));const answer=response.trim();return answer.toLowerCase()==="y"||answer.toLowerCase()==="yes"}finally{readline2.close()}};var isPromptAbort=(error2)=>error2 instanceof Error&&error2.name==="AbortError";var runInteractiveCliUpdate=async(runtime,outputMode)=>{if(!shouldAskForSelfUpdate(runtime,outputMode)){return false}const result4=await autoUpdateCliIfStale({currentVersion:version2,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:runtime.updateTag,timeoutMs:5000});if(result4.status==="current"||result4.status==="unavailable"){return false}if(result4.check===null){return false}if(result4.status!=="available"){const command="command"in result4?result4.command:null;console.error(renderSelfUpdateNotice({command,currentVersion:result4.check.currentVersion,latestVersion:result4.check.latestVersion,packageName:result4.check.packageName}));return false}console.error(renderSelfUpdateNotice({command:result4.command,currentVersion:result4.check.currentVersion,latestVersion:result4.check.latestVersion,packageName:result4.check.packageName}));if(!await askYesNo("Update CLI before running this command?")){return false}if(runCliInstallCommand({baseEnvironment:runtime.commandEnvironment,command:result4.command,environment:result4.environment})){console.log(renderCommandSection("CLI upgraded",[`${result4.check.packageName} ${result4.check.currentVersion} -> ${result4.check.latestVersion}`,`Installer: ${result4.packageManager}`,`Command: ${formatCommand(result4)}`,"Re-run your command to use the upgraded CLI."].join(`
1549
1549
  `)));return true}console.error(renderCommandSection("CLI upgrade failed",`Command failed: ${formatCommand({command:result4.command})}`));process.exitCode=1;return true};var runCliUpdateCheck=async(runtime)=>{const result4=await autoUpdateCliIfStale({currentVersion:version2,packageName:name,runtime:{commandEnvironment:runtime.commandEnvironment,npmRegistry:runtime.npmRegistry,...runtime.npmUserAgent===undefined?{}:{npmUserAgent:runtime.npmUserAgent}},tag:runtime.updateTag});if(result4.status==="available"||result4.status==="manager-not-detected"||result4.status==="failed"){console.error(renderSelfUpdateNotice({command:result4.command,currentVersion:result4.check.currentVersion,latestVersion:result4.check.latestVersion,packageName:result4.check.packageName}))}};var runHiCliSkillCheck=runOperatorSkillApplication("status").pipe(tap2((result4)=>sync2(()=>{if(result4.lifecycle._tag==="Inspected"&&result4.lifecycle.installed._tag==="Absent"){console.error("hi startup checks: `hi-cli` skill not found. Run `hi operator install`, or `hi operator migrate` when legacy `dp-cli` is present.")}})),matchEffect3({onFailure:()=>void_3,onSuccess:()=>void_3}));var runStartupChecks=({checkCli,checkSkill,runtime})=>gen2(function*executeStartupChecks(){if(checkCli){yield*promise2(()=>runCliUpdateCheck(runtime))}if(checkSkill){yield*runHiCliSkillCheck}});var hasFreshStartupCheck=(runtime)=>{if(!Number.isFinite(runtime.startupCheckIntervalMs)||runtime.startupCheckIntervalMs<=0){return false}try{const parsed=JSON.parse(readFileSync16(startupCheckCacheFile,"utf-8"));return typeof parsed.checkedAt==="number"&&Date.now()-parsed.checkedAt<runtime.startupCheckIntervalMs}catch{return false}};var markStartupCheckStarted=()=>{mkdirSync10(path28.dirname(startupCheckCacheFile),{recursive:true});writeFileSync10(startupCheckCacheFile,JSON.stringify({checkedAt:Date.now()},null,2))};var startBackgroundStartupChecks=(runtime,outputMode)=>{const checkCli=shouldCheckSelfUpdate(runtime)&&!shouldAskForSelfUpdate(runtime,outputMode);const checkSkill=shouldCheckHiCliSkillUpdate(runtime);if(!checkCli&&!checkSkill||hasFreshStartupCheck(runtime)){return}const[,entrypoint]=process.argv;if(entrypoint===undefined||!existsSync16(entrypoint)){return}try{markStartupCheckStarted();const worker=spawn3(process.execPath,[entrypoint],{cwd:process.cwd(),detached:true,env:{...runtime.commandEnvironment,[startupCheckWorkerEnv]:"1",[startupCheckCliEnv]:checkCli?"1":"0",[startupCheckSkillEnv]:checkSkill?"1":"0"},stdio:["ignore","ignore","inherit"]});worker.once("error",()=>{});worker.unref()}catch{}};var main=gen2(function*main2(){const runtime=yield*CliRuntimeConfig;configureBrand({...runtime.colorForegroundBackground===undefined?{}:{colorForegroundBackground:runtime.colorForegroundBackground},forceColor:runtime.forceColor,forceColorDisabled:runtime.commandEnvironment.FORCE_COLOR==="0",noColor:runtime.noColor,...runtime.terminalTheme===undefined?{}:{terminalTheme:runtime.terminalTheme}});const rootCommand2=makeRootCommand(runtime);const cli=exports_Command.runWith(rootCommand2,{version:version2});const commandArguments=cliArgv.slice(2);const argumentScan=analyzeCliArguments({args:commandArguments,commandOptionsForArguments,rootOptions:rootOptionDescriptors(rootCommand2),stdinIsTTY:process.stdin.isTTY===true,stdoutIsTTY:process.stdout.isTTY===true});const outputMode=argumentScan.mode;const parsedArguments=argumentScan.arguments;if(runtime.startupWorker){yield*runStartupChecks({checkCli:runtime.startupCheckCli,checkSkill:runtime.startupCheckSkill,runtime});return}const stopBeforeCommand=yield*tryPromise2({catch:(cause)=>cause,try:()=>runInteractiveCliUpdate(runtime,outputMode)}).pipe(matchEffect3({onFailure:(error2)=>sync2(()=>{if(isPromptAbort(error2)){process.exitCode=130;return true}return false}),onSuccess:succeed6}));if(stopBeforeCommand){return}if(outputMode!=="json"){startBackgroundStartupChecks(runtime,outputMode)}const{nativeAction}=argumentScan;if(outputMode==="json"&&nativeAction!==undefined){process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"json-native-action",detail:`CLI-native action \`${nativeAction}\` does not support JSON output. Remove \`--json\` and retry.`,recoverable:true,subject:nativeAction},kind:"expected-failure"}});return}const{missingOption}=argumentScan;if(missingOption!==undefined){const normalizedOption=missingOption.replace(/^-+/u,"");process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"missing-command-input",detail:`Missing value for \`${missingOption}\`.`,recoverable:true,recoveryCommand:commandHelpForArguments(argumentScan.commandArguments),subject:normalizedOption},kind:"expected-failure"}});return}const rootHelpDisposition=classifyRootHelp(commandArguments,nativeAction);if(rootHelpDisposition==="exact"){process.stdout.write(renderRootCommandGuide(runtime,outputMode==="interactive"?outputMode:"plain"));return}if(rootHelpDisposition==="invalid"){process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"invalid-root-help-invocation",detail:"Root help accepts only `hi --help` or `hi -h`.",recoverable:true,recoveryCommand:"hi --help",subject:nativeAction??"--help"},kind:"expected-failure"}});return}if(parsedArguments.length===0){if(outputMode==="json"){process.exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,"plain"),mode:outputMode,outcome:{failure:{code:"missing-command",detail:"Choose a Harness command.",recoverable:true,recoveryCommand:"hi --help",subject:"command"},kind:"expected-failure"}});return}process.stdout.write(renderRootCommandGuide(runtime,outputMode==="interactive"?outputMode:"plain"));return}let capturedOutcome;const commandEffect=outputMode==="json"?cli(parsedArguments).pipe(provideService2(exports_CliOutput.Formatter,jsonCliFormatter),provideService2(Console,jsonCliConsole)):cli(parsedArguments);const outcome=yield*commandEffect.pipe(provideService2(SelectedOutputMode,outputMode),provideService2(RootPresentationSink,{publish:(publishedOutcome)=>sync2(()=>{capturedOutcome=publishedOutcome})}),match6({onFailure:presentationOutcome,onSuccess:()=>capturedOutcome}));if(outcome===undefined){return}const humanMode=outputMode==="interactive"?outputMode:"plain";const exitCode=present({humanEnvironment:makeRootRenderEnvironment(runtime,humanMode),mode:outputMode,outcome});if(exitCode!==0){process.exitCode=exitCode}});var cliConfigLayer=makeCliConfigLayer(processProvider,processEnvironment);var ProjectSettingsLive=ProjectSettingsDefault.pipe(provide2(ProjectSettingsFileSystemLive));var scaffoldCapabilitiesLive=scaffoldCapabilitiesLayer.pipe(provide2(cliConfigLayer));var skillsCliLive=makeSkillsCliLive({environment:processEnvironment});var featureApplicationDependencies=mergeAll2(exports_FetchHttpClient.layer,ProjectSettingsLive,cliConfigLayer,scaffoldCapabilitiesLive,skillsCliLive);var featureApplicationOperationsLive=featureApplicationOperationsLayer.pipe(provide2(featureApplicationDependencies));var mainLayer=mergeAll2(layer15,exports_CliConfig.layer({builtIns:effectBuiltIns}),exports_FetchHttpClient.layer,cliOutputLayer,cliPromptLayer,updateInteractionLayer.pipe(provide2(cliPromptLayer)),repositoryScaffoldingInteractionLayer.pipe(provide2(cliPromptLayer)),ProjectSettingsLive,cliConfigLayer,scaffoldCapabilitiesLive,repositoryCheckCapabilitiesLayer.pipe(provide2(merge2(cliConfigLayer,ProjectSettingsLive))),featureApplicationOperationsLive);if(__require.main==__require.module){main.pipe(provide4(mainLayer),runMain2)}export{rootCommands,rootCommandNames,main};