@unbrained/pm-cli 2026.10.3 → 2026.10.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (742) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +28 -2
  3. package/dist/cli/after-command-context-usage.js +1 -1
  4. package/dist/cli/argv-utils.js +1 -1
  5. package/dist/cli/bootstrap-args.js +1 -1
  6. package/dist/cli/bundle-integrity.js +2 -2
  7. package/dist/cli/command-namespaces.js +1 -1
  8. package/dist/cli/commander-usage.d.ts +1 -1
  9. package/dist/cli/commander-usage.js +7 -4
  10. package/dist/cli/commands/annotations/comments.js +1 -1
  11. package/dist/cli/commands/annotations/docs.js +1 -1
  12. package/dist/cli/commands/annotations/files.js +1 -1
  13. package/dist/cli/commands/annotations/learnings.js +1 -1
  14. package/dist/cli/commands/annotations/notes.js +1 -1
  15. package/dist/cli/commands/extension/describe.js +1 -1
  16. package/dist/cli/commands/extension/extension.js +1 -1
  17. package/dist/cli/commands/extension/scaffold.js +1 -1
  18. package/dist/cli/commands/extension/shared.js +1 -1
  19. package/dist/cli/commands/governance/gc.js +1 -1
  20. package/dist/cli/commands/governance/health.js +1 -1
  21. package/dist/cli/commands/governance/telemetry.js +1 -1
  22. package/dist/cli/commands/governance/validate.js +1 -1
  23. package/dist/cli/commands/history/activity.js +1 -1
  24. package/dist/cli/commands/history/history-compact.js +1 -1
  25. package/dist/cli/commands/history/history-redact.js +1 -1
  26. package/dist/cli/commands/history/history-repair.js +1 -1
  27. package/dist/cli/commands/history/history.js +1 -1
  28. package/dist/cli/commands/history/restore.js +1 -1
  29. package/dist/cli/commands/lifecycle/append.js +1 -1
  30. package/dist/cli/commands/lifecycle/claim.js +1 -1
  31. package/dist/cli/commands/lifecycle/close-many.js +1 -1
  32. package/dist/cli/commands/lifecycle/close.js +1 -1
  33. package/dist/cli/commands/lifecycle/copy.js +1 -1
  34. package/dist/cli/commands/lifecycle/create.js +1 -1
  35. package/dist/cli/commands/lifecycle/delete.js +1 -1
  36. package/dist/cli/commands/lifecycle/focus.js +1 -1
  37. package/dist/cli/commands/lifecycle/plan.js +1 -1
  38. package/dist/cli/commands/lifecycle/update-many.js +1 -1
  39. package/dist/cli/commands/lifecycle/update.js +1 -1
  40. package/dist/cli/commands/query/aggregate.js +1 -1
  41. package/dist/cli/commands/query/context.js +1 -1
  42. package/dist/cli/commands/query/deps.js +1 -1
  43. package/dist/cli/commands/query/duplicates.js +1 -1
  44. package/dist/cli/commands/query/eval.js +1 -1
  45. package/dist/cli/commands/query/get.js +1 -1
  46. package/dist/cli/commands/query/graph.js +1 -1
  47. package/dist/cli/commands/query/list.js +1 -1
  48. package/dist/cli/commands/query/next.js +1 -1
  49. package/dist/cli/commands/query/search.js +1 -1
  50. package/dist/cli/commands/query/stats.js +1 -1
  51. package/dist/cli/commands/test/test-all.js +1 -1
  52. package/dist/cli/commands/test/test-runs.js +1 -1
  53. package/dist/cli/commands/test/test.js +1 -1
  54. package/dist/cli/commands/workspace/config.js +1 -1
  55. package/dist/cli/commands/workspace/contracts.js +1 -1
  56. package/dist/cli/commands/workspace/init.js +1 -1
  57. package/dist/cli/commands/workspace/merge.js +1 -1
  58. package/dist/cli/commands/workspace/profile.js +1 -1
  59. package/dist/cli/commands/workspace/schema.js +1 -1
  60. package/dist/cli/commands/workspace/upgrade.js +1 -1
  61. package/dist/cli/context-intent-invocation.js +1 -1
  62. package/dist/cli/description-stdin.js +1 -1
  63. package/dist/cli/error-guidance.js +3 -1
  64. package/dist/cli/extension-command-help.js +5 -3
  65. package/dist/cli/extension-command-options.js +1 -1
  66. package/dist/cli/extension-recovery.js +1 -1
  67. package/dist/cli/help-content.js +5 -2
  68. package/dist/cli/help-json-payload.js +6 -3
  69. package/dist/cli/invocation-profile.js +2 -2
  70. package/dist/cli/main.js +5 -5
  71. package/dist/cli/migration-gates.js +1 -1
  72. package/dist/cli/option-values.js +1 -1
  73. package/dist/cli/public.js +1 -1
  74. package/dist/cli/register-annotations.js +1 -1
  75. package/dist/cli/register-assurance.js +1 -1
  76. package/dist/cli/register-files-lookup.js +1 -1
  77. package/dist/cli/register-history-activity.js +1 -1
  78. package/dist/cli/register-history-author.js +1 -1
  79. package/dist/cli/register-history-maintenance.js +2 -2
  80. package/dist/cli/register-list-query.js +10 -10
  81. package/dist/cli/register-mutation-options.js +1 -1
  82. package/dist/cli/register-mutation.js +2 -2
  83. package/dist/cli/register-operations.js +1 -1
  84. package/dist/cli/register-setup.js +1 -1
  85. package/dist/cli/register-structured-mutation.js +1 -1
  86. package/dist/cli/registration-helpers.js +1 -1
  87. package/dist/cli/runtime/activation.js +1 -1
  88. package/dist/cli/runtime/invocation-options.js +1 -1
  89. package/dist/cli/runtime/projection-retry.js +1 -1
  90. package/dist/cli/runtime/selection.js +1 -1
  91. package/dist/cli/runtime/telemetry-outcome.js +1 -1
  92. package/dist/cli/runtime-compatibility-boundary.d.ts +1 -1
  93. package/dist/cli/runtime-compatibility-boundary.js +4 -4
  94. package/dist/cli/schema/registration.js +2 -2
  95. package/dist/cli/schema-registration-helpers.js +1 -1
  96. package/dist/cli/search-refresh.js +1 -1
  97. package/dist/cli/stats-analytics-json.js +1 -1
  98. package/dist/cli/telemetry-flush.js +1 -1
  99. package/dist/cli-bundle/bundle-manifest.json +162 -162
  100. package/dist/cli-bundle/chunks/chunk-3CYOBJUK.js +3 -0
  101. package/dist/cli-bundle/chunks/chunk-5MNOWZPN.js +3 -0
  102. package/dist/cli-bundle/chunks/chunk-AJ7H6XUF.js +20 -0
  103. package/dist/cli-bundle/chunks/chunk-D332RXZ7.js +80 -0
  104. package/dist/cli-bundle/chunks/chunk-HRJ6G6ZG.js +31 -0
  105. package/dist/cli-bundle/chunks/chunk-KRVI56QE.js +6 -0
  106. package/dist/cli-bundle/chunks/chunk-N4YGSG6F.js +238 -0
  107. package/dist/cli-bundle/chunks/chunk-OOLYASYJ.js +2 -0
  108. package/dist/cli-bundle/chunks/chunk-R7CG2DB7.js +2 -0
  109. package/dist/cli-bundle/chunks/chunk-TGMONGWX.js +2 -0
  110. package/dist/cli-bundle/chunks/chunk-UZ7BIUCI.js +2 -0
  111. package/dist/cli-bundle/chunks/{chunk-44UGMMQ6.js → chunk-VZ63DEVJ.js} +3 -3
  112. package/dist/cli-bundle/chunks/chunk-WFZ4UEOB.js +2 -0
  113. package/dist/cli-bundle/chunks/chunk-YVBRASXO.js +8 -0
  114. package/dist/cli-bundle/chunks/{chunk-5XKF5SQV.js → chunk-Z66DWDAU.js} +91 -91
  115. package/dist/cli-bundle/chunks/{register-list-query-DYCGUQEW.js → register-list-query-75QXHIFH.js} +11 -11
  116. package/dist/cli-bundle/chunks/register-mutation-YS54SCHG.js +20 -0
  117. package/dist/cli-bundle/chunks/register-operations-6KHZQSYJ.js +2 -0
  118. package/dist/cli-bundle/chunks/register-setup-RTATEN2M.js +2 -0
  119. package/dist/cli-bundle/focused-chunks/{chunk-3BIYG72P.js → chunk-2CVX3KR3.js} +2 -2
  120. package/dist/cli-bundle/focused-chunks/chunk-5C3IDDW7.js +2 -0
  121. package/dist/cli-bundle/focused-chunks/{chunk-DBD4W4QP.js → chunk-ABV67XCC.js} +3 -3
  122. package/dist/cli-bundle/focused-chunks/chunk-B5RSLVE6.js +3 -0
  123. package/dist/cli-bundle/focused-chunks/chunk-C224METM.js +20 -0
  124. package/dist/cli-bundle/focused-chunks/chunk-CLDPTMQY.js +6 -0
  125. package/dist/cli-bundle/focused-chunks/chunk-DDRN42PB.js +8 -0
  126. package/dist/cli-bundle/focused-chunks/{chunk-EJN7DY3B.js → chunk-DOVTUKJQ.js} +2 -2
  127. package/dist/cli-bundle/focused-chunks/chunk-ECBOPEJE.js +75 -0
  128. package/dist/cli-bundle/focused-chunks/chunk-GITOYRUW.js +165 -0
  129. package/dist/cli-bundle/focused-chunks/chunk-GUIF3WVC.js +30 -0
  130. package/dist/cli-bundle/focused-chunks/chunk-LE4JUCRR.js +3 -0
  131. package/dist/cli-bundle/focused-chunks/{chunk-HFAW3FJQ.js → chunk-PSXFFQFT.js} +2 -2
  132. package/dist/cli-bundle/focused-chunks/chunk-RHIH6XIW.js +12 -0
  133. package/dist/cli-bundle/focused-chunks/chunk-UDYRVBOZ.js +2 -0
  134. package/dist/cli-bundle/focused-chunks/chunk-XV5RV4ZT.js +2 -0
  135. package/dist/cli-bundle/focused-chunks/{chunk-XRSCIYHR.js → chunk-YMU42COG.js} +2 -2
  136. package/dist/cli-bundle/main.js +28 -28
  137. package/dist/cli-bundle/sdk-authoring.js +1 -1
  138. package/dist/cli-bundle/sdk-contracts.js +2 -2
  139. package/dist/cli-bundle/sdk-core.js +32 -32
  140. package/dist/cli-bundle/sdk-governance.js +1 -1
  141. package/dist/cli-bundle/sdk-graph.js +1 -1
  142. package/dist/cli-bundle/sdk-merge.js +55 -55
  143. package/dist/cli-bundle/sdk-query.js +1 -1
  144. package/dist/cli-bundle/sdk-runtime.js +1 -1
  145. package/dist/cli-bundle/sdk-testing.js +1 -1
  146. package/dist/cli-bundle/sdk.js +10 -10
  147. package/dist/cli.js +1 -1
  148. package/dist/core/checkpoint/checkpoint-gc.js +1 -1
  149. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  150. package/dist/core/config/nested-settings.js +1 -1
  151. package/dist/core/config/positional-value.js +1 -1
  152. package/dist/core/diagnostics/remediation.js +1 -1
  153. package/dist/core/extensions/activation-summary-markdown.js +2 -1
  154. package/dist/core/extensions/activation-summary.js +1 -1
  155. package/dist/core/extensions/activation-transaction.js +1 -1
  156. package/dist/core/extensions/capability-usage.js +1 -1
  157. package/dist/core/extensions/command-hook-context.js +1 -1
  158. package/dist/core/extensions/command-metadata-contract.js +1 -1
  159. package/dist/core/extensions/command-visibility-tier.js +1 -1
  160. package/dist/core/extensions/contribution-inventory.js +1 -1
  161. package/dist/core/extensions/exporter-output-contract.js +1 -1
  162. package/dist/core/extensions/extension-candidate.js +1 -1
  163. package/dist/core/extensions/extension-capability-aliases.js +1 -1
  164. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  165. package/dist/core/extensions/extension-policy.js +1 -1
  166. package/dist/core/extensions/extension-registries.js +1 -1
  167. package/dist/core/extensions/extension-runtime-helpers.js +1 -1
  168. package/dist/core/extensions/extension-types.d.ts +8 -1
  169. package/dist/core/extensions/extension-types.js +1 -1
  170. package/dist/core/extensions/flag-definition-validation.js +1 -1
  171. package/dist/core/extensions/flag-value-types.js +1 -1
  172. package/dist/core/extensions/index.js +1 -1
  173. package/dist/core/extensions/item-field-types.js +1 -1
  174. package/dist/core/extensions/item-fields.js +1 -1
  175. package/dist/core/extensions/loader.js +1 -1
  176. package/dist/core/extensions/manifest-parser.js +1 -1
  177. package/dist/core/extensions/manifest-schema.js +1 -1
  178. package/dist/core/extensions/module-graph-snapshot.js +1 -1
  179. package/dist/core/extensions/preflight-ownership.js +1 -1
  180. package/dist/core/extensions/registration-contracts.js +1 -1
  181. package/dist/core/extensions/registration-validation.js +1 -1
  182. package/dist/core/extensions/registration-values.js +1 -1
  183. package/dist/core/extensions/reserved-host-flags.js +1 -1
  184. package/dist/core/extensions/runtime-registrations.js +1 -1
  185. package/dist/core/extensions/service-ownership.js +1 -1
  186. package/dist/core/extensions/version-compat.js +1 -1
  187. package/dist/core/fs/atomic-create.js +1 -1
  188. package/dist/core/fs/fs-utils.js +2 -2
  189. package/dist/core/fs/host-environment-errors.js +1 -1
  190. package/dist/core/fs/index.js +1 -1
  191. package/dist/core/fs/path-utils.js +1 -1
  192. package/dist/core/governance/content-fields.js +1 -1
  193. package/dist/core/governance/issue-codes.js +1 -1
  194. package/dist/core/governance/metadata-coverage.js +1 -1
  195. package/dist/core/history/digest.js +1 -1
  196. package/dist/core/history/drift-cache.js +3 -3
  197. package/dist/core/history/drift-scan.d.ts +4 -0
  198. package/dist/core/history/drift-scan.js +1 -1
  199. package/dist/core/history/event-classification.js +1 -1
  200. package/dist/core/history/event-index.js +8 -7
  201. package/dist/core/history/history-compact-bulk.js +1 -1
  202. package/dist/core/history/history-diff.js +1 -1
  203. package/dist/core/history/history-rewrite.js +1 -1
  204. package/dist/core/history/history-storage-stats.js +1 -1
  205. package/dist/core/history/history-stream-policy.js +1 -1
  206. package/dist/core/history/history.js +2 -2
  207. package/dist/core/history/identity.js +1 -1
  208. package/dist/core/history/index.js +1 -1
  209. package/dist/core/history/operation-contract.js +1 -1
  210. package/dist/core/history/projection.js +1 -1
  211. package/dist/core/history/read.js +1 -1
  212. package/dist/core/history/replay.js +2 -1
  213. package/dist/core/history/tombstone.js +1 -1
  214. package/dist/core/history/version-address.js +1 -1
  215. package/dist/core/history/workspace-history.js +2 -2
  216. package/dist/core/io/body-file.js +1 -1
  217. package/dist/core/io/bulk-ids-input.js +2 -1
  218. package/dist/core/item/actionability.js +1 -1
  219. package/dist/core/item/dependency-reference.js +1 -1
  220. package/dist/core/item/id.js +1 -1
  221. package/dist/core/item/index.js +1 -1
  222. package/dist/core/item/item-format-version.js +1 -1
  223. package/dist/core/item/item-format.js +6 -4
  224. package/dist/core/item/item-record.js +1 -1
  225. package/dist/core/item/item-type-definition.js +1 -1
  226. package/dist/core/item/parent-reference-policy.js +1 -1
  227. package/dist/core/item/parse.js +8 -2
  228. package/dist/core/item/plan-lifecycle.js +1 -1
  229. package/dist/core/item/priority.js +1 -1
  230. package/dist/core/item/sprint-release-format.js +1 -1
  231. package/dist/core/item/status-filter.js +1 -1
  232. package/dist/core/item/status.js +1 -1
  233. package/dist/core/item/toon-decode.js +1 -1
  234. package/dist/core/item/type-registry.js +1 -1
  235. package/dist/core/item/type-synonyms.js +1 -1
  236. package/dist/core/lock/index.js +1 -1
  237. package/dist/core/lock/lock-gc.js +1 -1
  238. package/dist/core/lock/lock.js +3 -3
  239. package/dist/core/output/mutation-projection.js +1 -1
  240. package/dist/core/output/output-control.js +1 -1
  241. package/dist/core/output/output.js +22 -10
  242. package/dist/core/output/query-summary.js +1 -1
  243. package/dist/core/output/tabular.js +3 -1
  244. package/dist/core/packages/manifest.js +1 -1
  245. package/dist/core/packages/root.js +1 -1
  246. package/dist/core/policy/workflow-policy-schema.js +1 -1
  247. package/dist/core/policy/workflow-policy-store.js +1 -1
  248. package/dist/core/policy/workflow-policy.js +1 -1
  249. package/dist/core/profile/profile-describe.js +1 -1
  250. package/dist/core/profile/profile-lint.js +1 -1
  251. package/dist/core/profile/profile-plan.js +1 -1
  252. package/dist/core/profile/profile-presets.js +25 -1
  253. package/dist/core/reproducibility/context.js +1 -1
  254. package/dist/core/schema/fields-file.js +2 -2
  255. package/dist/core/schema/item-types-file.js +2 -2
  256. package/dist/core/schema/runtime-field-filters.js +1 -1
  257. package/dist/core/schema/runtime-field-values.js +1 -1
  258. package/dist/core/schema/runtime-schema.js +2 -2
  259. package/dist/core/schema/status-defs-file.js +2 -2
  260. package/dist/core/schema/status-token.js +1 -1
  261. package/dist/core/schema/type-inference.js +1 -1
  262. package/dist/core/schema/type-presets.js +1 -1
  263. package/dist/core/schema/type-workflows.js +1 -1
  264. package/dist/core/search/background-refresh.js +2 -2
  265. package/dist/core/search/bm25.js +1 -1
  266. package/dist/core/search/cache.js +2 -2
  267. package/dist/core/search/corpus.js +1 -1
  268. package/dist/core/search/embedding-batches.js +1 -1
  269. package/dist/core/search/eval-thresholds.js +1 -1
  270. package/dist/core/search/eval.js +1 -1
  271. package/dist/core/search/http-client.js +1 -1
  272. package/dist/core/search/providers.js +1 -1
  273. package/dist/core/search/relevance.js +1 -1
  274. package/dist/core/search/semantic-defaults.js +1 -1
  275. package/dist/core/search/staleness.js +1 -1
  276. package/dist/core/search/vector-stores.js +2 -2
  277. package/dist/core/search/vectorization-metadata.js +1 -1
  278. package/dist/core/sentry/helpers.js +1 -1
  279. package/dist/core/sentry/instrument.js +1 -1
  280. package/dist/core/session/session-state.js +1 -1
  281. package/dist/core/shared/agent-session-context.js +1 -1
  282. package/dist/core/shared/author.js +5 -1
  283. package/dist/core/shared/command-line.js +1 -1
  284. package/dist/core/shared/command-types.js +1 -1
  285. package/dist/core/shared/conflict-markers.js +1 -1
  286. package/dist/core/shared/constants.js +1 -1
  287. package/dist/core/shared/errors.js +1 -1
  288. package/dist/core/shared/html-entity-decode.js +1 -1
  289. package/dist/core/shared/index.js +1 -1
  290. package/dist/core/shared/item-metadata-contract.js +1 -1
  291. package/dist/core/shared/lazy-module.js +1 -1
  292. package/dist/core/shared/levenshtein.js +1 -1
  293. package/dist/core/shared/memo.js +1 -1
  294. package/dist/core/shared/numeric-parsers.js +1 -1
  295. package/dist/core/shared/option-alias-visibility.js +1 -1
  296. package/dist/core/shared/primitives.js +1 -1
  297. package/dist/core/shared/secret-rules.js +1 -1
  298. package/dist/core/shared/serial-queue.js +1 -1
  299. package/dist/core/shared/serialization.js +1 -1
  300. package/dist/core/shared/split-comma-list.js +1 -1
  301. package/dist/core/shared/text-normalization.js +1 -1
  302. package/dist/core/shared/time.js +2 -1
  303. package/dist/core/store/index.js +1 -1
  304. package/dist/core/store/item-format-migration.js +1 -1
  305. package/dist/core/store/item-metadata-cache.js +1 -1
  306. package/dist/core/store/item-metadata-query-index.js +7 -7
  307. package/dist/core/store/item-metadata-read-work.js +1 -1
  308. package/dist/core/store/item-store.js +1 -1
  309. package/dist/core/store/paths.js +1 -1
  310. package/dist/core/store/settings-concurrency.js +1 -1
  311. package/dist/core/store/settings-read-cache.js +1 -1
  312. package/dist/core/store/settings-validator.js +1 -1
  313. package/dist/core/store/settings.d.ts +11 -2
  314. package/dist/core/store/settings.js +3 -3
  315. package/dist/core/store/tracker-preflight.js +1 -1
  316. package/dist/core/telemetry/consent.js +2 -2
  317. package/dist/core/telemetry/observability.js +1 -1
  318. package/dist/core/telemetry/policy.js +1 -1
  319. package/dist/core/telemetry/read-sampling.js +2 -2
  320. package/dist/core/telemetry/runtime.js +9 -5
  321. package/dist/core/test/background-runs.js +3 -3
  322. package/dist/core/test/item-test-run-tracking.js +1 -1
  323. package/dist/core/test/run-selectors.js +1 -1
  324. package/dist/core/validate/estimate-defaults.js +1 -1
  325. package/dist/core/validate/fix-planning.js +1 -1
  326. package/dist/core/validate/linked-artifact-reference.js +1 -1
  327. package/dist/core/validate/missing-by-type.js +1 -1
  328. package/dist/core/validate/missing-link-owners.js +1 -1
  329. package/dist/core/validate/stale-file-classification.js +1 -1
  330. package/dist/mcp/http-server.js +6 -4
  331. package/dist/mcp/legacy-adapter.js +1 -1
  332. package/dist/mcp/runtime-capabilities.js +1 -1
  333. package/dist/mcp/server.js +4 -4
  334. package/dist/mcp/tool-definitions.js +1 -1
  335. package/dist/sdk/actionability.js +1 -1
  336. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  337. package/dist/sdk/agent/command-recovery.js +1 -1
  338. package/dist/sdk/agent/command-suggestions.js +1 -1
  339. package/dist/sdk/agent/create-option-policy.js +1 -1
  340. package/dist/sdk/agent/identity-config.js +1 -1
  341. package/dist/sdk/agent/item-addressing.js +1 -1
  342. package/dist/sdk/agent/refusal-closure-census.js +2 -1
  343. package/dist/sdk/agent/refusal-closure.js +1 -1
  344. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
  345. package/dist/sdk/agent/refusal-reachability.js +3 -1
  346. package/dist/sdk/agent/subcommand-recovery.js +1 -1
  347. package/dist/sdk/agent/task-transcript-contracts.js +1 -1
  348. package/dist/sdk/agent/tracker-preflight-contracts.js +1 -1
  349. package/dist/sdk/agent-capability-contracts.js +3 -1
  350. package/dist/sdk/agent-session-context.js +1 -1
  351. package/dist/sdk/annotations.js +1 -1
  352. package/dist/sdk/author-attribution.js +1 -1
  353. package/dist/sdk/authoring.js +1 -1
  354. package/dist/sdk/cli-bootstrap.js +1 -1
  355. package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -3
  356. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  357. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  358. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
  359. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  360. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  361. package/dist/sdk/cli-contracts/completeness.js +1 -1
  362. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  363. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  364. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -1
  365. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  366. package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
  367. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  368. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
  369. package/dist/sdk/cli-contracts/string-lists.js +1 -1
  370. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  371. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  372. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  373. package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -1
  374. package/dist/sdk/cli-contracts.js +1 -1
  375. package/dist/sdk/cli-program.js +1 -1
  376. package/dist/sdk/command-line.js +1 -1
  377. package/dist/sdk/comments.js +1 -1
  378. package/dist/sdk/compile-cache.js +1 -1
  379. package/dist/sdk/completion/bash.js +2 -1
  380. package/dist/sdk/completion/fish.js +13 -7
  381. package/dist/sdk/completion/shared.js +1 -1
  382. package/dist/sdk/completion/zsh.js +14 -8
  383. package/dist/sdk/completion.js +1 -1
  384. package/dist/sdk/compose.js +1 -1
  385. package/dist/sdk/config.js +1 -1
  386. package/dist/sdk/context/recency.js +1 -1
  387. package/dist/sdk/context/semantic-session-attribution.js +1 -1
  388. package/dist/sdk/context/usage-egress.js +1 -1
  389. package/dist/sdk/context/usage-ledger.js +6 -3
  390. package/dist/sdk/context-intent-contracts.js +1 -1
  391. package/dist/sdk/context-intent-runtime.js +1 -1
  392. package/dist/sdk/context-packing.js +1 -1
  393. package/dist/sdk/context-relevance.js +1 -1
  394. package/dist/sdk/context-signal-store.js +2 -2
  395. package/dist/sdk/context-usage.js +1 -1
  396. package/dist/sdk/contracts.js +1 -1
  397. package/dist/sdk/core-governance.js +1 -1
  398. package/dist/sdk/core.js +1 -1
  399. package/dist/sdk/corpus-shape.js +1 -1
  400. package/dist/sdk/define.js +1 -1
  401. package/dist/sdk/dependencies.js +1 -1
  402. package/dist/sdk/dependency-flag-validation.js +1 -1
  403. package/dist/sdk/dependency-provenance.js +1 -1
  404. package/dist/sdk/docs.js +1 -1
  405. package/dist/sdk/duplicates.js +1 -1
  406. package/dist/sdk/environment/agent-environment.js +1 -1
  407. package/dist/sdk/environment/host-environment-errors.js +1 -1
  408. package/dist/sdk/environment/project-runtime-compatibility.js +2 -1
  409. package/dist/sdk/environment/source-context.js +1 -1
  410. package/dist/sdk/environment/tracker-preflight.js +1 -1
  411. package/dist/sdk/error-code-catalog.js +1 -1
  412. package/dist/sdk/error-runtime.js +1 -1
  413. package/dist/sdk/errors.js +1 -1
  414. package/dist/sdk/eval.js +1 -1
  415. package/dist/sdk/extension/author-manifest.js +1 -1
  416. package/dist/sdk/extension/bundled-catalog.js +1 -1
  417. package/dist/sdk/extension/concurrency.js +1 -1
  418. package/dist/sdk/extension/copy-scope.js +1 -1
  419. package/dist/sdk/extension/custom-field-collisions.js +1 -1
  420. package/dist/sdk/extension/describe.js +4 -2
  421. package/dist/sdk/extension/doctor.js +1 -1
  422. package/dist/sdk/extension/install-plan.js +1 -1
  423. package/dist/sdk/extension/install-receipts.js +1 -1
  424. package/dist/sdk/extension/install-runtime.js +3 -3
  425. package/dist/sdk/extension/install-snapshot.js +1 -1
  426. package/dist/sdk/extension/install-sources.js +5 -5
  427. package/dist/sdk/extension/managed-state.js +2 -2
  428. package/dist/sdk/extension/migrations.js +2 -2
  429. package/dist/sdk/extension/output-ownership.js +1 -1
  430. package/dist/sdk/extension/runtime-summary.js +1 -1
  431. package/dist/sdk/extension/scaffold.js +11 -4
  432. package/dist/sdk/extension/shared.js +1 -1
  433. package/dist/sdk/extension/source-resolution.js +1 -1
  434. package/dist/sdk/extension/static-inventory.js +1 -1
  435. package/dist/sdk/extension/update-check.js +1 -1
  436. package/dist/sdk/extension-command-context.js +1 -1
  437. package/dist/sdk/extension-contracts.js +1 -1
  438. package/dist/sdk/extension.js +1 -1
  439. package/dist/sdk/files.js +1 -1
  440. package/dist/sdk/flag-invocation-contracts.js +1 -1
  441. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  442. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  443. package/dist/sdk/generated-error-code-catalog.js +1 -1
  444. package/dist/sdk/governance/assurance-action-contracts.js +1 -1
  445. package/dist/sdk/governance/assurance-action.js +1 -1
  446. package/dist/sdk/governance/assurance-limits.js +1 -1
  447. package/dist/sdk/governance/assurance-mutation-error.js +1 -1
  448. package/dist/sdk/governance/assurance-presets.js +1 -1
  449. package/dist/sdk/governance/assurance-runtime.js +1 -1
  450. package/dist/sdk/governance/assurance.js +4 -4
  451. package/dist/sdk/governance/boundary-fixtures.js +1 -1
  452. package/dist/sdk/governance/closure-timestamps.js +1 -1
  453. package/dist/sdk/governance/coverage-assurance.js +1 -1
  454. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
  455. package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
  456. package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
  457. package/dist/sdk/governance/defect-recurrence.js +1 -1
  458. package/dist/sdk/governance/extension-host-version.js +1 -1
  459. package/dist/sdk/governance/gc.js +1 -1
  460. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  461. package/dist/sdk/governance/health.js +2 -1
  462. package/dist/sdk/governance/hierarchy-validation.js +1 -1
  463. package/dist/sdk/governance/linked-file-report.js +1 -1
  464. package/dist/sdk/governance/merge-receipt-history.js +1 -1
  465. package/dist/sdk/governance/provenance-health.js +4 -1
  466. package/dist/sdk/governance/reindex.js +5 -4
  467. package/dist/sdk/governance/stale-work.js +1 -1
  468. package/dist/sdk/governance/status-role-diagnostics.js +1 -1
  469. package/dist/sdk/governance/storage-integrity.js +1 -1
  470. package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
  471. package/dist/sdk/governance/upgrade.js +2 -2
  472. package/dist/sdk/governance/validate-history-drift.js +1 -1
  473. package/dist/sdk/governance/validate-item-reader.js +1 -1
  474. package/dist/sdk/governance/validate-normalization.js +1 -1
  475. package/dist/sdk/governance/validate.js +1 -1
  476. package/dist/sdk/governance/workflow-completeness.js +1 -1
  477. package/dist/sdk/governance/workflow-policy.js +3 -3
  478. package/dist/sdk/governance/workspace-position.js +2 -1
  479. package/dist/sdk/governance.js +1 -1
  480. package/dist/sdk/graph/adapter.js +1 -1
  481. package/dist/sdk/graph/analytics.js +1 -1
  482. package/dist/sdk/graph/assembly.js +1 -1
  483. package/dist/sdk/graph/cache.js +1 -1
  484. package/dist/sdk/graph/centrality.js +1 -1
  485. package/dist/sdk/graph/conformance.js +1 -1
  486. package/dist/sdk/graph/deadline-scheduling.js +1 -1
  487. package/dist/sdk/graph/durable-cache.js +1 -1
  488. package/dist/sdk/graph/governance-contracts.js +1 -1
  489. package/dist/sdk/graph/governance.js +1 -1
  490. package/dist/sdk/graph/hierarchy-integrity.js +1 -1
  491. package/dist/sdk/graph/index.js +1 -1
  492. package/dist/sdk/graph/lifecycle-coverage.js +1 -1
  493. package/dist/sdk/graph/mutation-advisory.js +1 -1
  494. package/dist/sdk/graph/query-contracts.js +1 -1
  495. package/dist/sdk/graph/remediation.js +1 -1
  496. package/dist/sdk/graph/run.js +1 -1
  497. package/dist/sdk/graph/scheduling.js +1 -1
  498. package/dist/sdk/graph/traversal.js +1 -1
  499. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
  500. package/dist/sdk/graph.js +1 -1
  501. package/dist/sdk/guide-topics.js +1 -1
  502. package/dist/sdk/guide.js +8 -1
  503. package/dist/sdk/history/attestation-command.js +1 -1
  504. package/dist/sdk/history/attestation-contract.js +1 -1
  505. package/dist/sdk/history/attestation-scan.js +1 -1
  506. package/dist/sdk/history/attestation.js +1 -1
  507. package/dist/sdk/history/maintenance.js +1 -1
  508. package/dist/sdk/history/salvage.js +3 -2
  509. package/dist/sdk/history/subject.js +1 -1
  510. package/dist/sdk/history-analytics.js +1 -1
  511. package/dist/sdk/history-compact.js +1 -1
  512. package/dist/sdk/history-mcp.js +1 -1
  513. package/dist/sdk/history-provenance.js +1 -1
  514. package/dist/sdk/history-read.js +1 -1
  515. package/dist/sdk/history-redact.js +1 -1
  516. package/dist/sdk/history-repair.js +1 -1
  517. package/dist/sdk/improvement-ledger-validation.js +1 -1
  518. package/dist/sdk/improvement-ledger.js +2 -2
  519. package/dist/sdk/index.js +1 -1
  520. package/dist/sdk/init-agent-guidance.js +16 -2
  521. package/dist/sdk/init.js +16 -2
  522. package/dist/sdk/invocation-author.js +1 -1
  523. package/dist/sdk/item-children.js +1 -1
  524. package/dist/sdk/item-metadata-index.js +1 -1
  525. package/dist/sdk/item-schedule.js +1 -1
  526. package/dist/sdk/item-transaction.js +1 -1
  527. package/dist/sdk/learnings.js +1 -1
  528. package/dist/sdk/lifecycle/append.js +4 -2
  529. package/dist/sdk/lifecycle/claim.js +1 -1
  530. package/dist/sdk/lifecycle/close-many.js +1 -1
  531. package/dist/sdk/lifecycle/close.js +1 -1
  532. package/dist/sdk/lifecycle/copy.js +1 -1
  533. package/dist/sdk/lifecycle/create.js +1 -1
  534. package/dist/sdk/lifecycle/delete.js +1 -1
  535. package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
  536. package/dist/sdk/lifecycle/focus.js +1 -1
  537. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  538. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
  539. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
  540. package/dist/sdk/lifecycle/mcp-actions.js +1 -1
  541. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
  542. package/dist/sdk/lifecycle/mutation-command-options.js +1 -1
  543. package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
  544. package/dist/sdk/lifecycle/plan.js +1 -1
  545. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
  546. package/dist/sdk/lifecycle/reopen.js +1 -1
  547. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -1
  548. package/dist/sdk/lifecycle/restore.js +1 -1
  549. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  550. package/dist/sdk/lifecycle/task-composition.js +1 -1
  551. package/dist/sdk/lifecycle/update-many.js +1 -1
  552. package/dist/sdk/lifecycle/update.js +2 -1
  553. package/dist/sdk/lifecycle-completion.js +1 -1
  554. package/dist/sdk/lifecycle-policy.js +1 -1
  555. package/dist/sdk/linked-artifacts.js +2 -1
  556. package/dist/sdk/mcp/apps.js +1 -1
  557. package/dist/sdk/mcp/authorization.js +1 -1
  558. package/dist/sdk/mcp/discovery.js +1 -1
  559. package/dist/sdk/mcp/interactions.js +1 -1
  560. package/dist/sdk/mcp/protocol.js +1 -1
  561. package/dist/sdk/mcp/skills.js +3 -1
  562. package/dist/sdk/mcp/subscriptions.js +1 -1
  563. package/dist/sdk/mcp/tasks.js +2 -2
  564. package/dist/sdk/mcp/transport.js +1 -1
  565. package/dist/sdk/merge/abandoned-receipts.js +1 -1
  566. package/dist/sdk/merge/driver.js +1 -1
  567. package/dist/sdk/merge/index.js +1 -1
  568. package/dist/sdk/merge/install.js +4 -2
  569. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  570. package/dist/sdk/merge/receipt-operation.js +1 -1
  571. package/dist/sdk/merge/receipt-schema.js +1 -1
  572. package/dist/sdk/merge/receipts.js +4 -4
  573. package/dist/sdk/merge/reconcile.js +1 -1
  574. package/dist/sdk/merge/three-way.js +3 -2
  575. package/dist/sdk/merge/worktree-config.js +1 -1
  576. package/dist/sdk/merge.js +1 -1
  577. package/dist/sdk/mutation-events.js +1 -1
  578. package/dist/sdk/mutation-guard.js +1 -1
  579. package/dist/sdk/notes.js +1 -1
  580. package/dist/sdk/output-contracts.js +1 -1
  581. package/dist/sdk/output-projection.js +1 -1
  582. package/dist/sdk/output-token-accounting.js +1 -1
  583. package/dist/sdk/output.js +2 -1
  584. package/dist/sdk/ownership-source.js +1 -1
  585. package/dist/sdk/package-import-adapters.js +1 -1
  586. package/dist/sdk/package-migrations.js +1 -1
  587. package/dist/sdk/package-runtime-options.js +1 -1
  588. package/dist/sdk/pagination.js +1 -1
  589. package/dist/sdk/profile.js +5 -1
  590. package/dist/sdk/provenance.js +1 -1
  591. package/dist/sdk/public-surface.json +1 -1
  592. package/dist/sdk/query/activity.js +1 -1
  593. package/dist/sdk/query/aggregate.js +1 -1
  594. package/dist/sdk/query/calendar.js +4 -1
  595. package/dist/sdk/query/complete-list.js +1 -1
  596. package/dist/sdk/query/context.js +2 -1
  597. package/dist/sdk/query/duplicate-candidates.js +1 -1
  598. package/dist/sdk/query/get.d.ts +14 -2
  599. package/dist/sdk/query/get.js +1 -1
  600. package/dist/sdk/query/history.js +1 -1
  601. package/dist/sdk/query/item-filter-options.js +1 -1
  602. package/dist/sdk/query/light-metadata.js +1 -1
  603. package/dist/sdk/query/list-filter-shared.js +1 -1
  604. package/dist/sdk/query/list.js +1 -1
  605. package/dist/sdk/query/multi-value-filters.js +1 -1
  606. package/dist/sdk/query/next-ready-budget.js +1 -1
  607. package/dist/sdk/query/next.js +2 -1
  608. package/dist/sdk/query/parsers.js +1 -1
  609. package/dist/sdk/query/projection-contracts.js +1 -1
  610. package/dist/sdk/query/search/corpus.js +2 -1
  611. package/dist/sdk/query/search/filters.js +1 -1
  612. package/dist/sdk/query/search/input.js +1 -1
  613. package/dist/sdk/query/search/lexical.js +1 -1
  614. package/dist/sdk/query/search/response.js +1 -1
  615. package/dist/sdk/query/search/semantic.js +3 -2
  616. package/dist/sdk/query/search/types.js +1 -1
  617. package/dist/sdk/query/search-contracts.js +1 -1
  618. package/dist/sdk/query/search-pagination.d.ts +1 -1
  619. package/dist/sdk/query/search-pagination.js +1 -1
  620. package/dist/sdk/query/search-rendering.js +1 -1
  621. package/dist/sdk/query/search.js +1 -1
  622. package/dist/sdk/query/workspace-contracts.js +1 -1
  623. package/dist/sdk/query.js +1 -1
  624. package/dist/sdk/read-output/continuation.js +1 -1
  625. package/dist/sdk/read-output/options.js +1 -1
  626. package/dist/sdk/read-output/provenance.js +1 -1
  627. package/dist/sdk/read-output-budget.js +1 -1
  628. package/dist/sdk/read-output-contracts.js +1 -1
  629. package/dist/sdk/read-output-rows.js +1 -1
  630. package/dist/sdk/read-output-session.js +1 -1
  631. package/dist/sdk/relationship-analytics.js +1 -1
  632. package/dist/sdk/relationship-context.js +1 -1
  633. package/dist/sdk/relationship-history.js +7 -4
  634. package/dist/sdk/relationship-kinds/contract.js +1 -1
  635. package/dist/sdk/relationship-migration.js +1 -1
  636. package/dist/sdk/relationships.js +1 -1
  637. package/dist/sdk/reproducibility/process.js +1 -1
  638. package/dist/sdk/runtime/actions.js +1 -1
  639. package/dist/sdk/runtime/context.js +1 -1
  640. package/dist/sdk/runtime/schema-preview.js +1 -1
  641. package/dist/sdk/runtime/schema.js +1 -1
  642. package/dist/sdk/runtime-action-aliases.js +1 -1
  643. package/dist/sdk/runtime-extended-actions.js +1 -1
  644. package/dist/sdk/runtime-input.js +1 -1
  645. package/dist/sdk/runtime-primitives.js +1 -1
  646. package/dist/sdk/runtime-public-contracts.js +1 -1
  647. package/dist/sdk/runtime-stats-options.js +1 -1
  648. package/dist/sdk/runtime.js +1 -1
  649. package/dist/sdk/scheduling-shortcuts.js +1 -1
  650. package/dist/sdk/schema-migration.js +4 -3
  651. package/dist/sdk/schema.js +7 -1
  652. package/dist/sdk/search-refresh-worker.js +1 -1
  653. package/dist/sdk/similarity-scoring.js +1 -1
  654. package/dist/sdk/similarity.js +1 -1
  655. package/dist/sdk/start-task-status.js +1 -1
  656. package/dist/sdk/stats.js +1 -1
  657. package/dist/sdk/structured-mutations.js +1 -1
  658. package/dist/sdk/telemetry-flush.js +1 -1
  659. package/dist/sdk/telemetry.js +4 -3
  660. package/dist/sdk/templates.js +26 -2
  661. package/dist/sdk/test/batch.js +2 -2
  662. package/dist/sdk/test/entry.js +1 -1
  663. package/dist/sdk/test/execution.js +6 -5
  664. package/dist/sdk/test/json-path.js +1 -1
  665. package/dist/sdk/test/linked-command-detection.js +1 -1
  666. package/dist/sdk/test/measurements.js +1 -1
  667. package/dist/sdk/test/parsers.js +1 -1
  668. package/dist/sdk/test/runs.js +1 -1
  669. package/dist/sdk/test/trust.js +2 -2
  670. package/dist/sdk/test/workspace-snapshot.js +1 -1
  671. package/dist/sdk/testing.js +7 -4
  672. package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
  673. package/dist/sdk/traceability/source-traceability.js +2 -1
  674. package/dist/sdk/tracker-root-discovery.js +1 -1
  675. package/dist/sdk/workspace-contracts-cache.js +1 -1
  676. package/dist/sdk/workspace-contracts.js +1 -1
  677. package/dist/sdk/workspace-memory.js +2 -2
  678. package/dist/sdk/workspace-recipe.js +1 -1
  679. package/dist/sdk/workspace-snapshot.js +5 -4
  680. package/dist/sdk/workspace-transaction-gc.js +1 -1
  681. package/dist/sdk/workspace-transaction.js +2 -2
  682. package/dist/sdk/workspace.js +3 -2
  683. package/dist/types/index.js +1 -1
  684. package/dist/types.js +1 -1
  685. package/docs/AGENT_EVIDENCE_CONSISTENCY.md +88 -0
  686. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +25 -0
  687. package/docs/GET_READ_EVIDENCE.md +68 -0
  688. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +23 -0
  689. package/docs/README.md +2 -0
  690. package/docs/SDK_AUDITED_MUTATIONS.md +35 -0
  691. package/docs/TESTING.md +8 -0
  692. package/docs/ecosystem-review-2026-09-28.json +2864 -3157
  693. package/marketplace.json +2 -2
  694. package/package.json +1 -1
  695. package/packages/pm-beads/package.json +1 -1
  696. package/packages/pm-calendar/package.json +1 -1
  697. package/packages/pm-command-kit/package.json +1 -1
  698. package/packages/pm-digital-twin/package.json +1 -1
  699. package/packages/pm-governance-audit/package.json +1 -1
  700. package/packages/pm-guide-shell/package.json +1 -1
  701. package/packages/pm-kanban/package.json +1 -1
  702. package/packages/pm-lifecycle-hooks/package.json +1 -1
  703. package/packages/pm-linked-test-adapters/package.json +1 -1
  704. package/packages/pm-search-advanced/package.json +1 -1
  705. package/packages/pm-templates/package.json +1 -1
  706. package/packages/pm-todos/package.json +1 -1
  707. package/packages/pm-vcs/extensions/vcs/index.ts +4 -2
  708. package/packages/pm-vcs/package.json +1 -1
  709. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  710. package/plugins/pm-claude/package.json +2 -2
  711. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  712. package/plugins/pm-codex/package.json +2 -2
  713. package/plugins/pm-codex/plugin.json +1 -1
  714. package/scripts/finalize-build.mjs +3 -2
  715. package/dist/cli-bundle/chunks/chunk-3AF2R3Y6.js +0 -6
  716. package/dist/cli-bundle/chunks/chunk-6ST3SCQ6.js +0 -2
  717. package/dist/cli-bundle/chunks/chunk-6Z4IV2MC.js +0 -8
  718. package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
  719. package/dist/cli-bundle/chunks/chunk-FW5LJXQY.js +0 -31
  720. package/dist/cli-bundle/chunks/chunk-H2DZW6I6.js +0 -3
  721. package/dist/cli-bundle/chunks/chunk-H7CXQBGQ.js +0 -2
  722. package/dist/cli-bundle/chunks/chunk-KP7NBQK3.js +0 -80
  723. package/dist/cli-bundle/chunks/chunk-MKXBCBAN.js +0 -20
  724. package/dist/cli-bundle/chunks/chunk-QPKQKSQU.js +0 -238
  725. package/dist/cli-bundle/chunks/chunk-SGFQQXFD.js +0 -2
  726. package/dist/cli-bundle/chunks/chunk-YCBGZF3T.js +0 -2
  727. package/dist/cli-bundle/chunks/chunk-YDWKGUQU.js +0 -3
  728. package/dist/cli-bundle/chunks/register-mutation-5PT3NW3A.js +0 -20
  729. package/dist/cli-bundle/chunks/register-operations-QDDQOAAV.js +0 -2
  730. package/dist/cli-bundle/chunks/register-setup-BBX67YMA.js +0 -2
  731. package/dist/cli-bundle/focused-chunks/chunk-4FFPGNCJ.js +0 -6
  732. package/dist/cli-bundle/focused-chunks/chunk-73DA7ISY.js +0 -75
  733. package/dist/cli-bundle/focused-chunks/chunk-E754JDLY.js +0 -2
  734. package/dist/cli-bundle/focused-chunks/chunk-FKK2HI3S.js +0 -2
  735. package/dist/cli-bundle/focused-chunks/chunk-GMYUNHST.js +0 -3
  736. package/dist/cli-bundle/focused-chunks/chunk-HIA2ZF64.js +0 -12
  737. package/dist/cli-bundle/focused-chunks/chunk-UTRSM3ZK.js +0 -8
  738. package/dist/cli-bundle/focused-chunks/chunk-VVWYI2X7.js +0 -2
  739. package/dist/cli-bundle/focused-chunks/chunk-WAJNX4RN.js +0 -20
  740. package/dist/cli-bundle/focused-chunks/chunk-WCY6HRZO.js +0 -30
  741. package/dist/cli-bundle/focused-chunks/chunk-YC32ZSLS.js +0 -165
  742. package/dist/cli-bundle/focused-chunks/chunk-ZIXFMIUL.js +0 -3
@@ -0,0 +1,75 @@
1
+ import{a as Ua,c as Gr,d as qr,e as pl,g as fl,h as za,i as hl,j as an,k as on,l as _l,m as gl,n as Wa,o as vl,p as sn,q as cn,r as bl,s as kl,t as Ga}from"./chunk-CLDPTMQY.js";import{e as ei,f as Ka,h as Ya}from"./chunk-2CVX3KR3.js";import{B as Ll,C as Xr,D as Ml,E as Ja,G as jl,H as Fl,J as Ul,K as Zr,M as Qr,a as ol,g as Fa,i as sl}from"./chunk-DOVTUKJQ.js";import{K as Yd}from"./chunk-UDYRVBOZ.js";import{D as to,E as pi,Ha as Hd,Ia as zd,Ma as Wd,Na as Gd,T as fi,U as gd,V as no,W as Yn,Y as ro,aa as Cd,ba as Td,ca as $d,da as Od,ea as _i,f as cd,g as ld,ga as Dd,h as dd,ha as Pd,ia as Nd,ja as Wt,k as mi,ka as Ld,kb as Vd,la as hn,ma as Md,mb as oo,na as io,nb as Jd,o as Jn,oa as _n,ob as Kd,p as ud,pa as jd,q as md,qa as Fd,r as Kn,ra as Ud,s as pd,sa as ao,u as eo,v as fd,wb as so,z as hd}from"./chunk-C224METM.js";import{a as ll,b as rn,c as Ha,d as dl,e as ul,f as ot,g as Br,h as ml,i as kt}from"./chunk-LE4JUCRR.js";import{$ as Bl,$a as _d,Aa as nd,Ab as te,Ba as rd,Bb as we,Cb as ve,D as G,Da as mn,Db as Ad,E as Hl,Ea as Vn,Eb as fn,Fa as id,Fb as st,Ga as oi,Gb as zt,H as Re,Ha as Ht,I as Xa,Ia as ce,Ja as si,Jb as Rd,Ka as ad,Kb as ct,La as Qa,Ma as ci,Na as pn,O as zl,Oa as li,P as ti,Pa as od,S as ni,T as ri,Ta as Ce,V as Wl,W as Me,Wa as sd,Xa as C,Y as Et,Ya as di,Yb as Xn,Z as Gl,Za as ui,_ as ql,_b as gi,aa as Ut,ba as Vl,fc as qd,ga as Jl,gb as yd,ha as Za,hb as wd,ia as ii,ic as Bd,ja as dn,jb as vd,kb as bd,la as ai,lb as xt,ma as Kl,mb as kd,na as Yl,nb as Sd,pa as Xl,qb as Ed,ra as Zl,rb as xd,ta as Ql,va as ed,wb as hi,xa as un,ya as td,yb as Id}from"./chunk-GITOYRUW.js";import{b as tn,e as de,g as Le,i as Ae,j as Ye,n as _e,o as yl,p as Vr,r as wl}from"./chunk-B5RSLVE6.js";import{$ as g,$a as Wr,$c as Pl,Aa as fe,Ac as Tl,Ba as Ne,Bb as Ke,Ca as Jc,Cc as $l,Ea as ee,Ha as Kc,Kc as H,La as Yc,Lb as cl,Nc as X,Pc as ze,Qb as Jr,Qc as Ol,Ra as Xc,Rb as Sl,Rc as Yr,S as Hc,Sa as Zc,Sb as qa,T as zc,Ta as W,Tb as Ba,Ub as Va,V as Wc,Wb as El,Wd as $,X as Gc,Xb as xl,Xd as Nl,Y as zr,Ya as Bn,Yc as Dl,Yd as ln,Z as qc,Za as L,Zc as Xe,Zd as St,_a as Ve,_b as Il,_d as Ft,a as Ur,aa as y,ab as Lt,cb as Qc,d as Hr,db as Mt,de as re,fb as el,fc as Al,gb as tl,ha as Bc,hb as nl,i as jc,ka as Vc,l as Fc,m as Uc,ma as Ma,pb as rl,qb as jt,ra as qn,rb as T,sa as O,sb as il,ta as bt,tb as Ie,ua as U,va as V,vb as ja,w as La,wb as al,wc as Rl,xa as Z,xb as nn,yc as Kr,zb as Je,zc as Cl}from"./chunk-GUIF3WVC.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="081bf1eb-4b9a-5fa9-a272-34ae781d250c")}catch{}})();var M=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},Te=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Ze=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function gn(e){try{return await e()}catch(t){throw t instanceof M?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Xd(e){try{return await e()}catch(t){throw t instanceof Te?new y(t.message,g.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as Hg}from"node:crypto";import zg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var yn=1e3;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="df2d04b7-a47b-59d1-8a70-ba321a1c6b24")}catch{}})();var Qd=1,Gt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],co=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],Wg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Gg=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,yi=30,wi=5e3,eu=4,qg=50;function lt(e,t){if(!Gg.test(e))throw new M(`${t} must be a stable lowercase id`)}function Bg(e,t){if(!Number.isFinite(e)||e<0)throw new M(`${t} must be a finite non-negative number`)}function Zn(e){let t=Wg.filter(i=>e[i]!==void 0);if(t.length!==1)throw new M(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],r=e[n];return{polarity:n,value:n==="zero"?0:r}}function uo(e,t){return T(e)===T(t)}function tu(e,t){if(t.polarity==="equals")return uo(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let r=t.value;return e.every(i=>r.includes(i))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function nu(e){let t=Zn(e),n=e.negative_control.cases;return n.some(r=>r.expected==="pass")&&n.some(r=>r.expected==="fail")&&n.every(r=>tu(r.observed,t)===(r.expected==="pass"))}function Vg(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,r=t.value;return!Array.isArray(n)||!Array.isArray(r)||r.some(i=>!n.includes(i))}return!uo(e.value,t.value)}function Jg(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||T(e.scope)!==T(t.scope))return!0;let n={observe:0,warn:1,block:2},r=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return Vg(Zn(e),Zn(t))||n[t.enforcement]<n[e.enforcement]||r}function Kg(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new M("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,r=Number(t)+Number(n);if(e.field!==void 0&&r!==1)throw new M("items source with field requires exactly one of equals or state");if(e.field===void 0&&r!==0)throw new M("items source equals/state requires field")}function Yg(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new M("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(t=>t!==void 0).length>1)throw new M("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new M("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new M("dependency_kind source source_kind_state must be present or missing")}function Xg(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new M("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new M("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new M("prose_edge_gap exemption selectors must not be empty")}}function mo(e){lt(e.id,"measurement.id"),e.max_cost!==void 0&&Bg(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new M(`measurement.source.kind must be one of ${co.join(", ")}`);let n=Reflect.get(t,"kind");if(!co.includes(n))throw new M(`measurement.source.kind must be one of ${co.join(", ")}`);let r=t;if(r.kind==="items"&&Kg(r),r.kind==="dependency_kind"&&Yg(r),r.kind==="prose_edge_gap"&&Xg(r),(r.kind==="graph"||r.kind==="validate"||r.kind==="health")&&(typeof r.field!="string"||r.field.trim().length===0))throw new M(`${r.kind} source requires field`);return r.kind==="provider"&&(lt(r.provider,"provider source provider"),lt(r.key,"provider source key")),e}function po(e){if(lt(e.id,"assertion.id"),lt(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new M("assertion.owner_item_id is required");let t=Zn(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new M(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new M("retired assertion requires retire_reason");e.scope.kind==="filter"&&lt(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(r=>r.expected==="pass")||!n.some(r=>r.expected==="fail"))throw new M("assertion negative control requires pass and fail cases");if(!nu(e))throw new M(`assertion ${e.id} negative control does not prove its bound`);return e}function Zg(e){if(!Array.isArray(e.allowed_providers))throw new M("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)lt(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new M("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!Gt.includes(t))throw new M(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new M(`gate provider policy trigger ${t} is invalid`)}}function ru(e){if(lt(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new M("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new M("gate requires at least one assertion");for(let t of e.assertion_ids)lt(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new M(`gate.triggers is required and must be an array of ${Gt.join(", ")}`);if(e.triggers.length===0)throw new M("gate requires at least one trigger");for(let t of e.triggers)if(!Gt.includes(t))throw new M(`gate trigger must be one of ${Gt.join(", ")}`);return e.provider_policy&&Zg(e.provider_policy),e}function wn(e){if(e.version!==Qd)throw new M(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let r of e.measurements){if(mo(r),t.has(`measurement:${r.id}`))throw new M(`duplicate measurement ${r.id}`);t.add(`measurement:${r.id}`)}for(let r of e.assertions){if(po(r),t.has(`assertion:${r.id}`))throw new M(`duplicate assertion ${r.id}`);t.add(`assertion:${r.id}`)}for(let r of e.gates){ru(r);let i=r.assertion_ids.filter(a=>!e.assertions.some(o=>o.id===a));if(i.length>0)throw new M(`gate ${r.id} references missing assertions: ${i.join(", ")}`);if(t.has(`gate:${r.id}`))throw new M(`duplicate gate ${r.id}`);t.add(`gate:${r.id}`)}let n=new Set(e.measurements.map(r=>r.id));for(let[r,i]of iu(e))if(!n.has(r))throw new M(`${i.join(", ")} references missing measurement ${r}`);return e}function fo(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)fo(n,t)}function iu(e){let t=new Map,n=(r,i)=>{let a=t.get(r)??[];a.push(i),t.set(r,a)};for(let r of e.assertions)n(r.measurement_id,`assertion ${r.id}`),r.scope.kind==="filter"&&n(r.scope.measurement_id,`assertion ${r.id} scope`);for(let r of e.measurements){if(r.source.kind!=="derived")continue;let i=[];fo(r.source.expression,i);for(let a of i)n(a,`derived measurement ${r.id}`)}return t}function Qg(e,t){let n=e.assertion_ids.flatMap(a=>{let o=t.assertions.find(s=>s.id===a);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),r=new Set,i=new Set;for(;n.length>0;){let a=n.pop();if(r.has(a))continue;r.add(a);let o=t.measurements.find(s=>s.id===a);o.source.kind==="provider"?i.add(o.source.provider):o.source.kind==="derived"&&fo(o.source.expression,n)}return i}function Qn(){return{version:Qd,measurements:[],assertions:[],gates:[]}}function ey(e,t){let n=t.items.filter(r=>(e.statuses===void 0||e.statuses.includes(r.status))&&(e.types===void 0||e.types.includes(r.type))&&(e.tags===void 0||e.tags.every(i=>r.tags?.includes(i)))&&(e.field===void 0||(()=>{let i=r[e.field];if(e.state!==void 0){let a=i==null||i===""||Array.isArray(i)&&i.length===0;return e.state==="missing"?a:!a}return uo(i,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function ty(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function ny(e,t){let n=[],r=Ma(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let i of t.items)for(let a of i.dependencies??[]){let o=Ma(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===r&&ty(e,s)&&n.push(`${i.id}->${a.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function ry(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let r=e[n];if(Array.isArray(r)){for(let i of r)if(typeof i=="string")t.push(i);else if(typeof i=="object"&&i!==null){let a=Reflect.get(i,"text");typeof a=="string"&&t.push(a)}}}return t}function iy(e,t,n,r){return e.some(i=>i.holder_id.trim().toLowerCase()===t.toLowerCase()&&(i.target_id===void 0||i.target_id.trim().toLowerCase()===n.toLowerCase())&&(i.text_contains===void 0||r.toLowerCase().includes(i.text_contains.trim().toLowerCase())))}function lo(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function ay(e){let t=new Map,n=new Set,r=[],i=/\b[a-z][a-z0-9]*-[a-z0-9]+\b/giu,a=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let s of o.dependencies??[])n.add(lo(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(lo(o.id,s));for(let s of ry(o)){let c=[...s.matchAll(i)].map(l=>l[0]);a+=c.length,r.push({holder_id:o.id,segment:s,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:r,mention_count:a}}function oy(e,t){let n=ay(t.items),r=new Map;for(let o of n.prose_mentions){let s=o.mentioned_ids.map(l=>n.canonical_ids.get(l.toLowerCase())).filter(l=>l!==void 0&&l!==o.holder_id),c=[...new Set(s)];for(let l of c){let d=lo(o.holder_id,l);if(n.linked_pairs.has(d)||iy(e.exemptions??[],o.holder_id,l,o.segment))continue;let u=c.some(m=>m!==l);r.get(d)?.explicit===!0&&!u||r.set(d,{contributor:`${o.holder_id}->${l}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let i=[...r.values()],a=i.map(o=>o.contributor).sort();return{value:a.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:a.slice(0,e.sample_limit??25),partitions:{explicit_subject:i.filter(o=>o.explicit).length,implicit_subject:i.filter(o=>!o.explicit).length}}}function sy(e,t){return{value:t.history.filter(n=>(e.op===void 0||n.op===e.op)&&(e.author===void 0||n.author===e.author)&&(e.harness===void 0||n.agent_harness===e.harness)&&(e.model===void 0||n.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function cy(e,t){let n=t.items.filter(r=>{let i=r[e.link],a=Array.isArray(i)&&i.length>0;return e.state==="present"?a:!a});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(r=>r.id)}}function ly(e,t){let n=e.source;return n.kind==="items"?ey(n,t):n.kind==="dependency_kind"?ny(n,t):n.kind==="prose_edge_gap"?oy(n,t):n.kind==="history"?sy(n,t):n.kind==="links"?cy(n,t):null}function au(e,t){return e.reduce((n,r)=>({units:n.units+r.units,items_scanned:n.items_scanned+r.items_scanned,history_entries:n.history_entries+r.history_entries,provider_calls:n.provider_calls+r.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function dy(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,r)=>n+r,0);if(e==="subtract")return t.slice(1).reduce((n,r)=>n-r,t[0]);if(e==="multiply")return t.reduce((n,r)=>n*r,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,r)=>n/r,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function ou(e,t,n){let r=new Array(e.length),i=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o],o)}});return await Promise.all(a),r}async function su(e,t,n,r,i){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(l=>l.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let s=await cu(o,t,n,r,i);if(typeof s.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=i.charged.has(o.id)?[]:[s.cost];return i.charged.add(o.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let a=await ou(e.operands,eu,o=>su(o,t,n,r,i));return{value:dy(e.operator,a.map(o=>o.value)),costs:a.flatMap(o=>o.costs),population_size:Math.max(0,...a.map(o=>o.population_size)),contributors:[...new Set(a.flatMap(o=>o.contributors))]}}async function uy(e,t,n,r,i){mo(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await su(e.source.expression,t,n,[...r,e.id],i);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=ly(e,t);u!==null?o=u:(o=await t.external(e.source),c=1)}let l={units:o.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-a},d=au([...s,l],Date.now()-a);if(e.max_cost!==void 0&&d.units>e.max_cost)throw new Te(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${d.units}`);return{id:e.id,definition_fingerprint:`sha256:${Hg("sha256").update(T(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:d,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function cu(e,t,n,r,i){if(r.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...r,e.id].join(" -> ")}`);let a=i.cache.get(e.id);if(a)return a;let o=uy(e,t,n,r,i).catch(s=>{if(s instanceof Ze&&s.measurement_id===void 0){let c={measurement_id:e.id,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}},l=new Ze(s.message,c);throw l.cause=s,l}throw s});return i.cache.set(e.id,o),o}async function ho(e,t,n=[e]){return cu(e,t,n,[],{cache:new Map,charged:new Set})}function my(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity,e-t.value)}function py(e,t,n={}){po(e);let r=Zn(e),i=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:r,distance:my(t.value,r),verdict:i?"retired":tu(t.value,r)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:nu(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function fy(e,t,n,r){let i=Qg(e,t);if(i.size===0)return;let a=e.provider_policy,o=a?.triggers[r];if(!a||!o)throw new Te(`assurance gate ${e.id} refuses provider execution at trigger ${r} without an explicit provider policy`);let s=new Set(a.allowed_providers),c={low:0,medium:1,high:2};for(let l of i){if(!s.has(l))throw new Te(`assurance gate ${e.id} refuses provider ${l}`);let d=n.provider_capabilities?.[l];if(!d)throw new Te(`assurance provider ${l} has no declared capabilities`);if(c[d.cost_class]>c[o.max_cost_class])throw new Te(`assurance gate ${e.id} refuses ${d.cost_class}-cost provider ${l} at trigger ${r}`);if(d.network&&!o.allow_network)throw new Te(`assurance gate ${e.id} refuses network provider ${l} at trigger ${r}`)}}async function Zd(e,t,n,r,i){try{return await ho(n,r,i)}catch(a){if(a instanceof Ze){let o=a.check?` check ${a.check}`:"",s=a.measurement_id??n.id,c=new Te(`assurance gate ${e} assertion ${t} measurement ${s} source ${a.source_kind}${o} field ${a.field} could not resolve: ${a.message}`,{gate_id:e,assertion_id:t,measurement_id:s,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}});throw c.cause=a,c}throw a}}async function lu(e,t,n,r){wn(t);let i=t.gates.find(c=>c.id===e);if(!i)throw new Te(`assurance gate ${e} not found`);if(!i.triggers.includes(r.trigger))throw new Te(`assurance gate ${e} does not declare trigger ${r.trigger}`);fy(i,t,n,r.trigger);let a=await ou(i.assertion_ids,eu,async c=>{let l=t.assertions.find(p=>p.id===c),d=t.measurements.find(p=>p.id===l.measurement_id),u=n;if(l.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!p.has(h.status))}}else if(l.scope.kind==="filter"){let p=l.scope.measurement_id,h=t.measurements.find(v=>v.id===p),_=await Zd(i.id,l.id,h,n,t.measurements),w=new Set(_.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(p=>p.id===l.owner_item_id),f=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return py(l,await Zd(i.id,l.id,d,u,t.measurements),{owner_terminal:f})}),o=a.some(c=>c.verdict==="fail"&&c.enforcement==="block"),s=a.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:i.id,tree_id:n.tree_id,trigger:r.trigger,dry_run:r.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:o?"block":s?"warn":"pass",exit_code:o?1:0,assertions:a,assertions_total:a.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:au(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function vi(e){return zg.join(e,"assurance.json")}async function du(e){let t=await V(vi(e));return t===null?Qn():bi(t)}function bi(e){try{return wn(JSON.parse(e))}catch(t){throw new y("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",g.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function ki(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function hy(e,t){e==="measurement"?mo(t):e==="assertion"?po(t):ru(t)}async function er(e,t){let n=structuredClone(ki(await du(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function _o(e,t,n){let r=ki(await du(e),t).find(i=>i.id===n);if(!r)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(r)}async function Si(e,t,n,r={}){hy(t,n);let i=await C(e),a=G(r.author,i.author_default),o=await pn({pmRoot:e,filePath:vi(e),op:`assurance:${t}:put`,author:a,message:r.message,lockTtlSeconds:yi,lockWaitMs:wi,mutate:s=>{let c=s===null?Qn():bi(s),l=ki(c,t),d=l.findIndex(m=>m.id===n.id),u=d<0?"created":"updated";if(t==="assertion"&&d>=0&&Jg(l[d],n)){let m=n.authorization_decision;if(!m||!r.authorized_decision_ids?.includes(m))throw new M(`loosening assertion ${n.id} requires a verified authorization_decision`)}return d<0?l.push(structuredClone(n)):l[d]=structuredClone(n),wn(c),{raw:`${JSON.stringify(c,null,2)}
2
+ `,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function go(e,t,n={}){let r=Qn();r.measurements=structuredClone(t.measurements),r.assertions=structuredClone(t.assertions),r.gates=structuredClone(t.gates),wn(r);let i=await C(e),a=G(n.author,i.author_default),o=await pn({pmRoot:e,filePath:vi(e),op:"assurance:bundle:apply",author:a,message:n.message,lockTtlSeconds:yi,lockWaitMs:wi,mutate:s=>{let c=s===null?Qn():bi(s),l=[],d=[],u=(m,f,p)=>{for(let h of f){let _=m.find(w=>w.id===h.id);if(!_){m.push(structuredClone(h)),l.push(`${p}:${h.id}`);continue}if(T(_)!==T(h))throw new M(`assurance bundle refuses to replace divergent ${p} ${h.id}`);d.push(`${p}:${h.id}`)}};return u(c.measurements,r.measurements,"measurement"),u(c.assertions,r.assertions,"assertion"),u(c.gates,r.gates,"gate"),wn(c),{raw:`${JSON.stringify(c,null,2)}
3
+ `,result:{changed:l.length>0,created_ids:l,unchanged_ids:d}}}});return{...o.result,changed:o.changed}}async function uu(e,t,n,r={}){let i=await C(e),a=G(r.author,i.author_default),o=await pn({pmRoot:e,filePath:vi(e),op:`assurance:${t}:remove`,author:a,message:r.message,lockTtlSeconds:yi,lockWaitMs:wi,mutate:s=>{let c=s===null?Qn():bi(s);if(t==="measurement"){let u=iu(c).get(n);if(u&&u.length>0)throw new M(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new M(`assurance assertion ${n} is referenced by gate`);let l=ki(c,t),d=l.findIndex(u=>u.id===n);if(d<0)throw new M(`assurance ${t} ${n} not found`);return l.splice(d,1),wn(c),{raw:`${JSON.stringify(c,null,2)}
4
+ `,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...o.result,changed:o.changed}}async function mu(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let r=await C(e);await ci({pmRoot:e,op:"assurance:gate:verdict",author:G(n.author,r.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:yi,lockWaitMs:wi})}async function pu(e,t={}){let n=t.limit??qg;if(!Number.isInteger(n)||n<1||n>yn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${yn}`);return(await Ut(si(e),ce)).reverse().filter(r=>r.op==="assurance:gate:verdict").map(r=>r.context?.assurance_verdict).filter(r=>typeof r=="object"&&r!==null&&"gate_id"in r).filter(r=>t.gate_id===void 0||r.gate_id===t.gate_id).slice(0,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var tr={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Ei={type:"array",minItems:1,maxItems:qa,items:tr},fu={...Ei,items:{...tr,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},_y={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Ei])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:tr,id:tr}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:fu}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Ei}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:fu,authors:Ei}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:qa,items:{type:"array",minItems:2,maxItems:2,items:tr}}}}]}}},qT={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:Sl,items:_y}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="808f3bb5-cca5-5f9c-b557-7923c79ae6ce")}catch{}})();async function hu(e,t,n,r){let i=await xt(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:_u(i,t,n,r)}function gy(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function _u(e,t,n=5,r=!1){let i=[],a=new Map,o=e.policies.filter(_=>_.rule.kind==="require_fields"),s=o.filter(_=>_.subject?.operations===void 0),c=new Set,l=0,d=0,u=0,m=0,f=0,p=Il(e);for(let _ of t){let w=p({operation:"",author:"",before:_,after:_,completeness_only:!0});l+=+(w.decisions.length>0),d+=w.decisions.length,w.decisions.forEach(k=>c.add(k.policy_id));let v=w.decisions.filter(k=>!k.satisfied);if(v.length===0)continue;m+=1;let S=a.get(_.type)??{items:0,violations:0,missing_fields:0};S.items+=1;for(let k of v)u+=1,S.violations+=1,S.missing_fields+=k.missing_fields.length,k.effect==="refuse"&&(f+=1),i.length<n&&i.push({id:_.id,type:_.type,status:_.status,decision:k});a.set(_.type,S)}let h=r||f>0?"error":u>0?"warn":"ok";return{check:{name:"completeness",status:h,ok:h==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:o.length,state_requirement_count:s.length,applicable_requirement_count:c.size,requirement_application_count:d,governed_items:l,ungoverned_items:t.length-l,contract_status:gy(o.length,t.length,l),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:u,refused_violations:f,missing_by_type:Object.fromEntries(a),violations:i,violations_truncated:i.length<u,enforcement:e.enforcement}},warnings:[...u>0?[`validate_completeness_missing_fields:${u}`]:[],...r?["validate_completeness_source_incomplete"]:[]]}}import yy from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c3bed4d-4a17-5004-a1c5-65f6acec2a9b")}catch{}})();function wy(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([e,t])=>({id:`completeness-${e.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${e} work reaches completion.`,subject:{types:[e],statuses:["closed"]},rule:{kind:"require_fields",fields:[...t]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function wu(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new y("Policy definition must be valid JSON.",g.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new y("Policy definition must be an object.",g.USAGE);return t}async function vy(e,t){let n=L(process.cwd(),e.path);await te(n);let r=await C(n);return{pmRoot:n,settings:r,author:G(t,r.author_default)}}function gu(e,t,n,r){if(e==="policy-mode")return Va({...n,enforcement:t});let i=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:i};let a=Ba(r.definition),o=Va({...n,policies:[...i,a].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
5
+ `)>vd)throw new y("Policy registry exceeds its byte ceiling.",g.USAGE);return o}async function yu(e,t,n,r){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:gu(e,t,await xt(r.pmRoot),n)};let i=await pn({pmRoot:r.pmRoot,filePath:yy.join(r.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:r.author,message:n.message,lockTtlSeconds:r.settings.locks.ttl_seconds,lockWaitMs:r.settings.locks.wait_ms,mutate(a){let o=gu(e,t,bd(a),n);return{raw:`${JSON.stringify(o,null,2)}
6
+ `,result:o}}});return{policy_result:!0,action:e,changed:i.changed,result:i.result}}async function by(e,t,n){let r,i=await Rd({...n,id:e,op:"policy_approve",message:t.message,resolveHistoryContext:()=>({workflow_approval:r}),async mutate(a){let o=(await xt(n.pmRoot)).policies.find(s=>s.id===t.policy);if(!o||o.rule.kind!=="approval")throw new y("--policy must name an approval rule.",g.USAGE);if(!o.rule.authors.includes(n.author))throw new y("This actor is not a declared approver.",g.CONFLICT);return await kd(n.pmRoot,a.metadata.id),r={policy_id:o.id,policy_fingerprint:El(o),content_fingerprint:xl(o,{...a.metadata,body:a.body})},{changedFields:[]}}});return{policy_result:!0,action:"policy-approve",changed:!0,result:{id:i.item.id,...r,warnings:i.warnings}}}function ky(e,t){let n=wu(t),r=Ba({...n,id:n.id===void 0?e:n.id});if(e!==void 0&&e.trim()!==r.id)throw new y("Policy id operand does not match definition.id.",g.USAGE,{required:"Use the same policy id operand and definition.id, or supply only one of them.",nextSteps:["Omit the policy id operand to use definition.id, or omit definition.id to use the operand."]});return r}async function u$(e,t,n={},r={}){if(!Jr.includes(e))throw new y("Unknown workflow policy action.",g.USAGE);if(e==="policy-presets")return{policy_result:!0,action:e,changed:!1,result:wy()};let i=await vy(r,n.author);if(e==="policies")return{policy_result:!0,action:e,changed:!1,result:await xt(i.pmRoot)};if(e==="policy-put"){let d=ky(t,n.definition);return yu(e,d.id,{...n,definition:d},i)}if(!t?.trim())throw new y(`schema ${e} requires an operand.`,g.USAGE);if(["policy-remove","policy-mode"].includes(e))return yu(e,t,n,i);if(e==="policy-approve"){if(n.dryRun)throw new y("Use policy-check to preview; policy-approve records an approval.",g.USAGE);return by(t,n,i)}let a=W(i.settings,H()),o=await we(i.pmRoot,t,i.settings.id_prefix,i.settings.item_format,a.type_to_folder);if(!o)throw new y(`Item ${t} not found.`,g.NOT_FOUND);let{document:s}=await ve(o,{schema:i.settings.schema}),c={...s.metadata,body:s.body},l=n.definition===void 0?c:{...c,...wu(n.definition)};if(l.id!==c.id)throw new y("Policy preview cannot change the item id.",g.USAGE);return{policy_result:!0,action:e,changed:!1,result:await Sd(i.pmRoot,await xt(i.pmRoot),{operation:"update",author:i.author,before:c,after:l,completeness_only:n.definition===void 0})}}import{createHash as $u}from"node:crypto";import nr from"node:fs/promises";import rr from"node:path";import{Option as $$}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b2ab212f-4af5-5084-b436-9a35d17af809")}catch{}})();function Sy(e,t){let n=[],r=new Set;for(let i of t.keys){if(!Object.hasOwn(e,i))continue;let a=e[i];if(a!=null){if(typeof a=="string"){n.push(a);continue}if(!Array.isArray(a)||!a.every(o=>typeof o=="string"))return;r.has(a)||(r.add(a),n.push(...a))}}return n.length>0?n.join("; "):void 0}function xi(e,t){return e.find(n=>n.target===t)??{target:t,keys:[t]}}function F(e,t){return e[t]===!0?!0:void 0}function dt(e,t){return e[t]===!1?!0:void 0}function vu(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function bu(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function ku(e){let t=i=>Fa(e,xi(ei,i)),n=i=>sl(e,xi(Ka,i)),r={title:t("title"),description:t("description"),body:t("body"),status:t("status"),closeReason:t("closeReason"),priority:t("priority"),type:t("type"),tags:t("tags"),addTags:n("addTags"),removeTags:n("removeTags"),deadline:t("deadline"),estimatedMinutes:t("estimatedMinutes"),acceptanceCriteria:Sy(e,xi(Ka,"acceptanceCriteria")),addAc:n("addAc"),removeAc:n("removeAc"),definitionOfReady:t("definitionOfReady"),order:t("order"),rank:t("rank"),goal:t("goal"),objective:t("objective"),value:t("value"),impact:t("impact"),outcome:t("outcome"),whyNow:t("whyNow"),author:t("author"),message:t("message"),force:!!e.force,ownershipMetadataBypass:e.ownershipMetadataBypass===!0?!0:void 0,ownershipDependencyBypass:e.ownershipDependencyBypass===!0?!0:void 0,assignee:t("assignee"),parent:t("parent"),allowUnresolvedDeps:vu(e,["allowUnresolvedDeps","allow_unresolved_deps"])===!0,reviewer:t("reviewer"),risk:t("risk"),confidence:t("confidence"),sprint:t("sprint"),release:t("release"),blockedBy:t("blockedBy"),blockedReason:t("blockedReason"),unblockNote:t("unblockNote"),reporter:t("reporter"),severity:t("severity"),environment:t("environment"),reproSteps:t("reproSteps"),resolution:t("resolution"),expectedResult:t("expectedResult"),actualResult:t("actualResult"),affectedVersion:t("affectedVersion"),fixedVersion:t("fixedVersion"),component:t("component"),regression:e.regression===!0?"true":t("regression"),customerImpact:t("customerImpact"),dep:n("dep"),depRemove:n("depRemove"),replaceDeps:F(e,"replaceDeps"),replaceTests:F(e,"replaceTests"),replaceFiles:F(e,"replaceFiles"),replaceDocs:F(e,"replaceDocs"),comment:n("comment"),note:n("note"),learning:n("learning"),file:n("file"),test:n("test"),doc:n("doc"),reminder:n("reminder"),event:n("event"),typeOption:n("typeOption"),field:n("field"),unset:n("unset"),clearDeps:F(e,"clearDeps"),clearComments:F(e,"clearComments"),clearNotes:F(e,"clearNotes"),clearLearnings:F(e,"clearLearnings"),clearFiles:F(e,"clearFiles"),clearTests:F(e,"clearTests"),clearDocs:F(e,"clearDocs"),clearReminders:F(e,"clearReminders"),clearEvents:F(e,"clearEvents"),clearTypeOptions:F(e,"clearTypeOptions")};return bu(r,e),r}function ie(e,t){let n=xi(ol,t),r=Fa(e,n);if(r!==void 0)return r;for(let i of n.keys){let a=e[i];if(Array.isArray(a)){let o=a.filter(s=>typeof s=="string");if(o.length>0)return o.join(",")}if(t==="ids"&&typeof a=="string")return a;if(typeof a=="number"&&Number.isFinite(a))return String(a)}}function Ey(e){let t=F(e,"filterFilesMissing"),n=F(e,"filterDocsMissing");return{filterReviewerMissing:F(e,"filterReviewerMissing"),filterRiskMissing:F(e,"filterRiskMissing"),filterConfidenceMissing:F(e,"filterConfidenceMissing"),filterSprintMissing:F(e,"filterSprintMissing"),filterReleaseMissing:F(e,"filterReleaseMissing"),hasNotes:F(e,"hasNotes"),hasLearnings:F(e,"hasLearnings"),hasFiles:F(e,"hasFiles"),hasDocs:F(e,"hasDocs"),hasTests:F(e,"hasTests"),hasComments:F(e,"hasComments"),hasDeps:F(e,"hasDeps"),hasBody:F(e,"hasBody"),hasLinkedCommand:F(e,"hasLinkedCommand"),noNotes:dt(e,"notes"),noLearnings:dt(e,"learnings"),noFiles:dt(e,"files")??t,filterFilesMissing:t,noDocs:dt(e,"docs")??n,filterDocsMissing:n,noTests:dt(e,"tests"),noComments:dt(e,"comments"),noDeps:dt(e,"deps"),emptyBody:F(e,"emptyBody"),noLinkedCommand:dt(e,"linkedCommand")}}function Su(e){let t={status:ie(e,"status"),type:ie(e,"type"),tag:ie(e,"tag"),priority:ie(e,"priority"),deadlineBefore:ie(e,"deadlineBefore"),deadlineAfter:ie(e,"deadlineAfter"),updatedAfter:ie(e,"updatedAfter"),updatedBefore:ie(e,"updatedBefore"),createdAfter:ie(e,"createdAfter"),createdBefore:ie(e,"createdBefore"),today:F(e,"today"),recent:F(e,"recent"),ids:ie(e,"ids"),assignee:ie(e,"assignee"),assigneeFilter:ie(e,"assigneeFilter"),parent:ie(e,"parent"),sprint:ie(e,"sprint"),release:ie(e,"release"),limit:ie(e,"limit"),offset:ie(e,"offset"),noTruncate:dt(e,"truncate"),includeBody:F(e,"includeBody"),strictRead:F(e,"strictRead"),compact:F(e,"compact"),brief:F(e,"brief"),full:F(e,"full"),fields:ie(e,"fields"),sort:ie(e,"sort"),order:ie(e,"order"),tree:F(e,"tree"),treeDepth:ie(e,"treeDepth"),filterAcMissing:F(e,"filterAcMissing"),filterEstimatesMissing:vu(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:F(e,"filterResolutionMissing"),filterMetadataMissing:F(e,"filterMetadataMissing"),...Ey(e)};return bu(t,e),t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2b0a2979-accd-55f8-be45-db54f1528f86")}catch{}})();var xy=Symbol("pm.mcp-mutation-transport"),Iy=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function Ai(e){return xy in e}function Ri(e,t){return Ai(e)?pd(t):eo(e,t)}function W$(e,t,n=[]){let r=eo(e,{...e,...t});for(let i of n)Reflect.deleteProperty(r,i);return r}function P(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function oe(e,t){let n=e[t];return typeof n=="string"?n.trim().length>0?n:void 0:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function G$(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function vn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function vo(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new y(`${t} must be a finite integer.`,g.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new y(`${t} must be a finite integer.`,g.USAGE);return n}}function q$(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:P(e,"limit")??P(t,"limit")}function B$(e){let t=P(e,"outputFormat");return{json:!0,quiet:!0,author:P(e,"author"),path:P(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:P(e,"outputInclude"),outputLimit:oe(e,"outputLimit"),outputBudget:oe(e,"outputBudget"),outputSession:P(e,"outputSession"),outputCursor:P(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Ay=new Set(["tags","blockedBy","blocked_by","skills","fields"]),xu=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),Ry=new Set([...xu].filter(e=>e!=="file")),Cy=new Set(["files","files-discover","docs","test","test-all"]),Iu=new Set(["comments","notes","learnings"]);function Ty(e,t){if(!(!Iu.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new y(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,g.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}var $y=new Set(["claim","release","start-task","pause-task","close-task"]),Oy={"history-attest":["verify","output","hashAlgorithm"],list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun"],package:["dryRun"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},Dy=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function Au(e,t=""){let n={},r=Cy.has(t),i=t==="files"||t==="files-discover"||t==="docs",a=Iu.has(t)?Ry:xu;for(let[o,s]of Object.entries(e)){if(Array.isArray(s)&&Ay.has(o)){n[o]=s.join(",");continue}if(o==="note"&&i){n[o]=s;continue}if(typeof s=="string"&&a.has(o)){n[o]=[s];continue}if(typeof s=="string"&&r&&(o==="add"||o==="remove")){n[o]=[s];continue}n[o]=s}return Object.assign(n,Object.fromEntries(Object.getOwnPropertySymbols(e).map(o=>[o,Reflect.get(e,o)]))),n}function Py(e,t,n){let r=P(e,"author");return r!==void 0?r:n!==void 0&&$y.has(n)?P(e,"assignee")??P(t,"assignee"):void 0}function Ny(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function V$(e,t){let n=vn(e.options)?e.options:void 0,r=Yc(e.options),i={},a=c=>{r[c]!==void 0||e[c]===void 0||(i[c]=e[c])};for(let c of Oy[t??""]??[])a(c);for(let c of Dy)a(c);t!==void 0&&Ai(e)&&Ty(t,r);let o=Au({...i,...r},t);if(t==="history-attest"&&Ai(e)&&(o.output!==void 0||typeof o.verify=="string"))throw new y("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",g.USAGE);let s=Ai(e)?e:n??e;return Ri(s,Ny(o,Py(e,o,t)))}function J$(e){if(e.addNote===void 0)return e;let t={...e};return t.note===void 0&&typeof t.addNote=="string"&&(t.note=t.addNote),delete t.addNote,t}function K$(e){let t={...e};return t.discoveryNote!==void 0&&t.note===void 0&&typeof t.discoveryNote=="string"&&(t.note=t.discoveryNote),delete t.discover,delete t.discoveryNote,t}function Ly(e){let t=[],n=!0;for(let r of e.trim().toLowerCase()){if(r>="a"&&r<="z"||r>="0"&&r<="9"){t.push(r),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function Y$(e){return!Iy.has(Ly(e))}function X$(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function bo(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function Z$(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(let[a,o]of Object.entries(e))n.has(a)||(r[a]=o);let i={...r,...t};return delete i.args,i}function Q$(e,t){let n=Ri(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function wo(e){return{type:oe(e,"filterType"),tag:oe(e,"filterTag"),priority:oe(e,"filterPriority"),deadlineBefore:oe(e,"filterDeadlineBefore"),deadlineAfter:oe(e,"filterDeadlineAfter"),updatedAfter:oe(e,"filterUpdatedAfter"),updatedBefore:oe(e,"filterUpdatedBefore"),createdAfter:oe(e,"filterCreatedAfter"),createdBefore:oe(e,"filterCreatedBefore"),ids:to(e.ids),assignee:oe(e,"filterAssignee"),assigneeFilter:oe(e,"filterAssigneeFilter")??oe(e,"filterAssignee_filter"),parent:oe(e,"filterParent"),sprint:oe(e,"filterSprint"),release:oe(e,"filterRelease"),limit:oe(e,"limit"),offset:oe(e,"offset")}}function yo(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return bo(e)}function Ii(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function eO(e){let t=yo(e.kind),n=yo(e.exemptIsolate),r=yo(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:Ii(e.maxDepth),limit:Ii(e.limit),after:P(e,"after"),direction:P(e,"direction"),maxPaths:Ii(e.maxPaths),sample:Ii(e.sample),...n===void 0?{}:{exemptIsolate:n},...r===void 0?{}:{exemptIsolateType:r},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function Ru(e){let t=Su(e);return e.ids!==void 0&&(t.ids=to(e.ids)),t}function tO(e){return{status:P(e,"filterStatus"),list:vn(e.list)?Ru(e.list):wo(e),reason:P(e,"reason"),resolution:P(e,"resolution"),expectedResult:P(e,"expectedResult")??P(e,"expected_result")??P(e,"expected"),actualResult:P(e,"actualResult")??P(e,"actual_result")??P(e,"actual"),validateClose:P(e,"validateClose")??P(e,"validate_close"),author:P(e,"author"),message:P(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:P(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var My=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function Eu(e){let t={};for(let[n,r]of Object.entries(e))My.has(n)||(t[n]=r);return Cu(t)}function Cu(e){let t=Au(e,"update-many");for(let n of ei)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return ku(t)}function nO(e){if(vn(e.list)||vn(e.update)){let t=vn(e.update)?e.update:Eu(e),n=Ri(e,Cu(t));return{status:oe(e,"filterStatus"),list:vn(e.list)?Ru(e.list):wo(e),update:fd(t,n),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:P(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:oe(e,"filterStatus"),list:wo(e),update:Ri(e,Eu(e)),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:P(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="69bf315a-01aa-56d9-bd56-196d6792dea2")}catch{}})();function je(e,t){throw new y(e,g.USAGE,t)}var jy="2026-07-15T06:22:12.276Z",Fy=Date.parse(jy),Uy=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Tu=e=>typeof e=="string"?e:"",Ou=e=>{let t=e??{},n=Tu(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Tu(t.ts))>=Fy);return Uy[r][i]};function Du(e,t,n=20,r=new Set,i=!1){let a=[],o=[],s={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(f)}catch{continue}l+=1;let h=Ou(p);if(h!=="attributed"){if(d+=1,h==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}s[h]+=1,i&&h==="actionable_unknown"&&o.push({item_id:e,line:m+1}),a.length<c&&a.push({item_id:e,line:m+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:s.legacy_unknown,actionable_unknown_event_count:s.actionable_unknown,acknowledged_actionable_event_count:u,samples:a,samples_truncated:s.legacy_unknown+s.actionable_unknown>a.length,actionable_events:o}}var mO=(e,t,n=20,r=new Set)=>Du(e,t,n,r);function Pu(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let i=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof i!="object"||i===null||!Array.isArray(i.events)))for(let a of i.events)typeof a=="object"&&a!==null&&typeof a.item_id=="string"&&Number.isSafeInteger(a.line)&&t.add(`${a.item_id}:${String(a.line)}`)}return t}var ir=async(e,t=20,n=!1)=>{let r=rr.join(e,"history"),i;try{i=(await nr.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,v)=>w.localeCompare(v))}catch{i=[]}let a=new Set,o=[],s=[],c=0,l=0,d=0,u=0,m=0,f=0,p="_workspace.jsonl",h=new Set;if(i.includes(p))try{h=Pu(await nr.readFile(rr.join(r,p),"utf8"))}catch{h=new Set}for(let w of i){let v;try{v=await nr.readFile(rr.join(r,w),"utf8")}catch{continue}let S=w.slice(0,-6),k=Du(S,v,t-o.length,h,n);c+=1,l+=k.checked_events,d+=k.unknown_event_count,u+=k.legacy_unknown_event_count,m+=k.actionable_unknown_event_count,f+=k.acknowledged_actionable_event_count,k.unknown_event_count>0&&a.add(S),o.push(...k.samples),n&&s.push(...k.actionable_events)}let _=u+m;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...a].sort((w,v)=>w.localeCompare(v)),samples:o,samples_truncated:_>o.length,...n?{actionable_events:s}:{}}};function Hy(e){return[...new Map(e.map(t=>[`${t.item_id}:${t.line}`,{item_id:t.item_id,line:t.line}])).values()].sort((t,n)=>t.item_id.localeCompare(n.item_id)||t.line-n.line)}async function zy(e){try{return Pu(await nr.readFile(rr.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function Wy(e){return(e.item_id===ce||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function Gy(e,t,n){let r=n[e.line-1]??"",i;try{i=JSON.parse(r)}catch{je(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Ou(i)!=="actionable_unknown"&&je(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:$u("sha256").update(r).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Nu(e,t,n){let r=t.events??[],i=+(t.all_actionable===!0)+ +(r.length>0);i===0&&je("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),i>1&&je("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&je("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let a=Hy(t.all_actionable===!0?(await ir(e,0,!0)).actionable_events:r),o=await zy(e),s=new Map;for(let m of a)if(Wy(m)||je(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!s.has(m.item_id))try{s.set(m.item_id,(await nr.readFile(rr.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{je(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=a.map(m=>Gy(m,o,s.get(m.item_id))),l=t.all_actionable===!0?"all_actionable":"events",d=$u("sha256").update(JSON.stringify({version:1,selection:l,coordinates:c})).digest("hex"),u=c.filter(({disposition:m})=>m==="actionable").length;return{plan:{selection:{kind:l},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:d},completeCoordinates:c}}async function pO(e,t,n=50){return(await Nu(e,t,n)).plan}function qy(e,t){let n=e.length>0;return n&&t&&je("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&je("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:By(e),all_actionable:t}}function By(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),a=r===ce||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!a||!Number.isSafeInteger(i)||i<1)&&je(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function fO(e,t){let n=qy(bo(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Vy(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:P(t,"planFingerprint")??P(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:P(t,"attributedAuthor")??P(t,"attributed_author")??void 0,reviewer:P(t,"reviewer"),reason:P(t,"reason")})}async function Vy(e,t){let n=t.reviewer?.trim()??"",r=t.attributed_author?.trim()??"",i=t.reason?.trim()??"",a=await Nu(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:g.SUCCESS,plan:a.plan};if([n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&je("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||je("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==a.plan.plan_fingerprint)throw new y("Author acknowledgment selection changed after preview; no history was mutated.",g.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let o=a.completeCoordinates.filter(({disposition:d})=>a.plan.selection.kind==="events"||d==="actionable").map(({item_id:d,line:u})=>({item_id:d,line:u}));if(o.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:g.NO_EFFECT,plan:a.plan};let s=await C(e),c=await ci({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:o,attributed_author:r}},message:i,lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms}),l=a.plan.actionable_count>0&&a.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:g.PARTIAL_EFFECT}:{outcome:"effect",exit_code:g.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:o.length,...l,plan:a.plan,history_path:c.historyPath}}import{execFile as Jy}from"node:child_process";import Lu from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3bb613e2-51f9-5947-8d92-d6207bb62cdc")}catch{}})();function Mu(e,t){return new Promise((n,r)=>{Jy("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(i,a)=>{i?r(i):n(a)})})}function ju(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function wO(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(ju(n),!n)throw new RangeError("Source line range must use start:end.");return n}function Ky(e){let t=new Map;for(let n of e.split(`
7
+ `)){let r=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];r&&t.set(r,(t.get(r)??0)+1)}return t}function Yy(e){let t=e.split("\0"),n=new Map;for(let r=0;r+1<t.length;r+=2){let i=t[r]?.trim();if(!i)continue;let a=[...new Set(t[r+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((o,s)=>o.localeCompare(s));n.set(i,a)}return n}async function Xy(e){let t=Lu.relative(e.workspaceRoot,Lu.resolve(e.workspaceRoot,e.sourcePath)),n=await Mu(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),r=await Mu(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:Ky(n),commitItems:Yy(r),available:!0}}function Zy(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,r;for(let i of e.graph.incidentEdges(t)){let a=i.source===t,o=a?i.target:i.source;if((e.visitedDepth.get(o)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(o,n);let s=e.graph.registry().require(i.kind),c={nodes:[...e.current.nodes,o],kinds:[...e.current.kinds,a?i.kind:s.inverse??i.kind]};e.details.get(o)?.type?.toLowerCase()==="decision"?(r=n,e.found.push(c)):e.queue.push(c)}return r}function Qy(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),r=[],i;for(;t.length>0;){let a=t.shift(),o=a.kinds.length;i!==void 0&&o>=i||o>=e.maxDepth||(i=Zy({current:a,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:r})??i)}return r.sort((a,o)=>a.nodes.join("\0").localeCompare(o.nodes.join("\0"))),r}function ew(e,t,n){let r=Bd(t);if(!r.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let i=Qy({itemId:e,maxDepth:n,graph:r.graph,details:new Map(r.details.map(s=>[s.id,s]))}),a=i[0];if(!a)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let o=[...new Set(i.map(s=>s.nodes.at(-1)))];return{status:o.length===1?"found":"ambiguous",nodes:a.nodes,kinds:a.kinds,alternative_decision_ids:o.slice(1)}}async function tw(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await Xy({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function nw(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function rw(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Fu(e){ju(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await tw(e),r=rw(n),i=new Map;for(let a of e.candidates){let o=[...n.commitLines.entries()].filter(([d])=>n.commitItems.get(d)?.includes(a.item.id)),s=o.reduce((d,[,u])=>d+u,0),c=ew(a.item.id,e.corpus,t),l=nw({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:s,decisionStatus:c.status});i.set(a.item.id,{score:s*100+a.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(a.item.updated_at))/(720*60*60*1e3))),contribution_lines:s,evidence:[...a.files.map(d=>({kind:"linked_file",reference:d.path})),...o.map(([d,u])=>({kind:"git_commit",reference:d.slice(0,12),contribution_lines:u}))],rationale:{value:a.item.value?.trim()||null,why_now:a.item.why_now?.trim()||null,outcome:a.item.outcome?.trim()||null,objective:a.item.objective?.trim()||null},decision_path:c,ambiguities:l})}return{explanations:i,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:r.length,unmapped_commit_count:n.commitLines.size-r.length,decision_depth:t}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bee6d15d-ca4a-538c-bb70-fd3dc7e2a8ec")}catch{}})();var ar=["software-delivery","research","agent-evaluation","operations"];function Uu(e,t,n,r,i){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:r,lifetime:"hold",enforcement:i,negative_control:{cases:[{observed:r,expected:"pass"},{observed:r+1,expected:"fail"}]}}}function Ci(e,t,n,r,i){let a=`preset-${e}`,o=i.map(c=>({id:`${a}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),s=o.map(c=>Uu(`${c.id}-zero`,c.id,r,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:o,assertions:s,gates:[{id:`${a}-readiness`,description:n,assertion_ids:s.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function Ti(e,t){return e==="software-delivery"?Ci(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Ci(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Ci(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Ci(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function Hu(e,t,n,r={}){return go(e,Ti(t,n).declarations,r)}async function zu(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),r={...e,items:e.items.filter(i=>!n.has(i.status))};return await Promise.all(["files","tests","docs"].map(async i=>{let a={id:`derived-active-missing-${i}`,description:`Observed active items missing ${i} evidence.`,source:{kind:"links",link:i,state:"missing"}},o=(await ho(a,r)).value,s=Uu(`${a.id}-ceiling`,a.id,t,o,"observe"),c=`active-missing-${i}`;return{id:c,population_size:r.items.length,scope:{kind:"active"},observed:o,declarations:{measurements:[a],assertions:[s],gates:[{id:`derived-${c}`,description:`Observe the accepted ${i} evidence baseline.`,assertion_ids:[s.id],triggers:["ci","scheduled"]}]}}}))}function Wu(e,t,n={}){return go(e,{measurements:t.flatMap(r=>r.declarations.measurements),assertions:t.flatMap(r=>r.declarations.assertions),gates:t.flatMap(r=>r.declarations.gates)},n)}async function Gu(e,t,n,r={}){let i=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==i)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${i}`);return Si(e,"assertion",{...t,enforcement:n},{...r,message:r.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import Vu from"node:fs/promises";import{createRequire as iw}from"node:module";import $e from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32adaa7c-f0aa-5aff-8d88-d7c0ccfbd971")}catch{}})();function qu(e,t){let n=$e.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${$e.sep}`)&&!$e.isAbsolute(n))return n.split($e.sep).join("/");let r=$e.resolve(e),i=0xcbf29ce484222325n;for(let a=0;a<r.length;a+=1)i^=BigInt(r.charCodeAt(a)),i=BigInt.asUintN(64,i*0x100000001b3n);return`<external>/${i.toString(16).padStart(16,"0")}/${$e.basename($e.dirname(e))}/package.json`}function aw(e){return e.includes(`${$e.sep}.pnpm${$e.sep}`)?"pnpm":e.includes(`${$e.sep}node_modules${$e.sep}`)?"npm":"other"}async function Bu(e){try{let t=JSON.parse(await Vu.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function ko(e){try{return await Vu.realpath(e)}catch{return $e.resolve(e)}}async function Ju(e,t,n=Ne(import.meta.url,["../../.."])){let r=await ko(t),i=await ko($e.join(n,"package.json")),a=await Bu(i),o=new Map;a!==void 0&&o.set(i,{version:a,path:qu(i,r),layout:"host",consumers:["pm-cli-host"]});for(let l of e)try{let d=iw(l.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await ko(d),m=await Bu(u);if(m===void 0)continue;let f=u,p=o.get(f);if(p){p.consumers.includes(l.name)||(p.consumers.push(l.name),p.consumers.sort((h,_)=>h.localeCompare(_)));continue}o.set(f,{version:m,path:qu(u,r),layout:aw(u),consumers:[l.name]})}catch{}let s=[...o.values()].sort((l,d)=>l.path.localeCompare(d.path)),c=a===void 0?[]:s.filter(l=>l.version!==a);return{host_version:a??null,copies:s,mismatches:c,warnings:c.map(l=>`extension_host_pm_cli_version_skew:${a}:${l.version}:${l.consumers.join("+")}`)}}import So from"node:fs/promises";import Eo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="069e2e60-11d9-5a37-a966-9073944d32a2")}catch{}})();var Ku=8388608,ow=new Set(["resolved","failed"]),sw=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function Qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xo(e){return sw.find(t=>t.matches(e))?.kind}function Yu(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let a=Qe(i.agent_provenance)?i.agent_provenance:void 0;if(a===void 0||!Kl(i).ok)return i;let o={},s=!1;for(let[l,d]of Object.entries(a)){let u=Qe(d)?xo(d.value):void 0;if(u===void 0){o[l]=d;continue}s=!0,r+=1;let m=i.agent_harness??"unknown",f=`${m}\0${l}\0${u}`,p=t.get(f)??{harness:m,dimension:l,kind:u,count:0};p.count+=1,t.set(f,p)}if(!s)return i;n+=1;let c={...i};return Object.keys(o).length===0?delete c.agent_provenance:c.agent_provenance=o,Yl(i,c,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((i,a)=>i.harness.localeCompare(a.harness)||i.dimension.localeCompare(a.dimension)||i.kind.localeCompare(a.kind))}}}async function Xu(e){let t=[];for(let n of await Zu(e)??[])try{let r=await So.readFile(Eo.join(e,"history",n),"utf8");for(let i of r.split(`
8
+ `)){if(i.trim().length===0)continue;let a=Qu(i);if(!(a===null||!Qe(a.agent_provenance))&&Object.values(a.agent_provenance).some(o=>Qe(o)&&xo(o.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function Zu(e){try{return(await So.readdir(Eo.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return null}}async function cw(e,t,n){let r;try{r=await So.open(Eo.join(e,"history",t),"r");let i=(await r.stat()).size,a=Math.min(i,Math.max(0,n)),o=Buffer.alloc(a),{bytesRead:s}=await r.read(o,0,a,0),c=o.subarray(0,s).toString("utf8"),l=s>=i,d=c.lastIndexOf(`
9
+ `),u=c;return l||(u=d===-1?"":c.slice(0,d+1)),{content:u,bytesRead:s,complete:l}}catch{return null}finally{await r?.close()}}function Qu(e){try{let t=JSON.parse(e);return Qe(t)?t:null}catch{return null}}function lw(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=Qe(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([o,s])=>{if(!Qe(s))return;let c=xo(s.value);if(!c)return;let l=`${r}\0${o}\0${c}`,d=n.get(l)??{harness:r,dimension:o,kind:c,count:0};d.count+=1,n.set(l,d)}),!Qe(e.context))return;let a=e.context.agent_provenance_outcomes;Qe(a)&&Object.entries(a).forEach(([o,s])=>{if(!Qe(s)||typeof s.resolver!="string"||!ow.has(String(s.status)))return;let c=`${r}\0${o}\0${s.resolver}`,l=t.get(c)??{harness:r,dimension:o,resolver:s.resolver,attempts:0,successes:0};l.attempts+=1,s.status==="resolved"&&(l.successes+=1),t.set(c,l)})}function dw(e,t,n,r,i,a){let o=i;for(let s of e.split(`
10
+ `)){if(s.trim().length===0)continue;if(o>=r)return{eventsRead:o,truncated:!0};o+=1;let c=Qu(s);if(c===null){a.malformed_events+=1;continue}if(typeof c.ts=="string"&&St(c.ts)){let l=new Date(c.ts).toISOString();(a.earliest_event_at===null||l<a.earliest_event_at)&&(a.earliest_event_at=l),(a.latest_event_at===null||l>a.latest_event_at)&&(a.latest_event_at=l)}lw(c,t,n)}return{eventsRead:o,truncated:!1}}function uw(e,t,n){return n?[...e.filter(r=>r.attempts>0&&r.successes===0).map(r=>`provenance_resolver_zero_success:${r.harness}:${r.dimension}:${r.resolver}:${String(r.attempts)}`),...t.map(r=>`provenance_value_domain_invalid:${r.harness}:${r.dimension}:${r.kind}:${String(r.count)}`)]:[]}async function em(e,t=1e4){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("Provenance event limit must be a non-negative safe integer.");let n={scope:"history_prefix",event_limit:t,byte_limit:Ku,bytes_read:0,events_read:0,truncated:!1,unreadable_sources:0,malformed_events:0,earliest_event_at:null,latest_event_at:null,complete:!1},r=new Map,i=new Map,a=0,o=0,s=!1,c=await Zu(e);c===null&&(n.unreadable_sources+=1);for(let u of c??[]){let m=await cw(e,u,Math.max(0,Ku-o));if(m===null){n.unreadable_sources+=1;continue}o+=m.bytesRead;let f=dw(m.content,r,i,t,a,n);if(a=f.eventsRead,f.truncated){s=!0;break}if(!m.complete){s=!0;break}}let l=[...r.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.resolver.localeCompare(m.resolver)),d=[...i.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.kind.localeCompare(m.kind));return n.bytes_read=o,n.events_read=a,n.truncated=s,n.complete=!s&&n.unreadable_sources===0&&n.malformed_events===0,{outcomes:l,sample:n,invalid_values:d,warnings:uw(l,d,n.complete),events_read:a,truncated:s}}import mw from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eeaf2318-5964-5d98-ad90-9faa7fc69975")}catch{}})();function Io(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=Ce(e.settings);if(n.ownership_enforcement==="strict")throw new y(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,g.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function pw(e){let t=await V(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new y(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);let n=await we(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),r=n?e.readItem?await e.readItem(n):await ve(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new y(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:r}}async function $i(e){let t=e.writeHistoryRaw??Z;try{await t(e.historyPath,e.nextHistoryRaw),await Za(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await mw.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await Za(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function tm(e){let t=[...Io({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await re(e.pmRoot,e.subject.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let r=await pw({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation});return await e.applyRewrite(r),e.applyPostRewrite&&t.push(...await e.applyPostRewrite(r)),t}finally{await n()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6283ef18-f75e-5e8c-a65f-0ba05858bc2b")}catch{}})();async function nm(e){let{subject:t,settings:n,operation:r,options:i}=e,a=await Bl(t.historyPath,t.id);if(a.raw===null)throw new y(`No history stream exists for ${t.id}.`,g.NOT_FOUND);if(a.entries.length===0)throw new y(`No history entries exist for ${t.id}; nothing to ${r.slice(8)}.`,g.USAGE);let o=t.located?await ve(t.located,{schema:n.schema}):null,s=G(i.author,n.author_default),c=await e.transform({raw:a.raw,entries:a.entries,verification:Vn(a.entries),loadedItem:o,author:s}),l=Vn(c.rewrittenEntries);if(!l.ok)throw new y(`${r} produced an invalid rewritten chain (${l.errors.join(", ")}).`,g.GENERIC_FAILURE);let d=c.changed&&!i.dryRun?await tm({pmRoot:e.pmRoot,subject:t,settings:n,typeRegistry:e.typeRegistry,historyRawBeforeLock:a.raw,currentItemRawBeforeLock:o?.raw??null,operation:r,author:s,force:i.force,itemDocument:o?.document??null,applyRewrite:async u=>{await c.beforeWrite?.(),c.applyRewrite?await c.applyRewrite(u):await $i({historyPath:t.historyPath,nextHistoryRaw:Ht(c.rewrittenEntries),historyRawUnderLock:u.historyRawUnderLock})},applyPostRewrite:c.afterWrite??(async()=>X({path:t.historyPath,scope:"project",op:`${r.replace("-","_")}:history`}))}):[];return c.report({verification:l,warnings:d})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d8f1968e-a030-5a3c-b766-60a409163745")}catch{}})();function Oi(e,t,n=25){let r=e.definitions.filter(o=>o.roles.length===0).map(o=>o.id).sort((o,s)=>o.localeCompare(s)),i=new Set(r),a=t.filter(o=>{let s=yl(o.status,e);return s!==void 0&&i.has(s)}).map(o=>o.id).sort((o,s)=>o.localeCompare(s));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:a.length,affected_item_ids:a.slice(0,n),affected_item_ids_truncated:a.length>n}}function Di(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}import Ro from"node:fs/promises";import ue from"node:path";import fw from"node:readline/promises";import{stdin as hw,stdout as Pi}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="04a94059-e242-58a6-9138-bc48a24e267e")}catch{}})();var aD=["ask","add","skip","status"],_w=["AGENTS.md","CLAUDE.md"],gw=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],yw=8,Co=1,ww="<!-- pm-cli:agent-guidance:start:",vw=`<!-- pm-cli:agent-guidance:start:v${Co} -->`,Ao="<!-- pm-cli:agent-guidance:end -->",sr="Add workflow guidance later: pm init --agent-guidance add";var bw=()=>fw.createInterface({input:hw,output:Pi});function bn(e,t){let n=ue.relative(e,t);return n.length===0?ue.basename(t):n.split(ue.sep).join("/")}function rm(e){return e.endsWith(`
11
+ `)?e:`${e}
12
+ `}function kw(e){return e.includes(`\r
13
+ `)?`\r
14
+ `:`
15
+ `}function im(e){let t=e.indexOf(ww);if(t===-1)return null;let n=e.indexOf(Ao,t);return n===-1?null:{start_index:t,end_index:n+Ao.length}}function Sw(e){return im(e)!==null}function Ew(e,t="<your project test command>"){return[vw,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --limit 10 --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and start atomically: `pm claim <id> --start`.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",Ao,""].join(e)}function am(e,t="<your project test command>"){let n=kw(e),r=Ew(n,t),i=im(e);if(i){let s=e.slice(i.end_index),c=s.startsWith(`\r
16
+ `)?s.slice(2):s.startsWith(`
17
+ `)?s.slice(1):s,l=rm(`${e.slice(0,i.start_index)}${r}${c}`);return{next_content:l,changed:l!==e}}let a=e.length===0?"":e.endsWith(`
18
+ `)?`
19
+ `:`
20
+
21
+ `,o=rm(`${e}${a}${r}`);return{next_content:o,changed:o!==e}}async function om(e){if(await O(ue.join(e,"scripts","run-tests.mjs")))return"node scripts/run-tests.mjs test";let t;try{t=JSON.parse(await Ro.readFile(ue.join(e,"package.json"),"utf8"))}catch{return"<your project test command>"}let n=xw(t);if(n===void 0)return"<your project test command>";let r=n.packageManager?.split("@")[0];return r==="pnpm"?"pnpm test":r==="bun"?"bun run test":r==="yarn"?"yarn test":r==="npm"?"npm test":await O(ue.join(e,"pnpm-lock.yaml"))?"pnpm test":await O(ue.join(e,"bun.lock"))||await O(ue.join(e,"bun.lockb"))?"bun run test":await O(ue.join(e,"yarn.lock"))?"yarn test":"npm test"}function xw(e){if(typeof e!="object"||e===null||!("scripts"in e))return;let t=e.scripts;if(!(typeof t!="object"||t===null||!("test"in t)||typeof t.test!="string"||t.test.trim().length===0))return{scripts:{test:t.test},..."packageManager"in e&&typeof e.packageManager=="string"?{packageManager:e.packageManager}:{}}}function Iw(e,t){let n=ue.dirname(e);return ue.basename(e)==="pm"&&ue.basename(n)===".agents"?ue.dirname(n):ue.resolve(t,e)}function Aw(e,t){let n=e.find(i=>ue.basename(i.file_path)==="AGENTS.md"&&i.exists);if(n)return n.file_path;let r=e.find(i=>i.exists);return r?r.file_path:ue.join(t,"AGENTS.md")}function Rw(e,t){let n=e.trim().toLowerCase();return n.length===0?t:n==="y"||n==="yes"?!0:n==="n"||n==="no"?!1:t}async function Cw(e){let t=bw();try{Pi.write(`
22
+ Agent guidance check
23
+ `),Pi.write(`No AGENTS.md/CLAUDE.md file currently contains compact pm workflow guidance.
24
+ `);let n=await t.question(`Add a compact pm workflow section to ${e}? [Y/n] `);return Pi.write(`
25
+ `),Rw(n,!0)}finally{t.close()}}function sm(e){let t=e.agent_guidance;return{prompt_completed:t?.prompt_completed===!0,declined:t?.declined===!0,declined_at:typeof t?.declined_at=="string"?t.declined_at:"",template_version:typeof t?.template_version=="number"&&Number.isInteger(t.template_version)&&t.template_version>0?t.template_version:Co,last_checked_files:Array.isArray(t?.last_checked_files)?[...new Set(t.last_checked_files.map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r)):[]}}async function cm(e){let t=[],n=await om(e);for(let r of _w){let i=ue.join(e,r),a=await O(i);if(!a){t.push({file_path:i,exists:a,has_guidance:!1,has_marker:!1});continue}let o=await Ro.readFile(i,"utf8"),s=o.toLowerCase(),c=gw.filter(d=>s.includes(d)),l=Sw(o);t.push({file_path:i,exists:a,has_guidance:l||c.length>=yw,has_marker:l,outdated:l&&am(o,n).changed})}return t}function kn(e,t){e.includes(t)||e.push(t)}function Tw(e,t){let n=sm(e),r=JSON.stringify(n)!==JSON.stringify(t);return r&&(e.agent_guidance=t),{changed:r,state:t}}async function lm(e,t=ue.dirname(e)){let n=await O(e)?await Ro.readFile(e,"utf8"):"",r=am(n,await om(t));return r.changed?(await Z(e,r.next_content),{changed:!0,warnings:await X({path:e,scope:"project",op:"init:agent_guidance_file"})}):{changed:!1,warnings:[]}}function $w(e){return{mode:e.mode,present:e.scans.some(t=>t.has_guidance),prompted:e.prompted,applied:e.applied,skipped:e.skipped,declined:e.state.declined,prompt_completed:e.state.prompt_completed,template_version:e.state.template_version,target_file:e.targetRelativePath,checked_files:e.scans.map(t=>bn(e.projectRoot,t.file_path)),files_with_guidance:e.scans.filter(t=>t.has_guidance).map(t=>bn(e.projectRoot,t.file_path)),missing_files:e.scans.filter(t=>!t.exists).map(t=>bn(e.projectRoot,t.file_path))}}async function Ow(e,t,n){return e?await cm(n):t}function or(e,t,n){e.state={...e.state,...n,template_version:Co,last_checked_files:t}}async function dm(e,t){if(t.presentBefore)return;let n=await lm(t.targetPath,t.projectRoot);e.warnings.push(...n.warnings),n.changed&&(e.applied=!0,e.warnings.push(`agent_guidance:added:${t.targetRelativePath}`))}function Dw(e,t){t||(e.warnings.push("agent_guidance:missing"),kn(e.nextSteps,sr))}function Pw(e,t){e.skipped=!0,or(e,t,{prompt_completed:!0,declined:!0,declined_at:e.state.declined_at||new Date().toISOString()}),e.warnings.push("agent_guidance:explicit_skip"),kn(e.nextSteps,sr)}async function Nw(e,t){await dm(e,t),or(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""})}function Lw(e,t){e.state.declined&&or(e,t,{prompt_completed:!0,declined:!1,declined_at:""})}function Mw(e){e.skipped=!0,e.warnings.push("agent_guidance:skipped_declined"),kn(e.nextSteps,sr)}async function jw(e,t){if(e.prompted=!0,await Cw(t.targetRelativePath)){await dm(e,t),or(e,t.checkedFiles,{prompt_completed:!0,declined:!1,declined_at:""});return}e.skipped=!0,or(e,t.checkedFiles,{prompt_completed:!0,declined:!0,declined_at:new Date().toISOString()}),e.warnings.push("agent_guidance:declined"),kn(e.nextSteps,sr)}function Fw(e){e.warnings.push("agent_guidance:missing_non_interactive"),kn(e.nextSteps,sr)}async function Uw(e,t){let n={warnings:[],nextSteps:[],prompted:!1,applied:!1,skipped:!1,state:e};return t.mode==="status"?(Dw(n,t.presentBefore),n):t.mode==="skip"?(Pw(n,t.checkedFiles),n):t.mode==="add"?(await Nw(n,t),n):t.presentBefore?(Lw(n,t.checkedFiles),n):n.state.prompt_completed&&n.state.declined?(Mw(n),n):t.interactive?(await jw(n,t),n):(Fw(n),n)}async function um(e){let t=Iw(e.pm_root,e.cwd),n=await cm(t),r=Aw(n,t),i=bn(t,r),a=n.map(d=>bn(t,d.file_path)),o=n.some(d=>d.has_guidance),s=await Uw(sm(e.settings),{mode:e.mode,interactive:e.interactive,targetPath:r,targetRelativePath:i,checkedFiles:a,presentBefore:o,projectRoot:t});if(e.mode==="add")for(let d of n.filter(u=>u.outdated)){let u=await lm(d.file_path,t);s.applied||=u.changed,s.warnings.push(...u.warnings)}let c=Tw(e.settings,s.state);n=await Ow(s.applied,n,t);let l=n.filter(d=>d.outdated).map(d=>bn(t,d.file_path));return l.length>0&&(s.warnings.push(`agent_guidance_outdated:${l.join(",")}`),kn(s.nextSteps,"pm init --agent-guidance add")),{summary:$w({mode:e.mode,scans:n,projectRoot:t,targetRelativePath:i,prompted:s.prompted,applied:s.applied,skipped:s.skipped,state:s.state}),warnings:s.warnings,next_steps:s.nextSteps,settings_changed:c.changed}}import wt from"node:fs/promises";import ke from"node:path";import cr from"node:fs/promises";import{createHash as Hw}from"node:crypto";import pm from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="97537e2a-b8cb-559e-82bc-3c98b0c51db1")}catch{}})();var To=new Set([void 0,...Hl]),fm=11,zw="history-drift-cache.json";function hm(e){return pm.join(e,"runtime",zw)}async function Ww(e){try{let t=await cr.readFile(hm(e),"utf8"),n=JSON.parse(t);return n.version!==fm||n.history_item_hash_version!==ii||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!To.has(r.hash_algorithm)||!dn.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&dn.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}function _m(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function gm(e){let t=[...new Set([...e.missingStreams,...e.unreadableStreams,...e.hashMismatches,...e.chainMismatches,...e.versionSkews,...e.workspaceStateMismatches.length>0||e.workspaceStateMissing.length>0||e.workspaceStateUnreadable.length>0?[ce]:[]])].sort((n,r)=>n.localeCompare(r));return{...e,driftedItems:t}}async function Gw(e,t,n,r,i){let a=si(e),o;try{o=await cr.stat(a)}catch(l){return U(l)||i.unreadableStreams.push(ce),!1}let s=i.missingStreams.length,c=await ym({itemId:ce,historyPath:a,stat:o,cached:t[ce],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.versionSkew&&i.versionSkews.push(ce),c.verification.chainOk||i.chainMismatches.push(ce),n[ce]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion,hash_algorithm:c.verification.hashAlgorithm},c.cacheDirty):(i.missingStreams.splice(s),c.cacheDirty)}function qw(e){return!To.has(e.hash_algorithm)||e.item_hash_version!==void 0&&!dn.includes(e.item_hash_version)}async function Bw(e){let t=await cr.readFile(e,"utf8"),n=Hw("sha256").update(t).digest("hex");if(t.trim().length===0)return null;let r=[],i=null;for(let m of t.split(/\r?\n/)){let f=m.trim();if(f.length===0)continue;let p=JSON.parse(f);if(typeof p.after_hash!="string"||p.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(p),i=p.after_hash}if(!i)return null;let a=mn(r),o=r.some(qw),s=r[r.length-1],c=To.has(s.hash_algorithm),l=s.item_hash_version,d=l!==void 0&&dn.includes(l),u=d?l:a.item_hash_version;return{latestAfterHash:i,hashAlgorithm:c?Re(s.hash_algorithm):void 0,identityDiscontinuities:Ql(r),chainOk:a.ok,versionSkew:o,latestHashComparable:c&&u!==void 0&&(!o||d||l===void 0),contentHash:n,itemHashVersion:u??ii}}function Vw(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function mm(e,t,n){try{return await Bw(t)||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}function Jw(e,t){return e!==null&&e.contentHash===t.content_hash&&e.latestAfterHash===t.latest_after_hash&&e.chainOk===t.chain_ok&&e.versionSkew===(t.version_skew===!0)&&e.latestHashComparable===t.latest_hash_comparable&&e.itemHashVersion===t.item_hash_version&&e.hashAlgorithm===t.hash_algorithm}async function ym(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(Vw(e.cached,e.stat)&&t!==void 0)||!e.cached||!e.cached.chain_ok)return{verification:await mm(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let n=await mm(e.itemId,e.historyPath,e.accumulator);return{verification:n,cacheDirty:!Jw(n,e.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&dn.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version,hashAlgorithm:e.cached.hash_algorithm},cacheDirty:!1}}async function wm(e,t,n,r){let i,a;try{i=Mt(e,t.id),a=await cr.stat(i)}catch(l){return(U(l)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let o=await ym({itemId:t.id,historyPath:i,stat:a,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!o.verification)return o.cacheDirty;o.verification.identityDiscontinuities.length>0&&(r.identityDiscontinuities??=[]).push(...o.verification.identityDiscontinuities.map(l=>({...l,item_id:t.id}))),o.verification.versionSkew&&r.versionSkews.push(t.id),o.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:a.mtimeMs,ctime_ms:a.ctimeMs,size:a.size,content_hash:o.verification.contentHash,latest_after_hash:o.verification.latestAfterHash,chain_ok:o.verification.chainOk,version_skew:o.verification.versionSkew,latest_hash_comparable:o.verification.latestHashComparable,item_hash_version:o.verification.itemHashVersion,hash_algorithm:o.verification.hashAlgorithm};let{body:s,...c}=t;return o.verification.latestHashComparable&&(Xl({metadata:c,body:s},o.verification.itemHashVersion,o.verification.hashAlgorithm).includes(o.verification.latestAfterHash)||r.hashMismatches.push(t.id)),o.cacheDirty}async function Kw(e,t){if(!(t.unreadableStreams.includes(ce)||t.chainMismatches.includes(ce)||t.versionSkews.includes(ce)))try{let n=await ad(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(ce)}}async function vm(e,t){let n=_m();return await wm(e,t,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},n),gm(n)}async function qt(e,t,n={}){let r=_m(),i=(await Ww(e))?.entries??{},a={},o=!1,s=n.cacheHitVerification!=="metadata",c={previousEntries:i,nextEntries:a,verifyCacheHitByContent:s};for(let d of t)await wm(e,d,c,r)&&(o=!0);let l=await Gw(e,i,a,s,r);if(o||=l,await Kw(e,r),o||Object.keys(i).length!==Object.keys(a).length){let d=hm(e);try{await cr.mkdir(pm.dirname(d),{recursive:!0}),await Z(d,JSON.stringify({version:fm,history_item_hash_version:ii,entries:a}))}catch{}}return gm(r)}import lr from"node:fs/promises";import Ni from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b5974276-3b45-5ad6-a7aa-e05a33807ee7")}catch{}})();function Yw(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:r,owner:i,created_at:a,ttl_seconds:o}=n;return typeof r!="string"||typeof i!="string"||typeof a!="string"||typeof o!="number"||!Number.isFinite(o)?null:{id:r,owner:i,created_at:a,ttl_seconds:o}}function bm(e,t,n){let r=Yw(t);if(r===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let i=Date.parse(r.created_at);if(!Number.isFinite(i))return{detail:"invalid_timestamp",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let a=n-i,o=Math.floor(a/1e3),s=a>r.ttl_seconds*1e3;return{detail:s?"expired":"active",entry:{file:e,id:r.id,owner:r.owner,created_at:r.created_at,ttl_seconds:r.ttl_seconds,age_seconds:o,stale:s,reason:s?"expired":"active"}}}async function km(e,t){let n=t??Date.now(),r=Ni.join(e,"locks"),i={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},a;try{a=(await lr.readdir(r)).filter(o=>o.endsWith(".lock")).sort()}catch(o){if(U(o))return i;throw o}for(let o of a){let s;try{s=await lr.readFile(Ni.join(r,o),"utf8")}catch(l){if(U(l))continue;i.scanned+=1,i.unreadable_lock_count+=1;continue}i.scanned+=1;let{detail:c}=bm(o,s,n);c==="active"?i.active_lock_count+=1:c==="expired"?i.stale_lock_count+=1:i.unparseable_lock_count+=1}return i}async function Sm(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Ni.join(e,"locks"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},s;try{s=(await lr.readdir(a)).filter(c=>c.endsWith(".lock")).sort()}catch(c){if(U(c))return o;throw c}for(let c of s){o.scanned+=1;let l=Ni.join(a,c),d=`locks/${c}`;if(r?.onRead){let f=await r.onRead(l);o.warnings.push(...f)}let u;try{u=await lr.readFile(l,"utf8")}catch(f){if(U(f)){o.scanned-=1;continue}o.warnings.push(`lock_unreadable:${c}`),o.retained.push(d),o.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let m=bm(c,u,i);if(m.detail==="unparseable_json"){o.warnings.push(`lock_unparseable:${c}`),o.retained.push(d),o.entries.push(m.entry);continue}if(m.detail==="invalid_timestamp"){o.warnings.push(`lock_invalid_timestamp:${c}`),o.retained.push(d),o.entries.push(m.entry);continue}if(m.detail==="active"){o.retained.push(d),o.entries.push(m.entry);continue}if(!n){try{await lr.unlink(l)}catch(f){if(!U(f)){o.warnings.push(`lock_remove_failed:${c}`),o.retained.push(d),o.entries.push(m.entry);continue}}if(r?.onWrite){let f=await r.onWrite(l);o.warnings.push(...f)}}o.removed.push(d),o.entries.push(m.entry)}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3d7db45e-123f-596b-afc7-b698f2b2f45c")}catch{}})();var Xw=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:"A lossless merge receipt is still pending; run pm merge reconcile to settle it (optionally preview first with --dry-run) so a green health gate certifies receipt settlement, not only intact data."},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function $o(e){if(typeof e!="string")return;let t=e.trim();for(let n of Xw)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Oo(e){let t={};for(let n of e){let r=$o(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Em(e){return Object.values(Oo(e))}import Ot from"node:fs/promises";import Pe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="184c43e0-a543-5b0b-ac09-9139ba5ded6a")}catch{}})();var Zw=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Sn(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Kr(t.extensionName));for(let _ of t.extensionNames??[])n.add(Kr(_));let r=_=>n.size===0||n.has(Kr(_)),i=(_,w)=>xm(_.filter(v=>r(v.name)).map(w)),a=(_,w)=>xm(_.filter(v=>r(v.name)).flatMap(w)),{registrations:o,commands:s,parsers:c,preflight:l,services:d,renderers:u,hooks:m}=e,f=a(o.relationship_kinds??[],_=>_.definitions.map(w=>w.kind)),p=u.overrides.filter(_=>r(_.name)&&((_.commands?.length??0)>0||_.resultDiscriminator!==void 0)).map(_=>({format:_.format,commands:[..._.commands??[]],result_discriminator:_.resultDiscriminator!==void 0})).sort((_,w)=>_.format.localeCompare(w.format)),h=i(o.assurance_providers??[],_=>_.definition.id);return{capabilities:Cl(e,t),commands:i(o.commands,_=>_.command),command_overrides:i(s.overrides,_=>_.command),command_handlers:i(s.handlers,_=>_.command),hooks:Zw.filter(([_])=>m[_].some(w=>r(w.name))).map(([,_])=>_),flag_commands:i(o.flags,_=>_.target_command),item_types:a(o.item_types,_=>_.types.map(w=>w.name)),item_fields:a(o.item_fields,_=>_.fields.map(w=>w.name)),...f.length>0?{relationship_kinds:f}:{},migrations:a(o.migrations,_=>typeof _.definition.id=="string"?[_.definition.id]:[]),profiles:i(o.profiles,_=>_.profile.name),importers:i(o.importers,_=>_.importer),exporters:i(o.exporters,_=>_.exporter),search_providers:i(o.search_providers,_=>_.definition.name),vector_store_adapters:i(o.vector_store_adapters,_=>_.definition.name),...h.length>0?{assurance_providers:h}:{},parser_overrides:i(c.overrides,_=>_.command),service_overrides:i(d.overrides,_=>_.service),renderer_overrides:i(u.overrides,_=>_.format),...p.length>0?{renderer_ownership:p}:{},preflight_overrides:l.overrides.filter(_=>r(_.name)).length,preflight_ownership:l.overrides.filter(_=>r(_.name)).map(_=>({commands:[..._.commands??[]]}))}}function xm(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}import fb from"node:path";import{mkdir as hb}from"node:fs/promises";import{access as pv,readFile as zo,realpath as It}from"node:fs/promises";import{constants as fv}from"node:fs";import{execFile as hv}from"node:child_process";import J from"node:path";import{promisify as _v}from"node:util";import{readFile as Qw,writeFile as ev}from"node:fs/promises";import dr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1de99e25-e132-5071-833e-37361b4cc7e6")}catch{}})();var Am="# pm-cli:runtime-cache:start",Do="# pm-cli:runtime-cache:end",Rm=".agents/pm",Po=["runtime/","search/","locks/","transactions/","checkpoints/"],tv=["search/eval-queries.json"];async function Im(e){try{return await e()}catch(t){throw t instanceof Error&&"code"in t&&typeof t.code=="string"&&["EACCES","EPERM","EROFS"].includes(t.code)?new y("The workspace .gitignore is not writable.",g.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:t.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):t}}function Cm(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function No(e){let t=e.replaceAll("\\","/");return dr.isAbsolute(e)||t===".."||t.startsWith("../")}function nv(e=Rm){let t=Cm(e);return[Am,...Po.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...tv.map(n=>`!${t}/${n}`),Do].join(`
26
+ `)}async function TD(e,t={}){let n=dr.join(e,".gitignore"),r=Rm;if(t.pmRoot!==void 0){let l=Cm(dr.relative(dr.resolve(e),dr.resolve(t.pmRoot)));if(No(l))return{path:n,changed:!1};l.length>0&&(r=l)}let i="";try{i=await Im(()=>Qw(n,"utf8"))}catch(l){if(!(l instanceof Error&&"code"in l&&U(l)))throw l}let a=i.indexOf(Am),o=i.indexOf(Do),s=(a>=0&&o>=a?`${i.slice(0,a)}${i.slice(o+Do.length)}`:i).trimEnd(),c=`${s.length>0?`${s}
27
+
28
+ `:""}${nv(r)}
29
+ `;return c===i?{path:n,changed:!1}:(await Im(()=>ev(n,c,"utf8")),{path:n,changed:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d1f8e03-97b4-5d83-b85c-e47f39c07d48")}catch{}})();var rv="PM_SOURCE_CONTEXT_ACCESS",iv="PM_ALLOW_SOURCE_CONTEXT_WRITES";function Tm(e){let t=e[rv],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[iv]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||r}}import{execFile as av}from"node:child_process";import ov from"node:path";import{promisify as sv}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ed89ee24-d57b-5964-a95b-742c4f4f28a8")}catch{}})();var En=sv(av);function Fe(){let e={...process.env};for(let t of["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM"])delete e[t];return e}async function Lo(e,t){try{return(await En("git",["config","--local",...t==="core.bare"||t==="extensions.worktreeConfig"?["--type=bool"]:[],"--get",t],{cwd:e,env:Fe(),timeout:1e4})).stdout.trim()}catch(n){if(typeof n=="object"&&n!==null&&"code"in n&&n.code===1)return;throw n}}async function $m(e){if(await Lo(e,"extensions.worktreeConfig")==="true")return"--worktree";let{stdout:t}=await En("git",["rev-parse","--path-format=absolute","--git-dir","--git-common-dir"],{cwd:e,env:Fe(),timeout:1e4}),[n,r]=t.trim().split(/\r?\n/);if(n===r)return"--local";let i=ov.join(r,"config.worktree");for(let a of["core.bare","core.worktree"]){let o=await Lo(e,a);o===void 0||a==="core.bare"&&o!=="true"||(await En("git",["config","--file",i,a,o],{cwd:e,env:Fe(),timeout:1e4}),await En("git",["config","--local","--unset-all",a],{cwd:e,env:Fe(),timeout:1e4}))}for(let a of["pm-item-toon","pm-item-markdown","pm-history","pm-relationship","pm-json"])for(let o of["name","driver"]){let s=`merge.${a}.${o}`,c=await Lo(e,s);c!==void 0&&await En("git",["config","--file",i,s,c],{cwd:e,env:Fe(),timeout:1e4})}return await En("git",["config","--local","extensions.worktreeConfig","true"],{cwd:e,env:Fe(),timeout:1e4}),"--worktree"}import Om from"node:fs";import Li from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2d40ac36-0627-5636-9679-5669dbacf06b")}catch{}})();var Dm="@unbrained/pm-cli";var Fo=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,Uo="2026.8.31";function Mi(e){let t=e.match(Fo);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function Ho(e,t){let n=Mi(e),r=Mi(t);if(!n||!r)return null;for(let i=0;i<n.length;i+=1){let a=n[i]-r[i];if(a!==0)return Math.sign(a)}return 0}function Mo(e){return Ho(e,Uo)!==-1?3:2}function jo(e){try{let t=JSON.parse(Om.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function cv(e){let t=[...e.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(r=>({inclusive:r[1]==="<=",version:r[2]})),n=e.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return n?[...t,{inclusive:!0,version:n[1]}]:t}function lv(e){let t=e.split("||").map(n=>cv(n));return{bounded:t.some(n=>n.length>0),compatible:t.some(n=>n.every(r=>{let i=Ho(Uo,r.version);return i!==null&&(r.inclusive?i!==1:i===-1)}))}}function dv(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let n=e[t];if(typeof n!="object"||n===null)return[];let r=n[Dm],i=typeof r=="string"?r.trim():"",a=/^[<!]/u.test(i)?void 0:i.match(Fo)?.[0];if(!a)return[];let o=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(i),s=lv(i);return[{version:a,constraint:o?"exact":s.bounded?"range":"minimum",...o?{}:{declaration:i},history_epoch_compatible:o?Ho(a,Uo)!==-1:s.compatible}]})}function uv(e){let t=jo(Li.join(e,"package-lock.json"))?.packages;if(typeof t!="object"||t===null)return;let n=t["node_modules/@unbrained/pm-cli"];if(typeof n!="object"||n===null)return;let r=n.version;return typeof r=="string"?r:void 0}function mv(e,t){try{let n=Om.readFileSync(Li.join(e,t),"utf8").split(/\r?\n/u),r=n.findIndex(o=>o.includes(Dm));if(r<0)return;let i=n[r].match(/^\s*/u)[0].length,a=[n[r]];for(let o=r+1;o<n.length;o+=1){let s=n[o],c=s.trim(),l=s.match(/^\s*/u)[0].length;if(c.length>0&&l<=i)break;a.push(s)}return a.join(`
30
+ `).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??a[0].match(Fo)?.[0]}catch{return}}function Pm(e){let t=[],n=jo(Li.join(e,"package.json"));n&&t.push(...dv(n).map(a=>({...a,source:"package.json"})));let r=jo(Li.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof r=="string"&&Mi(r)&&t.push({version:r,source:"installed-package",constraint:"exact",history_epoch_compatible:Mo(r)===3});let i=uv(e);i&&Mi(i)&&t.push({version:i,source:"package-lock.json",constraint:"exact",history_epoch_compatible:Mo(i)===3});for(let a of["pnpm-lock.yaml","yarn.lock"]){let o=mv(e,a);o&&t.push({version:o,source:a,constraint:"exact",history_epoch_compatible:Mo(o)===3})}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5bcde7f0-1785-530a-91bb-80f2793fb8cf")}catch{}})();var xn=_v(hv),ji="# pm-cli:merge-drivers:start",gv="# pm-cli:merge-drivers:end",ur="# pm-cli:merge-drivers:v2:start",Mm="# pm-cli:merge-drivers:v2:end",yv="merge-fence",wv="merge-attributes";function Nm(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function vv(e,t){let n=await It(e);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(n))return;let{stdout:r}=await xn(e,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return r.trim()===t?n:void 0}async function bv(){let e=Ne(import.meta.url,["../../.."]),t=process.execPath,n=!1,r=await It(process.execPath),i=process.versions.bun,a=(process.env.PATH??"").split(J.delimiter).filter(s=>J.isAbsolute(s)).map(s=>J.join(s,i===void 0?J.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),o=i===void 0?a:[process.env.npm_execpath??"",...a,r].filter(s=>J.isAbsolute(s)&&/^(?:bun|bun\.exe)$/iu.test(J.basename(s)));for(let s of o)try{if(await pv(s,fv.X_OK),i!==void 0){let c=await vv(s,i);if(c!==void 0){t=c,n=!0;break}continue}if(s!==r&&await It(s)===r){t=s;break}}catch{}if(i!==void 0&&!n)throw new y("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",g.DEPENDENCY_FAILED,{code:"merge_bun_launcher_unavailable",why:"The current Bun process may be a temporary bunx launcher that Git cannot reuse after this command exits.",nextSteps:["Run with a durable version-matched Bun executable, expose one on an absolute PATH entry, or invoke pm through a Bun runner that publishes an absolute npm_execpath.","Retry pm merge install, then check pm health --strict-exit before merging branches."]});return`${Nm(t)} ${Nm(J.join(e,"dist","cli.js"))}`}var jm=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function kv(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),i=Tm(e.environment),a=!!(n&&r),o=t===void 0&&a&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let s=L(e.cwd,t);return{pm_root:s,workspace_start:s,source_coordinates_available:a,source_context_selected:!1,source_policy:i}}return o?{pm_root:J.resolve(r),workspace_start:J.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:a?L(e.cwd,".agents/pm"):L(e.cwd),workspace_start:e.cwd,source_coordinates_available:a,source_context_selected:!1,source_policy:i}}async function et(e){try{let{stdout:t}=await xn("git",["rev-parse","--show-toplevel"],{cwd:e,env:Fe(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await It(t.trim())}catch{return null}}async function Fm(e){let t=await et(e);if(t===null)throw new y("pm merge install requires a git repository (merge drivers are git configuration).",g.USAGE);return t}function Wo(e,t){return J.relative(e,t).replaceAll("\\","/")}function We(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Lm(e,t){if(e[t]!=="'")return null;let n="";for(let r=t+1;r<e.length;r+=1){if(e.startsWith(`'"'"'`,r)){n+="'",r+=4;continue}if(e[r]==="'")return{value:n,nextOffset:r+1};n+=e[r]}return null}async function Sv(e,t,n){if(Pm(t).filter(i=>i.constraint==="exact").some(i=>i.version!==n))return!1;let r=await et(e);if(r!==null&&r!==await It(t)){let i=await Promise.all([r,t].map(async a=>{let o=await xn("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:a,env:Fe(),timeout:1e4});return It(o.stdout.trim())}));if(i[0]===i[1])return!1}return!0}async function Ev(e,t,n){let r=Lm(e,0);if(r===null||e[r.nextOffset]!==" ")return!1;let i=Lm(e,r.nextOffset+1);if(i===null||e.slice(i.nextOffset)!==t||!/^(?:node|bun)(?:\.exe)?$/iu.test(J.basename(r.value))||J.basename(i.value)!=="cli.js"||J.basename(J.dirname(i.value))!=="dist"||!await O(r.value)||!await O(i.value))return!1;try{let a=J.dirname(J.dirname(i.value)),o=JSON.parse(await zo(J.join(a,"package.json"),"utf8")),s=typeof o.bin=="string"?o.bin:o.bin?.pm;return await Sv(a,n,o.version)?o.name==="@unbrained/pm-cli"&&s==="dist/cli.js":!1}catch{return!1}}function Go(e,t){let n=e.length>0?`${e}/`:"",r=[`${We(`${n}**/*.toon`)} merge=pm-item-toon`,`${We(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)r.push(`${We(`${n}${i}/*.toon`)} merge=pm-item-toon`),r.push(`${We(`${n}${i}/*.md`)} merge=pm-item-markdown`);return r.push(`${We(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${We(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${We(`${n}settings.json`)} merge=pm-json`),r.push(`${We(`${n}**/*.json`)} merge=pm-json`),r.push(`${We(`${n}extensions/**`)} -merge`),r.push(`${We(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function Um(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(ji,n),i=e.indexOf(ur,n),a=r===-1?i:i===-1?r:Math.min(r,i);if(a===-1)break;let o=a===i,s=o?ur:ji,c=o?Mm:gv,l=e.indexOf(c,a+s.length),d=l===-1?e.length:l+c.length;t.push({start:a,end:d,closed:l!==-1,lines:e.slice(a+s.length,l===-1?d:l).split(`
31
+ `).map(u=>u.trim()).filter(Boolean)}),n=d}return t}function Hm(e,t,n){let r=new Set(t),i=We(n.length>0?`${n}/`:"").slice(0,-1);return e.some(a=>r.has(a)||a.startsWith(i)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(a.slice(i.length)))}async function zm(e,t,n,r){let i=J.join(e,".gitattributes"),a=r?null:(await xn("git",["rev-parse","--absolute-git-dir"],{cwd:e,env:Fe(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout.trim(),o=a===null?null:await re(a,wv,120,"merge-fence",!1,!0,5e3);try{let s=await V(i)??"",c=[ur,...n,Mm].join(`
32
+ `),l=Um(s),d=l.filter(m=>Hm(m.lines,n,t));d.length===0&&t===".agents/pm"&&l.length===1&&l[0].lines.every(m=>!m.includes(".agents/pm/"))&&d.push(l[0]);let u;if(d.length>0){let m=d[0];u=s;for(let f of d.slice(1).reverse())u=`${u.slice(0,f.start)}${u.slice(f.end)}`;u=`${u.slice(0,m.start)}${c}${u.slice(m.end)}`}else{let m=s.trimEnd();u=`${m.length>0?`${m}
33
+
34
+ `:""}${c}
35
+ `}return u===s?{path:i,changed:!1}:(r||await Z(i,u),{path:i,changed:!0})}finally{await o?.()}}function At(e){let t=W(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function In(e,t){let n=J.resolve(e),r=null,i="",a=n;for(let _=0;_<8;_+=1){let w=J.join(a,".gitattributes");try{let S=await zo(w,"utf8");if(S.includes(ur)||S.includes(ji)){r=a,i=S;break}}catch{}let v=J.dirname(a);if(v===a)break;a=v}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let o=J.join(r,".gitattributes"),s=Wo(r,n),c=Um(i),l=Go(s,t),d=c.filter(_=>Hm(_.lines,l,s)),u=d.flatMap(_=>_.closed?_.lines:[]),m=new Set(u),f=new Set(l),p=l.filter(_=>!m.has(_)),h=u.filter(_=>!f.has(_));return{status:d.length!==1||!d[0].closed||p.length>0||h.length>0?"drift":"ok",path:o,missing_patterns:p,stale_patterns:h,schema_scope:"project"}}async function An(e){let t=[],n=[];for(let r of jm){let i=`merge.${r.key}.driver`,a=` merge driver ${r.artifact} "%O" "%A" "%B"${r.itemPath===void 0?"":` --item-path ${r.itemPath}`}`;try{let{stdout:o}=await xn("git",["config","--get",i],{cwd:e,env:Fe(),encoding:"utf8",windowsHide:!0,timeout:1e4}),s=o.trim();await Ev(s,a,e)||n.push(i)}catch{t.push(i)}}return{status:t.length>0?"missing":n.length>0?"drift":"ok",missing_keys:t,drifted_keys:n}}async function Wm(e){let t;try{t=await Fm(J.resolve(e))}catch{return{status:"no_git"}}let n=Wo(t,J.resolve(e)),r=await C(e),i=G(void 0,r.author_default),a=await re(e,yv,r.locks.ttl_seconds,i,!1,Ce(r).force_required_for_stale_lock,r.locks.wait_ms);try{let o=J.join(t,".gitattributes"),s;try{s=await zo(o,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&U(u))return{status:"not_installed",path:o};throw u}if(!s.includes(ur)&&!s.includes(ji))return{status:"not_installed",path:o};let c=await C(e),l=At(c),d=await zm(t,n,Go(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await a()}}async function lP(e,t){let n=kv({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await te(r);let i=await Fm(n.workspace_start);return xv({pmRoot:r,workspaceRoot:i,dryRun:e.dryRun===!0})}async function xv(e){let t=J.resolve(e.pmRoot),n=J.resolve(e.workspaceRoot),r=e.dryRun===!0,i,a;try{[i,a]=await Promise.all([It(t),It(n)])}catch(f){throw new y(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,g.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let o=Wo(a,i);if(No(o))throw new y(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,g.USAGE);let s=await C(i),c=At(s),l=Go(o,c),d=[],u=await bv();for(let f of jm)d.push({key:`merge.${f.key}.name`,value:f.name}),d.push({key:`merge.${f.key}.driver`,value:`${u} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!r)try{let f=await $m(a);for(let p of d)await xn("git",["config",f,p.key,p.value],{cwd:a,env:Fe(),encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new y(`Cannot install repository-local merge drivers in ${a}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,g.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let m=await zm(a,o,l,r);return{ok:!0,dry_run:r,workspace_root:a,pm_root:i,gitattributes:{path:m.path,changed:m.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:$()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d01ffa0-2cdb-5d22-834e-d23d31403ad6")}catch{}})();var Iv=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function Av(e){let t=Iv.exec(e.trim());if(!t)return;let n=t[1];if(!(n.length<2)&&!/^[A-Za-z]\d+$/.test(n))return n.toLowerCase()}function Rv(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function Gm(e,t={}){let n=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,r=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,i=new Map;for(let o of e){let s=typeof o=="string"?o.trim():"";if(s.length===0)continue;let c=Av(s);if(c===void 0)continue;let l=i.get(c)??{count:0,examples:[]};l.count+=1,l.examples.length<r&&l.examples.push(s),i.set(c,l)}let a=[];for(let[o,s]of i.entries()){if(s.count<n)continue;let c=Rv(o);a.push({name:c,prefix:o,count:s.count,examples:s.examples,shadows_builtin:ll(c)!==void 0})}return a.sort((o,s)=>s.count-o.count||o.name.localeCompare(s.name)),a}import{createHash as np}from"node:crypto";import Vt from"node:fs/promises";import Cn from"node:path";import{mkdir as Cv,readFile as Tv}from"node:fs/promises";import Km from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0bd9a904-c076-5c2a-a9d8-42a543625e33")}catch{}})();var qo=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},$v="sdk-workspace-transaction",Ov=/^[a-zA-Z0-9._-]+$/,Dv=30,Pv=3e3;function Ym(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!Ov.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function qm(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function Nv(e){return{pmRoot:qm(e.pmRoot,"Transaction pmRoot"),transactionId:Ym(e.transactionId,"Transaction id"),author:qm(e.author,"Transaction author")}}function Bm(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw new TypeError(`${n} must be a positive integer`);return r}function Xm(e,t){return Km.join(e,"transactions","sdk",`${t}.json`)}async function Rt(e,t){t.updatedAt=$();let n=Xm(e,t.transactionId);await Cv(Km.dirname(n),{recursive:!0}),await Z(n,`${JSON.stringify(t,null,2)}
36
+ `)}function Lv(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Bt(e){return Object.assign(Object.create(null),e)}function Mv(e,t){try{let n=JSON.stringify(e,(r,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function Bo(e,t){return e===void 0?void 0:Mv(e,t)}function Vo(e,t,n,r){let i=Bo(n,r);i===void 0?delete e[t]:e[t]=i}function Vm(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Jm(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function jv(e,t){if(!Jm(e.startedStepIds,t)||!Jm(e.completedStepIds,t)||!Vm(e.results)||!Vm(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),i=e.completedStepIds,a=new Set(i);return Object.keys(e.compensationData).some(o=>!r.has(o))||Object.keys(e.results).some(o=>!a.has(o))?!1:e.status==="committed"?t.every(o=>a.has(o)):e.status!=="compensated"||a.size===0&&r.size===0}function Fv(e,t,n){let r;try{r=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!r||typeof r!="object"||Array.isArray(r))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let i=r,a=i.schemaVersion===1&&i.transactionId===t,o=Array.isArray(i.stepIds)&&i.stepIds.length===n.length&&i.stepIds.every((d,u)=>d===n[u]),s=jv(i,n),c=Lv(i),l=["applying","compensating","compensated","committed"].includes(String(i.status));if(!a||!o||!s||!c||!l)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...i,results:Bt(i.results),compensationData:Bt(i.compensationData)}}async function Uv(e,t,n,r,i){let a=i,o=a!==void 0;if(a?.status==="compensating"&&await Zm(e,a),a===void 0||a.status==="compensated"){let s=$();a={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(a?.attempt??0)+1,createdAt:a?.createdAt??s,updatedAt:s,stepIds:r,startedStepIds:[],completedStepIds:[],results:Bt(),compensationData:Bt()},await Rt(e.pmRoot,a),await ut(e,a,"prepared")}return{journal:a,recovered:o}}async function Hv(e,t,n){try{await Wv(t,e.steps),await Rt(e.pmRoot,t);let r=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let a of e.steps){if(r.has(a.id))continue;let o=await a.inspect(),s=Bo(o.result,`Step ${a.id} result`);if(o.state!=="applied"){let c=await a.prepareCompensation?.();Vo(t.compensationData,a.id,c,`Step ${a.id} compensation data`),i.add(a.id),t.startedStepIds=e.steps.map(d=>d.id).filter(d=>i.has(d)),await Rt(e.pmRoot,t);let l=await a.apply();s=Bo(l,`Step ${a.id} result`)}await ut(e,t,"step_applied",a.id),r.add(a.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),Vo(t.results,a.id,s,`Step ${a.id} result`),await Rt(e.pmRoot,t),await ut(e,t,"step_recorded",a.id)}return await ut(e,t,"committing"),t.status="committed",await Rt(e.pmRoot,t),await ut(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Bt(t.results)}}catch(r){if(r instanceof qo||t.status==="committed")throw r;try{await Zm(e,t)}catch(i){throw new AggregateError([r,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw r}}async function zv(e,t,n){try{return Fv(await Tv(Xm(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&U(r))return;throw r}}async function ut(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function Wv(e,t){let n=new Set,r=Bt();for(let i of t){let a=await i.inspect();a.state==="applied"&&(n.add(i.id),Vo(r,i.id,a.result,`Step ${i.id} result`))}e.results=r,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function Zm(e,t){t.status="compensating",await Rt(e.pmRoot,t),await ut(e,t,"compensating");let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!r.has(i.id)&&!n.has(i.id))continue;let a;try{a=r.has(i.id)&&(await i.inspect()).state==="applied"}catch{a=r.has(i.id)}a&&(await ut(e,t,"step_compensating",i.id),await i.compensate(t.compensationData[i.id])),n.delete(i.id),r.delete(i.id),t.completedStepIds=e.steps.map(o=>o.id).filter(o=>n.has(o)),t.startedStepIds=e.steps.map(o=>o.id).filter(o=>r.has(o)),delete t.results[i.id],delete t.compensationData[i.id],await Rt(e.pmRoot,t),await ut(e,t,"step_compensated",i.id)}t.status="compensated",await Rt(e.pmRoot,t),await ut(e,t,"compensated")}async function Qm(e){let{pmRoot:t,transactionId:n,author:r}=Nv(e),i=Bm(e.lockTtlSeconds,Dv,"Transaction lock TTL"),a=Bm(e.lockWaitMs,Pv,"Transaction lock wait"),o=[...e.steps];if(o.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=o.map(d=>{let u=Ym(d.id,"Transaction step id");if(u!==d.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return u});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:r,steps:o,lockTtlSeconds:i,lockWaitMs:a},l=await re(t,$v,i,r,!1,!1,a);try{let d=await zv(t,n,s),u=d!==void 0;if(d?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Bt(d.results)};let m=await Uv(c,n,r,s,d);return await Hv(c,m.journal,u||m.recovered)}finally{await l()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8d04c087-62e4-51d3-8832-6cbcfd3ed993")}catch{}})();function mt(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function rp(e){let t=mt(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function ip(e,t){let n=Ko(e),r=mt(t,"migrationScope");return`auto-${np("sha256").update(JSON.stringify({scope:r,request:n})).digest("hex").slice(0,20)}`}function Ko(e){let t=e.kind==="rename-type"?{kind:e.kind,from:mt(e.from,"source"),to:mt(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:de(mt(e.from,"source")),to:de(mt(e.to,"target")),...e.type===void 0?{}:{type:mt(e.type,"type")}}:{kind:e.kind,from:de(mt(e.from,"source")),to:de(mt(e.to,"target"))};if(t.from.toLowerCase()===t.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return t}function Gv(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function qv(e,t,n){let r=Ae(t.schema),i=Gv(n);return Ye(e,r.files[i],Le[i])}function ap(e,t){return Cn.join(e,"transactions","schema",`${t}-plan.json`)}function Fi(e){return e.length===0?null:JSON.parse(e)}async function Rn(e){let t=await V(e);return{exists:t!==null,raw:t??""}}async function op(e,t){t.exists?await Z(e,t.raw):await Vt.rm(e,{force:!0})}function Bv(e,t,n){let r=ot(e),i=r.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.from.toLowerCase()),a=r.definitions.findIndex(o=>o.name.trim().toLowerCase()===t.to.toLowerCase());if(n==="stage"){if(a>=0)return kt(r);if(i<0)throw new TypeError(`Unknown custom type "${t.from}".`);r.definitions.push({...r.definitions[i],name:t.to})}else i>=0&&r.definitions.splice(i,1);return kt(r)}function Vv(e,t,n){let r=an(e),i=r.fields.findIndex(o=>o.key===t.from),a=r.fields.findIndex(o=>o.key===t.to);if(n==="stage"){if(a>=0)return on(r);if(i<0)throw new TypeError(`Unknown custom field "${t.from}".`);let o=r.fields[i];r.fields.push({...o,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else i>=0&&r.fields.splice(i,1);return on(r)}function Jv(e,t,n){let r=sn(e),i=r.statuses.findIndex(o=>o.id===t.from),a=r.statuses.findIndex(o=>o.id===t.to);if(n==="stage"){if(a>=0)return cn(r);if(i<0)throw new TypeError(`Unknown custom status "${t.from}".`);r.statuses.push({...r.statuses[i],id:t.to})}else i>=0&&r.statuses.splice(i,1);return cn(r)}function Kv(e,t,n){return t.kind==="rename-type"?Bv(e,t,n):t.kind==="rename-field"?Vv(e,t,n):Jv(e,t,n)}function Ct(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function Yo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Tn(e){return Array.isArray(e)?e.map(t=>Yo(t)).filter(t=>t!==void 0):[]}function Yv(e,t){for(let n of Tn(e.fields))Array.isArray(n.required_types)&&(n.required_types=n.required_types.map(r=>Ct(r,t)));for(let n of Tn(e.type_workflows))n.type=Ct(n.type,t)}function Xv(e,t){for(let r of Tn(e.definitions))r.default_status=Ct(r.default_status,t);let n=Yo(e.workflow);if(n)for(let[r,i]of Object.entries(n))n[r]=Ct(i,t);for(let r of Tn(e.type_workflows))Array.isArray(r.allowed_transitions)&&(r.allowed_transitions=r.allowed_transitions.map(i=>Array.isArray(i)?i.map(a=>Ct(a,t)):i))}function Zv(e,t){for(let n of Tn(e.definitions)){for(let r of["required_create_fields","required_create_repeatables"])Array.isArray(n[r])&&(n[r]=n[r].map(i=>Ct(i,t)));for(let r of["options","command_option_policies"])for(let i of Tn(n[r])){let a=r==="options"?"key":"option";i[a]=Ct(i[a],t)}}}function Qv(e,t){let n=Yo(e.options);if(!n)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(n,t.from))return;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);n[t.to]=n[t.from],delete n[t.from];return}let r=t.kind==="rename-type"?"type":"status";n[r]=Ct(n[r],t)}function Jo(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))return e;let r=n;return t.kind==="rename-type"?Yv(r,t):t.kind==="rename-field"?Zv(r,t):Xv(r,t),Qv(r,t),`${JSON.stringify(r,null,2)}
37
+ `}function sp(e,t){if(t.kind==="rename-type"){let r=ot(e).definitions;return{source:r.some(i=>i.name.trim().toLowerCase()===t.from.toLowerCase()),target:r.some(i=>i.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let r=an(e).fields;return{source:r.some(i=>i.key===t.from),target:r.some(i=>i.key===t.to)}}let n=sn(e).statuses;return{source:n.some(r=>r.id===t.from),target:n.some(r=>r.id===t.to)}}function eb(e,t){let n=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(n,t.to)&&!Object.prototype.hasOwnProperty.call(n,t.from)?[]:[t.from,t.to]}function tb(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let n=e;if(!Object.prototype.hasOwnProperty.call(n,t.from))return null;if(Object.prototype.hasOwnProperty.call(n,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:n[t.from],after:void 0},{field:t.to,before:void 0,after:n[t.from]}]}}function cp(e,t){let n=Ko(t.request),r=t.migrationId===void 0?ip(n,t.migrationScope??"plan"):rp(t.migrationId),i=e.map(c=>tb(c,n)).filter(c=>c!==null).sort((c,l)=>c.id.localeCompare(l.id)),a=np("sha256").update(JSON.stringify({migrationId:r,request:n,items:i})).digest("hex"),o=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),s=i.filter(c=>!o.has(c.id));return Object.freeze({migration_id:r,request:n,fingerprint:a,affected_item_count:i.length,pending_item_count:s.length,skipped_completed_count:i.length-s.length,items:Object.freeze(s)})}async function nb(e){let t=W(e.settings,H()),n=[...new Set(Object.values(t.type_to_folder))],r=await hi(e.pmRoot,n),i=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},a=r?await Ed({pmRoot:e.pmRoot,expectedSourceCursor:r.source_cursor,query:i}):null;return a?{items:a.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await st(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function rb(e,t){let n=await V(ap(e,t));if(n===null)return null;try{let r=JSON.parse(n);if(r.schema_version!==1||r.plan.migration_id!==t||!Array.isArray(r.plan.items))throw new TypeError("invalid plan envelope");return r.plan}catch(r){throw new y(`Stored schema migration plan "${t}" is invalid: ${Kc(r)}`,g.GENERIC_FAILURE)}}async function ib(e,t){let n=ap(e,t.migration_id);await Vt.mkdir(Cn.dirname(n),{recursive:!0});let r={schema_version:1,plan:t,created_at:new Date().toISOString()};await Z(n,`${JSON.stringify(r,null,2)}
38
+ `)}function ab(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function ob(e){let t=await we(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new y(`Schema migration item "${e.id}" no longer exists.`,g.NOT_FOUND);return(await ve(t,{schema:e.settings.schema})).document.metadata}function ep(e,t,n){let r=n==="forward"?t.from:t.to,i=n==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===i.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected type "${r}" on item "${e.metadata.id}".`);return e.metadata.type=i,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===i.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==r.toLowerCase())throw new TypeError(`Schema migration expected status "${r}" on item "${e.metadata.id}".`);return e.metadata.status=i,["status"]}let a=e.metadata;if(Object.prototype.hasOwnProperty.call(a,i)&&!Object.prototype.hasOwnProperty.call(a,r))return[];if(!Object.prototype.hasOwnProperty.call(a,r)||Object.prototype.hasOwnProperty.call(a,i))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return a[i]=a[r],delete a[r],[r,i]}function tp(e){return{id:e.id,inspect:async()=>{let t=await Rn(e.filePath),n=sp(t.raw,e.request),r=e.phase==="stage"?n.source&&n.target:!n.source&&n.target;return{state:r?"applied":"pending",...r?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await Rn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Rn(e.filePath);return await Z(e.filePath,Kv(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await op(e.filePath,{exists:t.exists,raw:t.raw})}}}function sb(e){return{id:e.stepId,inspect:async()=>{let t=await Rn(e.filePath);return{state:Jo(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await Rn(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await Rn(e.filePath);return await Z(e.filePath,Jo(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await op(e.filePath,{exists:t.exists,raw:t.raw})}}}function cb(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await C(e.pmRoot),n=W(t,H()).type_to_folder,r=await ob({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id}),i=eb(r,e.request).length===0;return{state:i?"applied":"pending",...i?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await C(e.pmRoot),n=W(t,H()).type_to_folder,r=await ct({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(i){return{changedFields:ep(i,e.request,"forward")}}});return{item_id:e.id,changed_fields:r.changedFields}},compensate:async()=>{let t=await C(e.pmRoot),n=W(t,H()).type_to_folder;await ct({pmRoot:e.pmRoot,settings:t,typeToFolder:n,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(r){return{changedFields:ep(r,e.request,"reverse")}}})}}}async function lb(e){let t=await rb(e.pmRoot,e.migrationId);if(t){if(!ab(t.request,e.request))throw new y(`Schema migration id "${e.migrationId}" already belongs to a different request.`,g.CONFLICT);return{plan:t,stored:!0}}let n=await nb({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...cp(n.items,{migrationId:e.migrationId,request:e.request}),selection_source:n.selectionSource},stored:!1}}async function db(e){let t=sp(await V(e.schemaPath)??"",e.request);if(!t.source)throw new y(`Schema migration source "${e.request.from}" is not a custom definition.`,g.NOT_FOUND);if(t.target)throw new y(`Schema migration target "${e.request.to}" already exists.`,g.CONFLICT);await ib(e.pmRoot,e.plan)}async function ub(e){let t=Ae(e.settings.schema),n=[...new Set([["types",Le.types],["fields",Le.fields],["workflows",Le.workflows]].map(([i,a])=>Ye(e.pmRoot,t.files[i],a)).filter(i=>i!==e.schemaPath))];try{let i=Cn.join(e.pmRoot,"templates"),a=await Vt.readdir(i,{withFileTypes:!0});n.push(...a.filter(o=>o.isFile()&&o.name.toLowerCase().endsWith(".json")).map(o=>Cn.join(i,o.name)))}catch(i){if(typeof i!="object"||i===null||!("code"in i)||!U(i))throw i}n.sort((i,a)=>i.localeCompare(a));let r=[];for(let i of n){let a=await V(i);a!==null&&Jo(a,e.request)!==a&&r.push({filePath:i,beforeRaw:a})}return{paths:n,snapshots:r}}async function mb(e){for(let t of e.snapshots){let n=await Vt.readFile(t.filePath,"utf8"),r=Cn.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await Qa({pmRoot:e.pmRoot,author:e.author,documentPath:r,before:Fi(t.beforeRaw),after:Fi(n),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${r}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function pb(e,t,n){let r=Ko(e),i=L(process.cwd(),n.path);await te(i);let a=t.migrationId===void 0?ip(r,await Vt.realpath(i)):rp(t.migrationId),o=await C(i),s=G(t.author,o.author_default),c=await lb({pmRoot:i,settings:o,migrationId:a,request:r}),l=c.plan;if(t.dryRun===!0)return{...l,action:r.kind,applied:!1,recovered:!1,migrated_item_count:0};let d=qv(i,o,r),u=await Vt.readFile(d,"utf8");c.stored||await db({pmRoot:i,schemaPath:d,request:r,plan:l});let m=await ub({pmRoot:i,schemaPath:d,settings:o,request:r}),f=[tp({id:"stage-schema",filePath:d,request:r,phase:"stage"}),...m.paths.map((w,v)=>sb({filePath:w,request:r,stepId:`reference-${String(v+1).padStart(4,"0")}`})),...l.items.map(w=>cb({pmRoot:i,id:w.id,request:r,author:s,force:t.force===!0})),tp({id:"retire-source",filePath:d,request:r,phase:"retire"})],p=await Qm({pmRoot:i,transactionId:`schema-${a}`,author:s,steps:f,lockTtlSeconds:Math.max(o.locks.ttl_seconds,300),lockWaitMs:o.locks.wait_ms}),h=await Vt.readFile(d,"utf8"),{historyPath:_}=await Qa({pmRoot:i,author:s,documentPath:Cn.relative(i,d).replaceAll("\\","/"),before:Fi(u),after:Fi(h),op:"schema_migration",idempotencyKey:`${l.migration_id}:${l.fingerprint}`,message:`${r.kind}: ${r.from} -> ${r.to}; affected=${l.affected_item_count}`,lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms});return await mb({pmRoot:i,author:s,settings:o,request:r,plan:l,snapshots:m.snapshots}),{...l,action:r.kind,applied:!0,recovered:p.recovered,migrated_item_count:l.affected_item_count,workspace_history_path:_}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a59f90b-0497-530c-93e1-c93cfc8a0016")}catch{}})();var pN=[...Jr,"add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Ui="schema-types",lp="schema-statuses",dp="schema-fields";function Tt(e){return li({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function _N(e,t,n){let r=L(process.cwd(),n.path);await pt(r);let i;try{i=Ha({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(f){throw new y(f instanceof Error?f.message:String(f),g.USAGE)}let a=await C(r),o=Ae(a.schema),s=Ye(r,o.files.types,Le.types),c=[],l=G(t.author,a.author_default),d=Ce(a),u=await re(r,Ui,a.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,a.locks.wait_ms),m;try{let f=await V(s),p;try{p=ot(f)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.GENERIC_FAILURE)}try{dl(i,p);let h=new Map,_=W(a,H());for(let[w,v]of Object.entries(_.type_to_folder)){let S=v.trim().toLowerCase();S.length>0&&!h.has(S)&&h.set(S,w)}ul(i,p,h)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}m=Br(p,i),m.replaced&&m.previousName!==void 0&&m.previousName!==m.definition.name&&c.push(`type_recased:${m.previousName}->${m.definition.name}`),await Tt({pmRoot:r,filePath:s,raw:kt(m.file),op:"schema:add-type",author:l,settings:a}),await mr(r,[m.definition],c,"schema:add-type-folder"),c.push(...await X({path:s,scope:"project",op:"schema:add-type"}))}finally{await u()}return await up(r,c),{action:"add-type",registered:!0,replaced:m.replaced,type:m.definition,file:{path:s,definitions:m.file.definitions.length},warnings:$t(c),generated_at:$()}}async function pt(e){await te(e)}async function up(e,t){try{let n=await Wm(e);n.status==="refreshed"?t.push("merge_fence_refreshed"):n.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function $t(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}async function _b(e,t,n,r){let i=W(t,H()),a=r.trim().toLowerCase();return(await st(e,t.item_format,i.type_to_folder,[],n)).filter(o=>typeof o.type=="string"&&o.type.toLowerCase()===a).length}async function gb(e,t,n,r){let i=W(t,H()),a=_e(n),o=de(r);return(await st(e,t.item_format,i.type_to_folder,[],n)).filter(s=>{let c=typeof s.status=="string"?s.status:"";return(a.alias_to_id.get(de(c))??de(c))===o}).length}async function yb(e,t,n,r,i){if(i.length===0||Wa.has(i))return;let a=await gb(t,n,r,i);a>0&&e.push(`items_using_status:${a}`);let o=wb(r.workflow,i);o.length>0&&e.push(`status_referenced_by_workflow:${o.join(",")}`)}function wb(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,n])=>n!==void 0&&de(n)===t).map(([n])=>n)}async function gN(e,t,n){let r=L(process.cwd(),n.path);await pt(r);let i=await C(r),a=Ae(i.schema),o=Ye(r,a.files.types,Le.types),s=[],c=G(t.author,i.author_default),l=Ce(i),d=await re(r,Ui,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await V(o),f;try{f=ot(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=ml(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.USAGE)}if(u.removed){let p=(u.definition?.name??e??"").trim();if(p.length>0){let h=await _b(r,i,a,p);h>0&&s.push(`items_using_type:${h}`)}await Tt({pmRoot:r,filePath:o,raw:kt(u.file),op:"schema:remove-type",author:c,settings:i}),s.push(...await X({path:o,scope:"project",op:"schema:remove-type"}))}}finally{await d()}return u.removed&&await up(r,s),{action:"remove-type",removed:u.removed,...u.definition?{type:u.definition}:{},file:{path:o,definitions:u.file.definitions.length},warnings:$t(s),generated_at:$()}}function Xo(e,t){return Ye(e,t.files.statuses,Le.statuses)}function Hi(e,t){return Ye(e,t.files.fields,Le.fields)}function mp(e,t){return Ye(e,t.files.types,Le.types)}async function mr(e,t,n,r){for(let i of t){let a=Zc(i.folder??Xc(i.name)),o=fb.join(e,a);await O(o)||(await hb(o,{recursive:!0}),n.push(...await X({path:o,scope:"project",op:r})))}}function Zo(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function vb(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function bb(e){let t=new Map;for(let n of e){let r=de(n.id);if(r.length!==0){t.set(r,r);for(let i of Array.isArray(n.aliases)?n.aliases:[]){let a=de(i);a.length>0&&!t.has(a)&&t.set(a,r)}}}return t}async function yN(e,t,n){let r=L(process.cwd(),n.path);await pt(r);let i;try{i=vl({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}let a=await C(r),o=Ae(a.schema),s=Xo(r,o),c=_e(o);try{Ga(i,c.alias_to_id)}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}let l=vb(c.by_id.get(i.id));if((i.roles??l?.roles??[]).length===0)throw new y(`Status "${i.id}" requires at least one lifecycle role. Re-run with --role active, --role blocked, --role draft, or an appropriate terminal/default role.`,g.USAGE,{code:"status_lifecycle_role_required",examples:[`pm schema add-status "${rn(i.id)}" --role active`,`pm schema add-status "${rn(i.id)}" --role blocked`]});let d=[],u=G(t.author,a.author_default),m=Ce(a),f=await re(r,lp,a.locks.ttl_seconds,u,!!t.force,m.force_required_for_stale_lock,a.locks.wait_ms),p;try{let h=await V(s),_;try{_=sn(h)}catch(v){throw new y(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let w=bb(_.statuses);try{Ga(i,w)}catch(v){throw new y(v instanceof Error?v.message:String(v),g.USAGE)}p=bl(_,i,l),await Tt({pmRoot:r,filePath:s,raw:cn(p.file),op:"schema:add-status",author:u,settings:a}),d.push(...await X({path:s,scope:"project",op:"schema:add-status"}))}finally{await f()}return{action:"add-status",registered:!0,replaced:p.replaced,status:p.definition,file:{path:s,statuses:p.file.statuses.length},warnings:$t(d),generated_at:$()}}async function wN(e,t,n){let r=L(process.cwd(),n.path);await pt(r);let i=await C(r),a=Ae(i.schema),o=Xo(r,a),s=[],c=G(t.author,i.author_default),l=Ce(i),d=await re(r,lp,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await V(o),f;try{f=sn(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=kl(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.USAGE)}if(u.removed){let p=de(u.definition?.id??e);await yb(s,r,i,a,p),await Tt({pmRoot:r,filePath:o,raw:cn(u.file),op:"schema:remove-status",author:c,settings:i}),s.push(...await X({path:o,scope:"project",op:"schema:remove-status"}))}}finally{await d()}return{action:"remove-status",removed:u.removed,...u.definition?{status:u.definition}:{},file:{path:o,statuses:u.file.statuses.length},warnings:$t(s),generated_at:$()}}function pp(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function kb(e,t,n){return{...pp(e),source:t,...n?{extension:n}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function fp(e){return{id:e.id,source:Wa.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function hp(e,t,n){let r=e.toLowerCase();return n.has(r)?"extension":t.has(r)?"custom":"builtin"}function Sb(){let e=new Map,t=H();for(let n of t?.item_types??[]){let r=n.types;if(Array.isArray(r))for(let i of r){if(typeof i!="object"||i===null||Array.isArray(i))continue;let a=i.name;typeof a=="string"&&a.trim().length>0&&e.set(a.trim().toLowerCase(),{layer:n.layer,name:n.name})}}return e}function Eb(e){let t=_e(e),n=[],r=[];for(let i of t.definitions){let a=fp(i);a.source==="builtin"?n.push(a):r.push(a)}return{builtin:n,custom:r}}async function pr(e){let t=L(process.cwd(),e.path);await pt(t);let n=await C(t),r=Ae(n.schema),i=Ye(t,r.files.types,Le.types),a=Xo(t,r),o=W(n,H()),s=Sb(),c=new Set((n.item_types?.definitions??[]).map(l=>l.name.trim().toLowerCase()).filter(l=>l.length>0&&!s.has(l)));return{pmRoot:t,typesPath:i,statusesPath:a,byType:o.by_type,customNames:c,extensionProvenance:s,schema:r}}async function vN(e){let t=await pr(e),n=[],r=[],i=[];for(let s of Object.values(t.byType).sort((c,l)=>c.name.localeCompare(l.name))){let c=hp(s.name,t.customNames,new Set(t.extensionProvenance.keys())),l=pp(s);c==="extension"?i.push(l):c==="custom"?r.push(l):n.push(l)}let a=Eb(t.schema),o=Vr(t.schema).definitions.map(Zo);return{action:"list",builtin:n,custom:r,extension:i,counts:{builtin:n.length,custom:r.length,extension:i.length,total:n.length+r.length+i.length},statuses:{builtin:a.builtin,custom:a.custom,counts:{builtin:a.builtin.length,custom:a.custom.length,total:a.builtin.length+a.custom.length}},fields:{custom:o,counts:{total:o.length}},file:{path:t.typesPath},generated_at:$()}}async function bN(e,t){let n=(e??"").trim();if(n.length===0)throw new y("Type name must not be empty.",g.USAGE);let r=await pr(t),i=Object.values(r.byType).find(a=>a.name.toLowerCase()===n.toLowerCase()||a.aliases.some(o=>o.toLowerCase()===n.toLowerCase()));if(!i)throw new y(`Unknown item type "${n}". Run pm schema list to inspect registered types, or pm schema add-type "${rn(n)}" to register it.`,g.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:kb(i,hp(i.name,r.customNames,new Set(r.extensionProvenance.keys())),r.extensionProvenance.get(i.name.toLowerCase())),file:{path:r.typesPath},generated_at:$()}}async function kN(e,t){let n=de(e);if(n.length===0)throw new y("Status id must not be empty.",g.USAGE);let r=await pr(t),i=_e(r.schema),a=i.alias_to_id.get(n)??n,o=i.by_id.get(a);if(!o)throw new y(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${rn(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:fp(o),file:{path:r.statusesPath},generated_at:$()}}async function SN(e,t,n){let r=L(process.cwd(),n.path);await pt(r);let i;try{i=hl({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(p){throw new y(p instanceof Error?p.message:String(p),g.USAGE)}let a=await C(r),o=Ae(a.schema),s=Hi(r,o),c=[],l=Qr(i.key);l&&c.push(`custom_field_mcp_input_collision:${l.field}:${l.property}:${l.owner}:use=${l.nested_path}`);let d=G(t.author,a.author_default),u=Ce(a),m=await re(r,dp,a.locks.ttl_seconds,d,!!t.force,u.force_required_for_stale_lock,a.locks.wait_ms),f;try{let p=await V(s),h;try{h=an(p)}catch(_){throw new y(_ instanceof Error?_.message:String(_),g.GENERIC_FAILURE)}f=_l(h,i),await Tt({pmRoot:r,filePath:s,raw:on(f.file),op:"schema:add-field",author:d,settings:a}),c.push(...await X({path:s,scope:"project",op:"schema:add-field"}))}finally{await m()}return{action:"add-field",registered:!0,replaced:f.replaced,field:f.definition,file:{path:s,fields:f.file.fields.length},warnings:$t(c),generated_at:$()}}async function xb(e,t,n,r){let i=W(t,H());return(await st(e,t.item_format,i.type_to_folder,[],n)).filter(a=>{let o=a[r];return o==null?!1:Array.isArray(o)?o.length>0:typeof o=="string"?o.trim().length>0:!0}).length}async function EN(e,t,n){let r=L(process.cwd(),n.path);await pt(r);let i=await C(r),a=Ae(i.schema),o=Hi(r,a),s=[],c=G(t.author,i.author_default),l=Ce(i),d=await re(r,dp,i.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,i.locks.wait_ms),u;try{let m=await V(o),f;try{f=an(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.GENERIC_FAILURE)}try{u=gl(f,e)}catch(p){throw new y(p instanceof Error?p.message:String(p),g.USAGE)}if(u.removed){let p=de(u.definition?.key??e),h=de(u.definition?.metadata_key??u.definition?.front_matter_key??p);if(h.length>0){let _=await xb(r,i,a,h);_>0&&s.push(`items_using_field:${_}`)}await Tt({pmRoot:r,filePath:o,raw:on(u.file),op:"schema:remove-field",author:c,settings:i}),s.push(...await X({path:o,scope:"project",op:"schema:remove-field"}))}}finally{await d()}return{action:"remove-field",removed:u.removed,...u.definition?{field:u.definition}:{},file:{path:o,fields:u.file.fields.length},warnings:$t(s),generated_at:$()}}async function xN(e){let t=await pr(e),n=Vr(t.schema).definitions.map(Zo);return{action:"list-fields",fields:n,counts:{total:n.length},file:{path:Hi(t.pmRoot,t.schema)},generated_at:$()}}async function IN(e,t){let n=de(e);if(n.length===0)throw new y("Field key must not be empty.",g.USAGE);let r=await pr(t),i=Vr(r.schema).by_key.get(n);if(!i)throw new y(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${rn(e??"")}" to register it.`,g.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Zo(i),file:{path:Hi(r.pmRoot,r.schema)},generated_at:$()}}async function AN(e,t,n){let r=L(process.cwd(),n.path);await pt(r);let i;try{let h=fl(e);if(h===void 0)throw new Error(`Type preset name is required. Allowed: ${pl.join(", ")}.`);i=h}catch(h){throw new y(h instanceof Error?h.message:String(h),g.USAGE)}let a=await C(r),o=Ae(a.schema),s=mp(r,o),c=[],l=G(t.author,a.author_default),d=Ce(a),u=[],m=[],f,p=await re(r,Ui,a.locks.ttl_seconds,l,!!t.force,d.force_required_for_stale_lock,a.locks.wait_ms);try{let h=await V(s),_;try{_=ot(h)}catch(v){throw new y(v instanceof Error?v.message:String(v),g.GENERIC_FAILURE)}let w=_;for(let v of za(i)){let S=Br(w,v);w=S.file,(S.replaced?m:u).push(S.definition.name)}f=w.definitions.length,await Tt({pmRoot:r,filePath:s,raw:kt(w),op:"schema:apply-preset",author:l,settings:a}),await mr(r,za(i),c,"schema:apply-preset-folder"),c.push(...await X({path:s,scope:"project",op:"schema:apply-preset"}))}finally{await p()}return{action:"apply-preset",preset:i,registered:u,replaced:m,file:{path:s,definitions:f},warnings:$t(c),generated_at:$()}}function Ib(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new y("--min-count must be a positive integer (>= 1).",g.USAGE);return e}async function RN(e,t){let n=L(process.cwd(),t.path);await pt(n);let r=await C(n),i=Ae(r.schema),a=mp(n,i),o=Ib(e.minCount),s=W(r,H()),c=(await st(n,r.item_format,s.type_to_folder,[],i)).map(v=>typeof v.title=="string"?v.title:""),l=Gm(c,{minCount:o}),d=[],u=[],m=[],f=[],p;if(!e.apply){let v;try{v=ot(await V(a))}catch(S){throw new y(S instanceof Error?S.message:String(S),g.GENERIC_FAILURE)}return p=v.definitions.length,{action:"infer-types",applied:!1,min_count:o,candidates:l,registered:u,replaced:m,skipped:f,file:{path:a,definitions:p},warnings:d,generated_at:$()}}let h=G(e.author,r.author_default),_=Ce(r),w=await re(n,Ui,r.locks.ttl_seconds,h,!!e.force,_.force_required_for_stale_lock,r.locks.wait_ms);try{let v=await V(a),S;try{S=ot(v)}catch(x){throw new y(x instanceof Error?x.message:String(x),g.GENERIC_FAILURE)}let k=S;for(let x of l){if(x.shadows_builtin){f.push({name:x.name,reason:"shadows_builtin"});continue}let D;try{D=Ha({name:x.name})}catch{f.push({name:x.name,reason:"invalid_type_token"});continue}let E=Br(k,D);k=E.file,(E.replaced?m:u).push(E.definition.name)}p=k.definitions.length,await Tt({pmRoot:n,filePath:a,raw:kt(k),op:"schema:infer-types",author:h,settings:r}),await mr(n,k.definitions.filter(x=>u.includes(x.name)||m.includes(x.name)),d,"schema:infer-types-folder"),d.push(...await X({path:a,scope:"project",op:"schema:infer-types"}))}finally{await w()}return{action:"infer-types",applied:!0,min_count:o,candidates:l,registered:u,replaced:m,skipped:f,file:{path:a,definitions:p},warnings:$t(d),generated_at:$()}}import _p from"node:fs/promises";import Qo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cf1403b0-7b07-5f00-9523-87bc727dd7fa")}catch{}})();function Oe(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function A(e){return e.trim().toLowerCase()}function zi(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-"),n=0;for(;t[n]==="-";)n+=1;let r=t.length;for(;r>n&&t[r-1]==="-";)r-=1;let i=t.slice(n,r);if(i.length===0)throw new y("Extension manifest name must resolve to a non-empty directory name.",g.USAGE);if(i==="."||i==="..")throw new y('Extension manifest name must not resolve to "." or "..".',g.USAGE);return i}function es(e){return rl(e)}async function Ab(e){try{let t=JSON.parse(await _p.readFile(Qo.join(e,"package.json"),"utf8")),n=typeof t.name=="string"&&/^(?:@[a-z0-9._~-]+\/)?[a-z0-9._~-]+$/iu.test(t.name)?t.name:void 0;return{...n?{package_name:n}:{},has_build_script:["build","prepare","prepack"].some(r=>typeof t.scripts?.[r]=="string")}}catch{return{has_build_script:!1}}}async function Rb(e,t,n){if(n.source_kind!=="github"||typeof n.source_root!="string")return new y(`Extension entry file is missing at "${t}".`,g.USAGE);let r=await Ab(n.source_root),i=r.package_name?`pm install npm:${r.package_name}`:void 0,a=n.source_input??n.source_root;return new y(`Extension entry "${e.entry}" is absent from GitHub source "${a}". pm install copies GitHub repositories without running package scripts${r.has_build_script?", and this package declares a build or publish script":""}. ${i?`Try "${i}" if the package is published, or install a locally built directory.`:"Build the source locally and install that directory, or use its published npm: package."}`,g.USAGE,{code:"github_source_entry_unbuilt",required:"Use a GitHub tree with committed runtime output, a published npm artifact, or a locally built source directory.",why:"GitHub installation is a source copy and never executes untrusted package build scripts.",examples:i?[i,`pm install ${n.source_root}`]:[`pm install ${n.source_root}`],nextSteps:i?[`Retry with ${i}.`,"Or build the repository locally, then install its directory."]:["Build the repository locally, then install its directory.","If it is published, retry with pm install npm:<package-name>."],recovery:{attempted_command:`pm install ${a}`,normalized_args:["install",a],...i?{next_best_command:i}:{}}})}async function $n(e,t={}){let n=Qo.join(e,"manifest.json");if(!await O(n))throw new y(`Extension manifest is missing at "${n}".`,g.USAGE);let r;try{r=JSON.parse(await _p.readFile(n,"utf8"))}catch(o){throw new y(`Failed to parse extension manifest at "${n}": ${Cb(o)}`,g.USAGE)}let i=es(r);if(!i)throw new y(`Extension manifest at "${n}" is invalid.`,g.USAGE);let a=Qo.resolve(e,i.entry);if(!fe(e,a))throw new y(`Extension entry "${i.entry}" resolves outside extension directory "${e}".`,g.USAGE);if(!await O(a))throw await Rb(i,a,t);if(!await al(e,a))throw new y(`Extension entry "${i.entry}" resolves outside extension directory after symlink resolution.`,g.USAGE);return{directory:e,manifest_path:n,entry_path:a,manifest:i}}function Cb(e){return e instanceof Error?e.message:String(e)}import ts from"node:fs/promises";import Tb from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="57d830e7-a4e2-56f5-a89b-ae4403e256ce")}catch{}})();var $b=".managed-extensions.json",Wi=1;function fr(e){return Tb.join(e,$b)}function Ob(){return{version:Wi,updated_at:$(),entries:[]}}function hr(e){return[...e].sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let i=t.name.localeCompare(n.name);return i!==0?i:t.directory.localeCompare(n.directory)})}function gp(e,t){return e.kind!==t.kind||e.input!==t.input||e.location!==t.location?!1:e.kind==="npm"&&t.kind==="npm"?e.package===t.package&&e.version===t.version:e.kind==="github"&&t.kind==="github"?e.repository===t.repository&&e.ref===t.ref&&e.subpath===t.subpath&&e.commit===t.commit:e.kind==="builtin"&&t.kind==="builtin"?e.name===t.name:!0}function De(e){return typeof e=="string"?e:void 0}function Db(e){return typeof e.name=="string"&&e.name.trim().length>0&&typeof e.directory=="string"&&e.directory.trim().length>0&&(e.scope==="project"||e.scope==="global")&&typeof e.manifest_version=="string"&&typeof e.manifest_entry=="string"&&Array.isArray(e.capabilities)&&e.capabilities.every(t=>typeof t=="string")&&typeof e.installed_at=="string"&&typeof e.updated_at=="string"}function Pb(e){if(typeof e!="object"||e===null)return null;let t=e;return t.kind!=="local"&&t.kind!=="github"&&t.kind!=="npm"&&t.kind!=="builtin"||typeof t.input!="string"||typeof t.location!="string"?null:{kind:t.kind,input:t.input,location:t.location,name:De(t.name),package:De(t.package),version:De(t.version),repository:De(t.repository),owner:De(t.owner),repo:De(t.repo),ref:De(t.ref),subpath:De(t.subpath),commit:De(t.commit)}}function Nb(e){if(typeof e!="object"||e===null)return null;let t=e;if(!Db(t))return null;let n=Pb(t.source);if(!n)return null;let r=tl(t.contributions);return r===null?null:{name:t.name.trim(),directory:t.directory.trim(),scope:t.scope,manifest_version:t.manifest_version,manifest_entry:t.manifest_entry,capabilities:Oe(t.capabilities),contributions:r,installed_at:t.installed_at,updated_at:t.updated_at,source:n,last_update_check_at:De(t.last_update_check_at),last_update_remote_commit:De(t.last_update_remote_commit),update_available:typeof t.update_available=="boolean"||t.update_available===null?t.update_available:void 0,update_error:De(t.update_error)}}function Lb(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==Wi||!Array.isArray(t.entries))return null;let n=[];for(let r of t.entries){let i=Nb(r);i&&n.push(i)}return{version:Wi,updated_at:De(t.updated_at)??$(),entries:hr(n)}}async function be(e){let t=fr(e),n=Ob();try{let r=await ts.readFile(t,"utf8"),i=JSON.parse(r),a=Lb(i);if(!a)throw new y(`Managed extension state file "${t}" has an invalid schema. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE);return{path:t,state:a,warnings:[]}}catch(r){if(r instanceof y)throw r;if(typeof r=="object"&&r!==null&&"code"in r&&U(r))return{path:t,state:n,warnings:[]};throw new y(`Managed extension state file "${t}" could not be read. Repair or remove it before mutating extension state.`,g.GENERIC_FAILURE)}}async function Jt(e,t){let n=fr(e),r={version:Wi,updated_at:$(),entries:hr(t.entries)};await ts.mkdir(e,{recursive:!0}),await ts.writeFile(n,`${JSON.stringify(r,null,2)}
39
+ `,"utf8")}function _r(e,t){let n=e.entries.filter(r=>A(r.name)!==A(t.name)&&A(r.directory)!==A(t.directory));return n.push(t),{...e,updated_at:$(),entries:hr(n)}}async function yp(e,t,n,r){let i=t.entries.find(o=>A(o.name)===A(n));if(!i)return t;let a=_r(t,{...i,contributions:r});return await Jt(e,a),a}import{execFile as Vb}from"node:child_process";import K from"node:fs/promises";import ss from"node:os";import j from"node:path";import{fileURLToPath as Jb}from"node:url";import{promisify as Kb}from"node:util";import Yb from"npm-package-arg";import{extract as Xb,list as Zb}from"tar";import Mb from"node:fs/promises";import Ge from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c9a362e5-6eb5-52dc-aa74-6c6c0df2c291")}catch{}})();var jb="PM_CLI_PACKAGE_ROOT",wp={beads:{package_directory:"pm-beads",legacy_extension_directory:"beads"},todos:{package_directory:"pm-todos",legacy_extension_directory:"todos"}},Fb=new Set(["*","all"]);function ns(){let e=[],t=process.env[jb];return typeof t=="string"&&t.trim().length>0&&e.push(Ge.resolve(t.trim())),e.push(Ne(import.meta.url,["../../.."])),[...new Set(e)]}async function gr(e){let t=e.trim().toLowerCase(),n=await bp(t);if(n)return n;let r=wp[t];if(!r)return null;for(let i of ns()){let a=Ge.join(i,".agents","pm","extensions",r.legacy_extension_directory);if(await O(Ge.join(a,"manifest.json")))return a}return null}function vp(e){return Fb.has(e.trim().toLowerCase())}function Ub(e){return e.replace(/^pm-/i,"").trim().toLowerCase()}async function Hb(e,t){let n=await Mb.readdir(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||!r.name.startsWith("pm-"))continue;let i=Ge.join(e,r.name);if(!await O(Ge.join(i,"package.json")))continue;let a=await Gr(i),o=a.aliases&&a.aliases.length>0?a.aliases:[Ub(r.name)];for(let s of o){let c=s.trim().toLowerCase();c.length===0||t.has(c)||t.set(c,{alias:c,package_directory:r.name,package_root:i,package_name:a.package_name??null})}}}async function rs(){let e=new Map;for(let t of ns()){let n=Ge.join(t,"packages");await O(n)&&await Hb(n,e)}for(let[t,n]of Object.entries(wp))if(!e.has(t))for(let r of ns()){let i=Ge.join(r,"packages",n.package_directory);if(await O(Ge.join(i,"package.json"))){e.set(t,{alias:t,package_directory:n.package_directory,package_root:i,package_name:null});break}}return[...e.values()].sort((t,n)=>t.alias.localeCompare(n.alias))}async function Gi(){return(await rs()).map(e=>e.alias)}async function bp(e){let t=e.trim().toLowerCase();return(await rs()).find(n=>n.alias===t||n.package_directory.toLowerCase()===t||n.package_name?.toLowerCase()===t)?.package_root??null}async function kp(e){let t=await bp(e);return t?(await Gr(t)).package_name??null:null}async function Sp(e){let t=await gr(e);if(!t)return null;try{let n=await qr(t);return n.length!==1?null:(await $n(n[0])).manifest.name}catch{return null}}function zb(e){return{docs:e.catalog?.links?.docs??e.package_homepage,npm:e.catalog?.links?.npm??(e.package_name&&e.package_private!==!0?`https://www.npmjs.com/package/${encodeURIComponent(e.package_name)}`:void 0),repository:e.catalog?.links?.repository??e.package_repository_url,report:e.catalog?.links?.report??e.package_bugs_url}}function Wb(e,t,n,r,i,a){let o=r==="global"?"--global":"--project",s=Object.fromEntries(Ua.filter(c=>c!=="extensions").map(c=>[c,e.resources[c]??[]]).filter(([,c])=>Array.isArray(c)&&c.length>0));return{alias:t.alias,aliases:n,bundled:!0,available:!0,installed:n.some(c=>i.has(c))||a.has(Ge.resolve(t.package_root)),install_target:t.alias,install_command:`pm install ${t.alias} ${o}`,package_name:e.package_name,package_version:e.package_version,description:e.catalog?.summary??e.package_description,keywords:e.package_keywords??[],resources:e.resources,installable_resources:{extensions:e.resources.extensions??[]},metadata_only_resources:s,catalog:{display_name:e.catalog?.display_name,category:e.catalog?.category,tags:e.catalog?.tags??e.package_keywords??[],links:zb(e),media:e.catalog?.media}}}async function Ep(e,t,n={}){let r=nn(L(process.cwd(),t.path),process.cwd()),i=e==="global"?r.global:r.project,a=await be(i),o=new Set(a.state.entries.filter(m=>m.scope===e).filter(m=>m.source.kind!=="builtin").map(m=>Ge.resolve(m.source.location))),s=new Set(a.state.entries.filter(m=>m.scope===e&&m.source.kind==="builtin").flatMap(m=>[m.source.name,m.source.input,m.source.location]).filter(m=>typeof m=="string"&&m.trim().length>0).map(m=>m.trim().toLowerCase())),c=[],l=new Map;for(let m of await rs()){let f=Ge.resolve(m.package_root),p=l.get(f)??[];p.push(m),l.set(f,p)}for(let m of l.values()){let f=m[0],p=m.map(_=>_.alias).sort((_,w)=>_.localeCompare(w)),h=await Gr(f.package_root);c.push(Wb(h,f,p,e,s,o))}let d=qb(n.fields),u=d?c.map(m=>Bb(m,d)):c;return{total:u.length,scope:e,installable_resource_kinds:["extensions"],metadata_only_resource_kinds:Ua.filter(m=>m!=="extensions"),packages:u}}var Gb=new Set(["alias","aliases","bundled","available","installed","install_target","install_command","package_name","package_version","description","keywords","resources","installable_resources","metadata_only_resources","catalog","category","display_name"]);function qb(e){if(e===void 0)return;let t=zd(e);if(t.length===0)throw new y("Package catalog --fields requires a comma-separated list of field names",g.USAGE);let n=t.filter(r=>!Gb.has(r));if(n.length>0)throw new y(`Unknown package catalog --fields value(s): ${n.join(", ")}`,g.USAGE,{examples:["pm package list --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"]});return t}function Bb(e,t){let n={};for(let r of t)r==="category"?n[r]=e.catalog?.category??null:r==="display_name"?n[r]=e.catalog?.display_name??null:n[r]=e[r]??null;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="db10bb85-f21c-58b1-8b78-8ce1024b3e08")}catch{}})();var Ip=Kb(Vb),Bi="@unbrained/pm-cli",Qb={maxArchiveBytes:64*1024*1024,maxEntries:4096,maxExpandedBytes:256*1024*1024,maxEntryBytes:64*1024*1024},is;async function Ap(e,t=process.cwd()){let n=e.trim();if(!/^(@[^/\\\s]+\/[^/\\\s]+|[^@/\\\s][^/\\\s]*)$/u.test(n))return null;let r=j.resolve(t);for(;;){let i=j.join(r,"node_modules",...n.split("/")),a=j.join(i,"package.json");if(await O(a))try{let s=JSON.parse(await K.readFile(a,"utf8"));if(s.name===n)return{package:n,...typeof s.version=="string"?{version:s.version}:{},directory:i}}catch{return null}let o=j.dirname(r);if(o===r)return null;r=o}}function as(e,t,n){let r=e.split("/").map(l=>l.trim()).filter(l=>l.length>0);if(r.length<2)return null;let i=r[0],a=r[1].replace(/\.git$/i,"");if(i.length===0||a.length===0)return null;let o=r.slice(2),s,c;return o[0]==="tree"&&o.length>=2?(s=o[1],c=o.slice(2).join("/")):o.length>0&&(c=o.join("/")),typeof n=="string"&&n.trim().length>0&&(s=n.trim()),{kind:"github",input:t,owner:i,repo:a,repository:`https://github.com/${i}/${a}.git`,ref:s,subpath:c&&c.length>0?c:void 0}}function ek(e,t,n){let r=e.slice(4).trim();if(r.length===0)throw new y('npm package source must include a package spec after "npm:".',g.USAGE);if(t)throw new y('Options "--gh/--github" cannot be combined with npm: package sources.',g.USAGE);if(n)throw new y('Option "--ref" cannot be combined with npm: package sources.',g.USAGE);return{kind:"npm",input:e,spec:r}}function Vi(e,t={}){let n=e.trim();if(n.length===0)throw new y("Extension source is required for --install.",g.USAGE);let r=typeof t.ref=="string"&&t.ref.trim().length>0?t.ref.trim():void 0;if(n.startsWith("npm:"))return ek(n,t.forceGithub===!0,r);let i=(()=>{try{let o=new URL(n);if(o.hostname!=="github.com")return null;let s=o.pathname.replace(/^\/+/,"");return as(s,n,r)}catch{return null}})();if(i)return i;let a=n.startsWith("github.com/")?n.slice(11):null;if(a){let o=as(a,n,r);if(!o)throw new y(`Invalid GitHub source "${n}".`,g.USAGE);return o}if(t.forceGithub){let o=as(n,n,r);if(!o)throw new y(`Invalid GitHub shorthand "${n}".`,g.USAGE);return o}if(/^https?:\/\//i.test(n))throw new y(`Unsupported extension source URL "${n}". Supported remote source host: github.com.`,g.USAGE);return{kind:"local",input:n,absolute_path:j.resolve(process.cwd(),n)}}async function qi(e,t=Ip,n){try{return((await t("git",e,{encoding:"utf8",timeout:n})).stdout??"").trim()}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr):"",a=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new y(`Git command failed: git ${e.join(" ")}
40
+ ${a}`,g.GENERIC_FAILURE)}}function tk(e=process.platform){return e==="win32"?"npm.cmd":"npm"}function nk(e=process.platform){return e==="win32"}async function Rp(e,t,n=Ip,r=process.platform,i=process.env){let a=tk(r),o=Object.fromEntries(Object.entries(i).filter(([s])=>s.toLowerCase()!=="npm_config_allow_scripts"));o.NPM_CONFIG_ALLOW_SCRIPTS="";try{return((await n(a,e,{cwd:t,encoding:"utf8",env:o,shell:nk(r)})).stdout??"").trim()}catch(s){let c=typeof s=="object"&&s!==null&&"stderr"in s?String(s.stderr):"",l=c.trim().length>0?c.trim():s instanceof Error?s.message:String(s);throw new y(`npm command failed: ${a} ${e.join(" ")}
41
+ ${l}`,g.GENERIC_FAILURE)}}function Cp(e){let t=e.trim(),n=t.includes("@file:")?t.slice(0,t.lastIndexOf("@file:")):t;return n.startsWith("@")?n.match(/^(@[^/@\s]+\/[^/@\s]+)/)?.[1]??n:n.match(/^([^/@\s]+)/)?.[1]??n}function Tp(e){let t="@file:",n=e.lastIndexOf(t);return n>0&&e.slice(0,n).trim().length>0&&e.slice(n+t.length).trim().length>0}function rk(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return t.includes("npm err! code e404")||t.includes("404 not found")||t.includes("is not in this registry")}function ik(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase();return rk(e)||t.includes("not found")}function ak(e){let t=e.trim().toLowerCase();return t.startsWith("@unbrained/pm-")||t.startsWith("pm-")}function ok(e){let t=Cp(e),n=ak(t),r=t.replace(/^.*\//,""),i=n?`github.com/unbraind/${r}`:void 0,a=i?`pm install --project ${i}`:void 0;return{message:n?`npm package "${e}" was not found in the registry. If this is an unpublished first-party pm package, install its GitHub repository instead.`:`npm package "${e}" was not found in the registry.`,context:{code:"npm_package_not_found",required:"Use an install source that exists, or publish the npm package before installing it with npm:<name>.",why:"Classifying npm 404s avoids repeated registry retries and gives agents a deterministic fallback path.",examples:a?[a,"pm package catalog --project --json"]:[`npm view ${t}`,"pm package catalog --project --json"],nextSteps:a?[`Try ${a} if the repository exists.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."]:[`Verify ${t} exists in the npm registry and that you have access to it.`,"Use pm package catalog --project --json to inspect bundled package aliases before installing."],recovery:{attempted_command:`pm install --project npm:${e}`,normalized_args:["install","--project",`npm:${e}`],...i&&a?{fallback_candidates:[{source:i,command:a,reason:"canonical first-party GitHub repository fallback for unpublished pm packages"}],next_best_command:a}:{}}}}}function sk(e,t){if(!ik(t))return null;let n=ok(e);return new y(n.message,g.NOT_FOUND,n.context)}async function $p(e){if(j.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")){let t=j.resolve(process.cwd(),e);return await O(t)?t:null}try{let t=new URL(e);if(t.protocol==="file:"){let n=Jb(t);return await O(n)?n:null}}catch{}if(!/^[a-z][a-z0-9+.-]*:/i.test(e)){let t=j.resolve(process.cwd(),e);if(await O(t))return t}return null}async function ck(e){let t=await $p(e);if(t)return t;let n=lk(e);return n!==e?n:(/^[a-z][a-z0-9+.-]*:/i.test(e),e)}function lk(e,t=process.cwd()){let n="@file:",r=e.lastIndexOf(n);if(!Tp(e))return e;let i=e.slice(0,r),a=e.slice(r+n.length);if(a.startsWith("//")&&!a.startsWith("///"))return e;if(!a.startsWith("/"))return`${i}@${j.resolve(t,a)}`;let o;try{o=decodeURIComponent(new URL(`file:${a}`).pathname)}catch{return e}let s=/^\/[A-Za-z]:/.test(o)?o.slice(1):o;return`${i}@${s}`}function xp(e,t){let n=j.resolve(e,t),r=j.relative(e,n);if(r.length===0||r===".."||r.startsWith(`..${j.sep}`)||j.isAbsolute(r))throw new y("npm pack reported a package archive outside its isolated destination.",g.GENERIC_FAILURE,{code:"npm_package_archive_unsafe",required:"Retry with a trusted npm client that writes its archive inside the requested pack destination.",why:"pm will not read a package-manager artifact outside the isolated directory created for this install."});return n}function dk(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e;if(!(typeof n.filename!="string"||n.filename.trim().length===0))return{...t===void 0?{}:{key:t},filename:n.filename,...typeof n.name=="string"?{name:n.name}:{},...typeof n.version=="string"?{version:n.version}:{}}}function uk(e){return(Array.isArray(e)?e.map(t=>({value:t})):typeof e=="object"&&e!==null?Object.entries(e).map(([t,n])=>({key:t,value:n})):[]).flatMap(({key:t,value:n})=>{let r=dk(n,t);return r?[r]:[]})}function mk(e,t){let n=t?.trim().toLowerCase(),r=n?e.filter(o=>{let s=o.name?.trim().toLowerCase();return s!==void 0?s===n:o.key?.trim().toLowerCase()===n}):[];if(r.length===1)return r[0];if(e.length!==1)return;let i=e[0],a=i.name??i.key;return n&&a!==void 0&&a.trim().toLowerCase()!==n?void 0:i}function pk(e,t,n){let r;try{r=JSON.parse(e)}catch{let o=e.split(/\r?\n/).map(s=>s.trim()).filter(s=>s.length>0).at(-1);if(!o)throw new y("npm pack did not report a tarball filename.",g.GENERIC_FAILURE);return{tarball:xp(t,o)}}let i=uk(r),a=mk(i,n);if(!a)throw new y("npm pack --json returned an unsupported or ambiguous package receipt.",g.GENERIC_FAILURE,{code:"npm_pack_json_shape_unsupported",required:"Use an npm client that returns an array of package receipts or an object keyed by package name, with exactly one requested package entry containing filename.",why:`Well-formed JSON contained ${i.length} usable package receipt(s), but pm could not select ${n??"one package"} deterministically.`});return{tarball:xp(t,a.filename),package:a.name??a.key,version:a.version}}async function fk(e){return hk(e,Rp)}async function hk(e,t){let n=await $p(e.spec);if(n){if((await K.stat(n)).isFile()&&Op(n))return os(n);let a=j.join(n,"package.json"),o=await O(a)?JSON.parse(await K.readFile(a,"utf8")):{};return{directory:await Ji(n,e.input),package:typeof o.name=="string"?o.name:void 0,version:typeof o.version=="string"?o.version:void 0,cleanup:async()=>{}}}let r=await K.mkdtemp(j.join(ss.tmpdir(),"pm-npm-package-source-")),i=j.join(r,"pack");await K.mkdir(i,{recursive:!0});try{let a=await ck(e.spec),o=await t(["pack",a,"--json","--pack-destination",i]),s=pk(o,i,Tp(e.spec)?void 0:Cp(e.spec));if(!await O(s.tarball))throw new y("npm pack did not create its reported package archive.",g.GENERIC_FAILURE,{code:"npm_package_archive_missing",required:"Retry the npm package install with a healthy registry and writable temporary directory.",why:"The package manager reported a tarball filename that was absent before validation, so pm cannot safely extract or install it."});let c=await os(s.tarball);return{directory:c.directory,package:s.package??c.package,version:s.version??c.version,cleanup:async()=>{try{await c.cleanup()}finally{await K.rm(r,{recursive:!0,force:!0})}}}}catch(a){throw await K.rm(r,{recursive:!0,force:!0}),sk(e.spec,a)||a}}function Op(e){let t=e.toLowerCase();return t.endsWith(".tgz")||t.endsWith(".tar.gz")}function ft(e){throw new y(e,g.USAGE,{code:"local_package_archive_unsafe",required:"Use a bounded npm .tgz or .tar.gz archive with one package/ root and no links or escaping paths.",why:"Package archives are untrusted input and must be validated before any entry reaches the filesystem."})}function _k(e,t,n){if(e.meta)return;n.entries+=1,n.entries>t.maxEntries&&ft(`Local package archive exceeds the ${t.maxEntries} entry limit.`);let r=e.path,i=r.split("/");(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||i.some(a=>a===".."))&&ft(`Local package archive contains an escaping path: "${r}".`),i[0]!=="package"&&ft(`Local package archive entry "${r}" is outside the required package/ root.`),(e.type==="SymbolicLink"||e.type==="Link")&&ft(`Local package archive link "${r}" is not supported.`),e.type!=="File"&&e.type!=="OldFile"&&e.type!=="Directory"&&ft(`Local package archive entry "${r}" uses unsupported type "${e.type}".`),e.size>t.maxEntryBytes&&ft(`Local package archive entry "${r}" exceeds the ${t.maxEntryBytes} byte entry limit.`),n.expandedBytes+=e.size,n.expandedBytes>t.maxExpandedBytes&&ft(`Local package archive exceeds the ${t.maxExpandedBytes} expanded byte limit.`),r==="package/package.json"&&(n.packageJsonEntries+=1)}async function os(e,t=Qb){(await K.stat(e)).size>t.maxArchiveBytes&&ft(`Local package archive exceeds the ${t.maxArchiveBytes} archive byte limit.`);let n=await K.mkdtemp(j.join(ss.tmpdir(),"pm-local-package-archive-")),r=j.join(n,"extract");await K.mkdir(r,{recursive:!0});let i={entries:0,expandedBytes:0,packageJsonEntries:0},a;try{if(await Zb({file:e,strict:!0,maxDecompressionRatio:100,onReadEntry:l=>{if(a===void 0)try{_k(l,t,i)}catch(d){a=d}}}),a!==void 0)throw a;i.packageJsonEntries!==1&&ft(`Local package archive must contain exactly one package/package.json entry; found ${i.packageJsonEntries}.`),await Xb({file:e,cwd:r,strict:!0,preservePaths:!1,preserveOwner:!1,noMtime:!0,unlink:!0,maxDepth:64,maxDecompressionRatio:100});let o=j.join(r,"package"),s=j.join(o,"package.json"),c=JSON.parse(await K.readFile(s,"utf8"));return await gk(o),{directory:await Ji(o,e),package:typeof c.name=="string"?c.name:void 0,version:typeof c.version=="string"?c.version:void 0,cleanup:async()=>{await K.rm(n,{recursive:!0,force:!0})}}}catch(o){throw await K.rm(n,{recursive:!0,force:!0}),o}}async function gk(e,t=Rp){let n=j.join(e,"package.json");if(!await O(n))return;let r;try{r=JSON.parse(await K.readFile(n,"utf8"))}catch{return}if(typeof r!="object"||r===null)return;let i=r,a=Sk(i),o=yk(i);if(a.length===0&&!o)return;let s={...r};delete s.devDependencies;let c={...s};wk(c),await K.writeFile(n,`${JSON.stringify(c,null,2)}
42
+ `,"utf8");try{await Promise.all([K.rm(j.join(e,"package-lock.json"),{force:!0}),K.rm(j.join(e,"npm-shrinkwrap.json"),{force:!0})]),a.length>0&&await t(["install","--ignore-scripts","--no-audit","--fund=false","--package-lock=false","--no-save","--omit=peer","--"],e),o&&await vk(e)}finally{await K.writeFile(n,`${JSON.stringify(s,null,2)}
43
+ `,"utf8")}}function yk(e){for(let t of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(typeof t=="object"&&t!==null&&Bi in t)return!0;return!1}function wk(e){for(let t of["dependencies","optionalDependencies","peerDependencies"]){let n=e[t];if(typeof n!="object"||n===null)continue;let r={...n};delete r[Bi],Object.keys(r).length===0?delete e[t]:e[t]=r}}async function vk(e){let t=Ne(import.meta.url,["../../.."]),[n,r]=Bi.split("/"),i=j.join(e,"node_modules",n),a=j.join(i,r);await K.mkdir(i,{recursive:!0}),await K.rm(a,{recursive:!0,force:!0}),await K.symlink(t,a,bk(process.platform))}function bk(e){return e==="win32"?"junction":"dir"}function kk(e,t){if(e.startsWith("-"))throw new y(`Extension runtime dependency name "${e}" is unsafe because npm could interpret it as a command-line option.`,g.USAGE,{code:"extension_dependency_name_unsafe",required:"Use a valid npm package name that does not begin with a dash.",why:"Extension manifests are untrusted input and dependency names must never become npm options."});if([...t].some(n=>{let r=n.charCodeAt(0);return r<=31||r===127||"&|;()`\"'".includes(n)}))throw new y(`Extension runtime dependency "${e}" has an unsafe version specifier.`,g.USAGE,{code:"extension_dependency_version_unsafe",required:"Use an npm version, range, dist-tag, URL, or file specifier without shell metacharacters.",why:"npm.cmd requires a command shell on Windows, so untrusted shell metacharacters cannot be forwarded."});try{Yb.resolve(e,t)}catch{throw new y(`Extension runtime dependency "${e}@${t}" is not a valid npm dependency specifier.`,g.USAGE,{code:"extension_dependency_spec_invalid",required:"Use a valid npm package name and npm-supported version, range, dist-tag, URL, or file specifier.",why:"Only grammar-validated dependency specs may be written to the isolated runtime install manifest."})}return`${e}@${t}`}function Sk(e){let t=new Map;for(let n of[e.dependencies,e.optionalDependencies,e.peerDependencies])if(!(typeof n!="object"||n===null))for(let[r,i]of Object.entries(n)){if(r===Bi||typeof i!="string"||i.trim().length===0||t.has(r))continue;let a=i.trim();t.set(r,kk(r,a))}return[...t.values()]}async function Ji(e,t){let n=await qr(e);if(n.length===1)return n[0];if(n.length>1){let r=n.map(i=>j.relative(e,i).replaceAll(j.sep,"/")).sort((i,a)=>i.localeCompare(a));throw new y(`Package source "${t}" contains multiple extension manifests. Provide an explicit extension path. Candidates: ${r.join(", ")}`,g.USAGE)}throw new y(`Unable to locate a pm extension manifest in package source "${t}". Package installs currently activate only extension resources, so add package.json pm.extensions or an extensions/ directory. Metadata-only resources like pm.docs/pm.examples are catalog metadata and do not activate commands.`,g.USAGE)}async function Ek(e,t){let n=[];t.subpath&&(n.push(t.subpath),n.push(j.posix.join(".agents/pm/extensions",t.subpath)),n.push(j.posix.join(".custom/pm-extensions",t.subpath)),n.push(j.posix.join(".custom/pm-extension",t.subpath)));for(let i of n){let a=j.resolve(e,i);if(fe(e,a)&&await O(j.join(a,"manifest.json")))return{directory:a,resolved_subpath:i}}if(await O(j.join(e,"manifest.json")))return{directory:e,resolved_subpath:"."};let r=await Ji(e,t.input);return{directory:r,resolved_subpath:j.relative(e,r).replaceAll(j.sep,"/")}}function xk(e){let t=e.trim();return t.length===0||t.startsWith(".")||t.startsWith("~")?!1:t.startsWith("@")?t.split("/").length===2:!t.includes("/")&&!t.includes("\\")}async function Ik(e){let t=`Local extension source does not exist: "${e.absolute_path}".`,n=e.input.trim();if(!xk(n))return new y(t,g.NOT_FOUND);let r=[];try{let a=process.env.PM_CLI_PACKAGE_ROOT,o=typeof a=="string"&&a.trim().length>0?j.resolve(a.trim()):"";is?.key!==o&&(is={key:o,aliases:await Gi()}),r=is.aliases}catch{}let i=[`Retry with pm install npm:${n} if the package is published to npm.`,`Or inspect bundled packages with pm package catalog --project --json before installing by alias. Known aliases (blank means none found): ${r.join(", ")}`];return new y(`${t} "${n}" did not match a local directory, bundled package alias, or bundled package name; if you meant an npm package, install it as "npm:${n}".`,g.NOT_FOUND,{code:"local_source_not_found_bare_name",required:`Use "npm:${n}" for npm registry packages, a bundled catalog alias, or an existing local directory path.`,why:"Bare names resolve as local paths only after bundled aliases, so unmatched names need an explicit npm: source.",examples:[`pm install npm:${n}`,"pm package catalog --project --json"],nextSteps:i,recovery:{attempted_command:`pm install ${n}`,normalized_args:["install",n],next_best_command:`pm install npm:${n}`}})}async function Dp(e){if(e.kind==="local"){let r;try{r=await K.stat(e.absolute_path)}catch{throw await Ik(e)}if(r.isFile()&&Op(e.absolute_path)){let a=await os(e.absolute_path);return{source:e,directory:a.directory,source_root:j.dirname(a.directory),resolved_subpath:j.relative(j.dirname(a.directory),a.directory).replaceAll(j.sep,"/"),npm_package:a.package,npm_version:a.version,cleanup:a.cleanup}}if(!r.isDirectory())throw new y(`Local extension source must be a directory or npm .tgz/.tar.gz archive: "${e.absolute_path}".`,g.USAGE);let i=await Ji(e.absolute_path,e.input);return{source:e,directory:i,source_root:e.absolute_path}}if(e.kind==="npm"){let r=await fk(e);return{source:e,directory:r.directory,source_root:j.dirname(r.directory),cleanup:r.cleanup,resolved_subpath:j.relative(j.dirname(r.directory),r.directory).replaceAll(j.sep,"/"),npm_package:r.package,npm_version:r.version}}let t=await K.mkdtemp(j.join(ss.tmpdir(),"pm-extension-source-")),n=["clone","--depth","1"];e.ref&&n.push("--branch",e.ref),n.push(e.repository,t);try{await qi(n);let r=await qi(["-C",t,"rev-parse","HEAD"]),i=await Ek(t,e);return{source:e,directory:i.directory,source_root:t,resolved_subpath:i.resolved_subpath,commit:r,cleanup:async()=>{await K.rm(t,{recursive:!0,force:!0})}}}catch(r){throw await K.rm(t,{recursive:!0,force:!0}),r}}async function Ki(e,t){if(!await O(e)||!await O(t))return!1;let[n,r]=await Promise.all([K.realpath(e),K.realpath(t)]);return n===r}import yr from"node:fs/promises";import wr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ceca3e62-35a7-51eb-b478-5309ba430cc8")}catch{}})();var cs=1,Kt="2026.6.24",Ak=">=22.18.0",Rk={fs_read:!1,fs_write:!1,network:!1,env_read:!1,env_write:!1,process_spawn:!1},Pp=new Set([...Al.map(e=>e.split("-")[0].toLowerCase()),...Object.keys(cl).map(e=>e.toLowerCase()),"scaffold"]),Ck="^6.0.0",Tk="^22.0.0",Mp=["type StarterHarness = Awaited<ReturnType<typeof createExtensionTestHarness>>;","","async function deactivateIfNeeded(ext: StarterHarness, deactivated: boolean): Promise<void> {"," if (!deactivated) {"," try {"," await ext.deactivate();"," } catch {"," // Preserve the original assertion error; cleanup is best effort."," }"," }","}",""],tt=[" } finally {"," await deactivateIfNeeded(ext, deactivated);"," }"];function Np(e,t){return e.map(n=>n===""?n:`${t}${n}`)}function jp(e){let t=e.includeMigrationReplacementHint===!0?[" // as your migration grows."]:[];return[" // assertItemType/Field/Migration throw unless the registration is present, so"," // reaching each next line already proves the wiring; assert on the returned"," // definitions to demonstrate inspecting registered metadata.",` const itemType = ext.assertItemType({ name: ${JSON.stringify(e.itemTypeName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,` assert.equal(itemType.itemType.folder, ${JSON.stringify(e.itemTypeFolder)});`,` const itemField = ext.assertItemField({ name: ${JSON.stringify(e.fieldName)}, extensionName: ${JSON.stringify(e.extensionName)} });`,' assert.equal(itemField.field.type, "string");',` ext.assertMigration({ name: ${JSON.stringify(e.migrationId)}, extensionName: ${JSON.stringify(e.extensionName)}, mandatory: false });`,""," // runMigration invokes the migration through pm's real runner with a synthetic"," // context and returns its result.",...t,` const migrated = await ext.runMigration({ migration: ${JSON.stringify(e.migrationId)} });`,` assert.deepEqual(migrated, { migrated: true, id: ${JSON.stringify(e.migrationId)} });`]}function Fp(e){return[" // assertProfile throws unless the profile is registered, so reaching the next"," // line already proves the wiring; assert on the returned definition to inspect"," // the bundled archetype dimensions.",` const { profile } = ext.assertProfile({ name: ${JSON.stringify(e)}, extensionName: ${JSON.stringify(e)} });`,` assert.equal(profile.title, ${JSON.stringify(`${e} archetype`)});`," assert.equal(profile.types.length, 1);"," assert.equal(profile.workflows.length, 1);"]}var $k={compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",strict:!0,esModuleInterop:!0,skipLibCheck:!0,noEmit:!0,allowImportingTsExtensions:!0,resolveJsonModule:!0,types:["node"]},include:["**/*.ts"]},Lp=["commands","hooks","search","importers","schema","profile","renderers","parser","preflight","services"],Up={commands:["commands"],hooks:["commands","hooks"],search:["commands","search"],importers:["commands","schema","importers"],schema:["commands","schema"],profile:["commands","schema"],renderers:["commands","renderers"],parser:["commands","parser","schema"],preflight:["commands","preflight"],services:["commands","services"]},Ok={commands:'["commands"]',hooks:'["commands", "hooks"]',search:'["commands", "search"]',importers:'["commands", "schema", "importers"]',schema:'["commands", "schema"]',profile:'["commands", "schema"]',renderers:'["commands", "renderers"]',parser:'["commands", "parser", "schema"]',preflight:'["commands", "preflight"]',services:'["commands", "services"]'},Dk={commands:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration plus a `deactivate` teardown stub.",hooks:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `after_command` lifecycle hook, and a `deactivate` teardown stub.",search:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a search provider, a vector-store adapter, and a `deactivate` teardown stub.",importers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, importer/exporter command registrations, and a `deactivate` teardown stub.",schema:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a custom item type, a custom item field, a schema migration, and a `deactivate` teardown stub.",profile:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a project profile (item types, statuses, fields, a workflow, config, a template, and package recommendations) registered via `api.registerProfile`, and a `deactivate` teardown stub.",renderers:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a `toon` output renderer override, and a `deactivate` teardown stub.",parser:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a parser override that rewrites the command's parsed options, and a `deactivate` teardown stub.",preflight:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, a preflight override over pm's pre-run gate decision, and a `deactivate` teardown stub.",services:"- `index.ts`: the TypeScript manifest entry \u2014 starter command registration, an `output_format` service override, and a `deactivate` teardown stub."},Pk={commands:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, and teardown via the SDK testing helpers.",hooks:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, the after_command hook, and teardown via the SDK testing helpers.",search:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, search provider/vector adapter invocation, and teardown via the SDK testing helpers.",importers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, importer/exporter invocation, and teardown via the SDK testing helpers.",schema:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, item type/field/migration registration, migration invocation, and teardown via the SDK testing helpers.",profile:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, project-profile registration (asserting the bundled archetype dimensions), and teardown via the SDK testing helpers.",renderers:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, renderer override registration and invocation (including format pass-through), and teardown via the SDK testing helpers.",parser:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, parser override registration and the option rewrite it produces, and teardown via the SDK testing helpers.",preflight:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, preflight override registration and the gate decision it returns, and teardown via the SDK testing helpers.",services:"- `index.test.ts`: sample `node:test` suite covering activation, command invocation, service override registration and invocation (including command pass-through), and teardown via the SDK testing helpers."},Hp="- `tsconfig.json`: strict type-check-only TypeScript config (`noEmit`) for the `.ts` source the loader runs directly.",Nk={commands:[],hooks:["","## Lifecycle Hook","`index.ts` registers an `after_command` hook via `api.hooks.afterCommand`.","pm fires it once a command finishes, passing the command outcome and the","items it mutated (`context.affected`). React there to keep external context","in sync - sync records, emit telemetry, or refresh derived state. The","`hooks` capability in `manifest.json` is what grants the hook registration;","remove it (and the hook) if your package only needs commands."],search:["","## Search Provider","`index.ts` registers a deterministic in-memory search provider and","vector-store adapter through `api.registerSearchProvider` and","`api.registerVectorStoreAdapter`. Replace the sample scoring,","embedding, and storage behavior with your project-specific retrieval","logic. The `search` capability in `manifest.json` grants both","registrations."],importers:["","## Importer and Exporter","`index.ts` registers paired project-context import/export commands through","`api.registerImporter` and `api.registerExporter`. Replace the starter","payloads with your domain adapter: GitHub issues, CSV rows, documents,","tickets, or another project-management source of truth. The `importers`","capability grants both registrations, and `schema` grants the example","command flag metadata."],schema:["","## Custom Schema","`index.ts` models a project domain by registering a custom item type, a","custom item field, and a schema migration through `api.registerItemTypes`,","`api.registerItemFields`, and `api.registerMigration`. This is how a package","turns pm into a domain-specific tracker \u2014 `project management = context","management`. Replace the sample type/field/migration with your own domain","model; the `schema` capability in `manifest.json` grants all three","registrations. Once installed, the custom type is usable everywhere, e.g.",'`pm create <type> "<title>"` and `pm list --type <type>`.'],profile:["","## Project Profile","`index.ts` registers a complete project-profile archetype through","`api.registerProfile`. A profile is the broadest customization primitive pm","has \u2014 one declarative bundle of item types, custom statuses, fields, a per-type","workflow, config knobs, create templates, and package recommendations. Once the","package is installed the profile resolves by name through `pm profile list`,","`pm profile show <name>`, and `pm profile apply <name>`, which stages every","dimension idempotently \u2014 exactly like a core archetype (agile/ops/research),","with no consumer code required. Replace the sample archetype with your own","domain; the `schema` capability in `manifest.json` grants the registration (a","profile is a schema+config bundle, so it needs no separate capability)."],renderers:["","## Output Renderer","`index.ts` registers a `toon` output renderer override through","`api.registerRenderer`. Renderer overrides run for every command's output in","that format, so this starter scopes itself to THIS package's own command and","returns `null` (pass-through to pm's default renderer) for everything else.","Return a string to take over rendering. Replace the sample serialization with","your own; the `renderers` capability in `manifest.json` grants the","registration."],parser:["","## Parser Override","`index.ts` registers a parser override for the starter command through","`api.registerParser`. pm runs it on the command's parsed options BEFORE the","handler, merging the delta you return. This starter rewrites a deprecated","`--shout` alias to the canonical `--upper` flag; replace it with your","command's real normalization. The `parser` capability in `manifest.json`","grants the registration."],preflight:["","## Preflight Override","`index.ts` registers a preflight override through `api.registerPreflight`. pm","calls it only for its declared command ownership to compute the migration/format","gate decision. Overlapping or legacy global ownership is diagnosed. Return only","the decision keys you want to","change; this starter echoes the current decision unchanged (a safe no-op) so","installing the package does not alter gate behavior. The `preflight`","capability in `manifest.json` grants the registration."],services:["","## Service Override","`index.ts` overrides the built-in `output_format` service through","`api.registerService`. The service renders a command's structured result;","returning the payload unchanged passes through to pm's default formatting.","This starter scopes itself to THIS package's own command and passes every","other command through, so it never disrupts unrelated output. The `services`","capability in `manifest.json` grants the registration."]},Lk={package:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","package's `activate` registers. pm imports and activates the package lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands (`pm list`, `pm search`, ...) never pay to load it. Keep this list in","sync with the registrations in `index.ts`: add an entry when you register a new","command, importer, or exporter, and remove one you drop. An omitted or stale","entry means the matching command will not dispatch from the CLI. Globally-scoped","surfaces (hooks, parser/preflight/renderer overrides, and search providers for","built-in search commands) still activate regardless of this list."],extension:["","## Lazy Activation","`manifest.json` declares `activation.commands`: the exact command paths this","extension's `activate` registers. pm imports and activates the extension lazily \u2014","only when an invoked command path matches one of these entries \u2014 so unrelated","commands never pay to load it. Keep this list in sync with the registrations in","`index.ts`: an omitted or stale entry means the matching command will not dispatch","from the CLI. Globally-scoped surfaces (hooks, parser/preflight/renderer overrides,","and search providers for built-in search commands) still activate regardless."]},Mk={package:["","## Activation","This package contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the package","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`. If you","drop the schema registrations and keep only command/hook/search/importer surfaces,","add `activation.commands` back so pm can load the package lazily."],extension:["","## Activation","This extension contributes a GLOBAL custom item type and field, so `manifest.json`","intentionally declares no `activation.commands`. pm activates the extension","conservatively \u2014 for every command \u2014 so the custom type is present wherever it is","used: `pm create <type>`, `pm list --type <type>`, `pm validate`, and so on.","Declaring narrow `activation.commands` here would gate activation to only those","commands and silently leave the custom type unregistered for `pm create`."]},jk={package:["","## Activation","This package contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands \u2014 commands the package does not own \u2014 so `manifest.json` intentionally","declares no `activation.commands`. pm activates the package conservatively (for","every command, granted by the `schema` capability) so the profile is present","whenever `pm profile` runs. Declaring narrow `activation.commands` here would","gate activation to only the listed commands and silently leave the profile","unregistered for `pm profile`."],extension:["","## Activation","This extension contributes a project profile resolved by the built-in","`pm profile list`, `pm profile show <name>`, and `pm profile apply <name>`","commands, so `manifest.json` intentionally declares no `activation.commands`. pm","activates the extension conservatively (for every command, granted by the","`schema` capability) so the profile is present whenever `pm profile` runs.","Declaring narrow `activation.commands` here would silently leave the profile","unregistered for `pm profile`."]};function zp(e,t){return e==="schema"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the custom item type activates for every command).`:e==="profile"?`- \`manifest.json\`: ${t} metadata and capabilities (no \`activation.commands\` \u2014 the contributed profile resolves through \`pm profile\` for every command).`:`- \`manifest.json\`: ${t} metadata, capabilities, and \`activation.commands\` (the command paths that lazily activate this ${t}).`}function Wp(e,t){return e==="schema"?Mk[t]:e==="profile"?jk[t]:Lk[t]}function Fk(e){let t=e.replace(/-/g," ").trim().split(/\s+/).filter(o=>o.length>0);if(t.length===0)return"starter ping";let n=t[0].toLowerCase(),r=0;for(;t[r]?.toLowerCase()==="starter";)r+=1;let i=t[r]?.toLowerCase(),a=r>0&&(r===t.length||i!==void 0&&Pp.has(i));return`${(Pp.has(n)||a?["starter",...t]:t).join(" ")} ping`}function Gp(e){let t=e,n=`${e}s`,r=e.replace(/-/g,""),i=r===t?[]:[r],a=`${e.replace(/-/g,"_")}_owner`,o="reviewing";return[` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," // Item types the profile upserts into the project schema when applied."," types: ["," {",` name: ${JSON.stringify(t)},`,` folder: ${JSON.stringify(n)},`,` aliases: ${JSON.stringify(i)},`,` description: ${JSON.stringify(`A ${e} work item that flows to done.`)},`," },"," ],"," // Custom statuses upserted into the project status set."," statuses: ["," {",` id: ${JSON.stringify(o)},`,' roles: ["active"],',' aliases: ["in-review"],',' description: "Work is implementation-complete and awaiting review.",'," },"," ],"," // Custom item-metadata fields the archetype tracks."," fields: ["," {",` key: ${JSON.stringify(a)},`,' type: "string",',' commands: ["create", "update", "list"],',' description: "Stakeholder accountable for the item.",'," },"," ],"," // Per-type workflow transition allow-list staged into settings."," workflows: ["," {",` type: ${JSON.stringify(t)},`," allowed_transitions: [",' ["open", "in_progress"],',` ["in_progress", ${JSON.stringify(o)}],`,` [${JSON.stringify(o)}, "in_progress"],`,` [${JSON.stringify(o)}, "closed"],`,' ["in_progress", "blocked"],',' ["blocked", "in_progress"],'," ],"," },"," ],"," // Nested-settings knobs staged when the profile is applied."," config: [",' { key: "search_provider", value: "bm25", summary: "Offline BM25 lexical search needs no embedding service." },',' { key: "search_max_results", value: "20", summary: "Result cap tuned for quick triage." },'," ],"," // Create templates staged into <pmRoot>/templates."," templates: ["," {",` name: ${JSON.stringify(e)},`," options: {",` type: ${JSON.stringify(t)},`,' priority: "2",',` tags: ${JSON.stringify(e)},`,' acceptanceCriteria: "Item delivers the stated outcome with tests and docs updated.",',' body: "## Context\\n\\n## Acceptance\\n- [ ] \\n",'," },"," },"," ],"," // Advisory package recommendations (never auto-installed)."," packages: [",' { spec: "templates", reason: "Reusable create templates for recurring item shapes." },'," ],"]}function Uk(e,t,n){let r=`${e}-search`,i=`${e}-vector`,a=`${e.replace(/-/g," ")} items`,o=[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",' message: "Starter extension scaffold is active.",'," }),"," });"];if(n==="commands")return o;if(n==="search")return[...o,""," // Search providers let packages customize how pm ranks and retrieves"," // project context. This starter is deterministic and dependency-free:"," // replace the scoring with your domain retrieval, embedding, or rerank"," // logic as the package grows."," api.registerSearchProvider({",` name: ${JSON.stringify(r)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],"," });",""," // Vector-store adapters let packages own semantic index storage. This"," // starter returns a stable in-memory hit so generated tests can exercise"," // the adapter without external services."," api.registerVectorStoreAdapter({",` name: ${JSON.stringify(i)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),"," });"];if(n==="schema"){let s=e,c=`${e}s`,l=e.replace(/-/g,""),d=l===s?[]:[l],u=`${e.replace(/-/g,"_")}_note`,m=`${e}-0001-init`;return[...o,""," // Schema registrations let a package model its own project domain \u2014 the",' // heart of "project management = context management". Item types and fields'," // are GLOBAL contributions: built-in commands like `pm create <type>` and"," // `pm list --type <type>` must see them, so this package declares no"," // `activation.commands` and pm activates it conservatively for every command."," // The `schema` capability in manifest.json grants all three registrations."," api.registerItemFields(["," {",` name: ${JSON.stringify(u)},`,' type: "string",'," optional: true,"," },"," ]);",""," api.registerItemTypes(["," {",` name: ${JSON.stringify(s)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(c)},`,` aliases: ${JSON.stringify(d)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],"," },"," ]);",""," // Migrations let a package evolve stored items as its schema changes. pm"," // runs each migration ONCE through the preflight gate (not once per item),"," // passing a context that identifies the migration itself: `context.id` is"," // the migration id (not an item id), alongside `context.pm_root` \u2014 iterate"," // the corpus yourself from there. This starter is a deterministic no-op so"," // package tests can invoke it without touching the corpus; replace the body"," // with your real rewrite."," api.registerMigration({",` id: ${JSON.stringify(m)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),"," });"]}return n==="profile"?[...o,""," // A project profile is the broadest customization primitive pm has: one"," // declarative bundle of item types, custom statuses, fields, a per-type"," // workflow, config knobs, create templates, and package recommendations. Once"," // this package is installed the profile resolves by name through `pm profile"," // list`, `pm profile show`, and `pm profile apply`, which stages every dimension"," // idempotently like a core archetype. A profile registration is a schema+config"," // bundle, so the `schema` capability in manifest.json grants it."," api.registerProfile({",...Gp(e).map(s=>` ${s}`)," });"]:n==="importers"?[...o,""," // Importers/exporters are the bridge between pm's context graph and"," // another project-management system. Keep the starter deterministic so"," // package tests can run without touching the network or filesystem; replace"," // these payloads with your adapter's real mapping as the package grows."," api.registerImporter(",` ${JSON.stringify(a)},`," async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," );",""," api.registerExporter(",` ${JSON.stringify(a)},`," async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,"," }),"," {",` action: ${JSON.stringify(`${a} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," );"]:n==="renderers"?[...o,""," // Renderer overrides customize how pm serializes a command's structured",' // result for an output format ("toon" or "json"). Host-enforced ownership'," // prevents unrelated commands from reaching this callback."," // The `renderers` capability in manifest.json grants the registration.",' api.registerRenderer("toon", (context) => {',` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`,` }, { commands: [${JSON.stringify(t)}] });`]:n==="parser"?[" api.registerCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",'," flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,"," // Surfaces the normalized option so `--shout`/`--upper` is observable."," upper: context.options.upper === true,",' message: "Starter extension scaffold is active.",'," }),"," });",""," // Parser overrides preprocess a command's parsed options BEFORE its handler"," // runs, returning a delta \u2014 only the keys you set are merged over the parsed"," // input. This override is scoped to THIS package's own command. Here it"," // rewrites the deprecated `--shout` boolean alias to the canonical `--upper`"," // flag; replace it with your command's real normalization. The `parser`"," // capability in manifest.json grants the registration.",` api.registerParser(${JSON.stringify(t)}, (context) => {`," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };"," });"]:n==="preflight"?[...o,""," // Preflight overrides adjust pm's pre-run gate decision (extension"," // migrations + item-format checks) for the commands it owns. Disjoint"," // packages compose; overlapping or legacy global ownership is diagnosed."," // Return a delta of the keys you want to change"," // (enforce_item_format_gate, run_preflight_item_format_sync,"," // run_extension_migrations, enforce_mandatory_migration_gate); returning"," // context.decision unchanged is a safe no-op so installing the package does"," // not alter gate behavior \u2014 replace it with your policy, e.g."," // `{ run_extension_migrations: false }`. The `preflight` capability in"," // manifest.json grants the registration."," api.registerPreflight({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,"," });"]:n==="services"?[...o,""," // Service overrides replace a built-in pm service. The `output_format`"," // service renders a command's structured result; returning the payload"," // unchanged passes through to pm's default formatting. This override scopes"," // itself to THIS package's own command and passes every other command"," // through, so it never disrupts unrelated output. The `services` capability"," // in manifest.json grants the registration.",' api.registerService("output_format", (context) => {',` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`," });"]:[...o,""," // after_command hooks fire once pm finishes a command, receiving the items"," // it mutated. This is the natural place to react to every change - sync to"," // an external system, emit telemetry, or refresh derived context",' // ("project management = context management"). This starter is a documented'," // no-op on the success path; replace the body with your own reaction."," api.hooks.afterCommand((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status,"," // changed_fields). React here, e.g.:"," // for (const item of context.affected ?? []) { /* ...item.id... */ }"," });"]}function Hk(e,t,n){let r=n==="hooks",i=n==="search",a=n==="importers",o=n==="schema",s=n==="profile",c=n==="renderers",l=n==="parser",d=n==="preflight",u=n==="services",m=Ok[n],f=e,p=`${e}s`,h=`${e.replace(/-/g,"_")}_note`,_=`${e}-0001-init`,w=[" assertExtensionDeactivated,"," createExtensionTestHarness,"],v=r?[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertHook throws unless an after_command hook is registered, so"," // reaching the next line already proves the hook is wired."," ext.assertHook({",' kind: "after_command",',` extensionName: ${JSON.stringify(e)},`," });"," // runHook fires the hook through pm's real runner with a synthetic"," // context and returns the warnings it produced; a clean hook returns none."," // Replace the context/assertions as your hook grows."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...tt,"});",""]:[],S=i?ls(e,t,"search",m):[],k=a?ls(e,t,"importers",m):[],x=o?[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Np(jp({extensionName:e,itemTypeName:f,itemTypeFolder:p,fieldName:h,migrationId:_,includeMigrationReplacementHint:!0})," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...tt,"});",""]:[],D=s?[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {",...Np(Fp(e)," ")," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...tt,"});",""]:[],E=c?[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertRendererOverride throws unless a renderer is registered for the"," // format, so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override"," // customizes only THIS package's command output and returns a string the"," // host uses verbatim. Replace the assertions as it grows."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);",` assert.equal(rendered.rendered, ${JSON.stringify(`${e}: `)} + JSON.stringify({ ok: true }));`,""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...tt,"});",""]:[],b=l?[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertParserOverride throws unless a parser is registered for the"," // command, so reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and"," // returns the rewritten context. The starter rewrites the deprecated"," // `shout` alias to the canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to"," // prove `pm <command> --shout` surfaces the normalized `upper` flag in"," // the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...tt,"});",""]:[],N=d?[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertPreflightOverride throws unless a preflight override is"," // registered, so reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a"," // synthetic gate decision. The starter echoes the decision unchanged;"," // replace the values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...tt,"});",""]:[],I=u?[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertServiceOverride throws unless a service override is registered"," // for the service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner."," // The override customizes only THIS package's command output (handled),"," // passing every other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...tt,"});",""]:[];return['import assert from "node:assert/strict";','import { test } from "node:test";',"import {",...w,'} from "@unbrained/pm-cli/sdk/testing";',...i?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension from "./index.ts";',"",...Mp,`test(${JSON.stringify(`${e} registers its starter command`)}, async () => {`," // `capabilities` mirrors manifest.json so the in-memory activation grants"," // the capabilities the entrypoint relies on."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," let deactivated = false;"," try {"," // assertCommandContract is bound to the right activation registry and throws"," // if the command is not registered, so reaching here already proves the"," // wiring; assert on the returned definition to inspect metadata."," const registered = ext.assertCommandContract({",` name: ${JSON.stringify(t)},`,` extensionName: ${JSON.stringify(e)},`," });",' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command."," const invocation = await ext.runCommand({",` command: ${JSON.stringify(t)},`," });"," assert.equal(invocation.handled, true);"," // The handler result is typed `unknown`, so deep-equality on the whole"," // structured payload keeps the assertion type-safe without a cast."," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...l?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...tt,"});","",...v,...S,...k,...x,...D,...E,...b,...N,...I,`test(${JSON.stringify(`${e} tears down cleanly via deactivate`)}, async () => {`," // createExtensionTestHarness binds teardown to the same name/layer used for"," // activation, so this proves your `deactivate` hook runs without throwing."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${m},`," });"," const teardown = await ext.deactivate();"," // assertExtensionDeactivated throws unless exactly one extension tore down"," // with no failures, so reaching the next line already proves teardown ran."," assertExtensionDeactivated(teardown);"," assert.equal(teardown.deactivated, 1);","});",""].join(`
44
+ `)}function zk(e,t,n){if(n==="schema"||n==="profile")return[];if(n==="importers"){let r=`${e.replace(/-/g," ")} items`;return[t,`${r} import`,`${r} export`]}return[t]}var Wk={commands:"starter command",hooks:"starter command and after_command hook",search:"starter command, search provider, and vector-store adapter",importers:"starter command, importer, and exporter",schema:"starter command, custom item type, item field, and migration",profile:"starter command and project profile",renderers:"starter command and toon renderer override",parser:"starter command and parser override",preflight:"starter command and preflight override",services:"starter command and output_format service override"},Gk={commands:"`commands`",hooks:"`commands` and `hooks.afterCommand`",search:"`commands`, `searchProviders`, and `vectorStoreAdapters`",importers:"`commands`, `importers`, and `exporters`",schema:"`commands`, `itemTypes`, `itemFields`, and `migrations`",profile:"`commands` and `profiles`",renderers:"`commands` and `renderers`",parser:"`commands` and `parsers`",preflight:"`commands` and `preflights`",services:"`commands` and `services`"};function qk(e,t,n){let r=n==="parser";return["// The starter command, authored with the `defineCommand` builder so its literal","// name is preserved and the handler `context` is inferred. Exporting it lets you","// unit-test the definition in isolation, apart from the blueprint.","export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...r?[" flags: ["," {",' long: "--shout",',' value_type: "boolean",',' description: "Deprecated alias for --upper; the parser override rewrites it.",'," },"," {",' long: "--upper",',' value_type: "boolean",',' description: "Echo the canonical flag the parser override produces.",'," },"," ],"]:[]," run: async (context) => ({"," ok: true,",` source: ${JSON.stringify(e)},`," command: context.command,",...r?[" upper: context.options.upper === true,"]:[],' message: "Starter extension scaffold is active.",'," }),","});"]}function Bk(e,t,n){let r=[],i=[...qk(e,t,n)],a=[" commands: [pingCommand],"],o=`${e}-search`,s=`${e}-vector`,c=`${e.replace(/-/g," ")} items`,l=e,d=`${e}s`,u=e.replace(/-/g,""),m=u===l?[]:[u],f=`${e.replace(/-/g,"_")}_note`,p=`${e}-0001-init`;switch(n){case"commands":break;case"hooks":r.push("defineAfterCommandHook"),i.push("","// after_command hooks fire once pm finishes a command, receiving the items it","// mutated. React here - sync to an external system, emit telemetry, or refresh",'// derived context ("project management = context management"). This starter is a',"// documented no-op on the success path; replace the body with your own reaction.","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) {"," return;"," }"," // `context.affected` lists the items pm mutated (id, status, changed_fields):"," // for (const item of context.affected ?? []) { /* ...item.id... */ }","});"),a.push(" hooks: { afterCommand: [afterCommandHook] },");break;case"search":r.push("defineSearchProvider","defineVectorStoreAdapter"),i.push("","// Search providers let packages customize how pm ranks and retrieves project","// context. This starter is deterministic and dependency-free: replace the scoring","// with your domain retrieval, embedding, or rerank logic as the package grows.","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(o)},`," query: async (context) => {"," const needle = context.query.toLowerCase();"," const hits = context.documents"," .filter((document) => {",' const title = String(document.metadata.title ?? "").toLowerCase();'," return title.includes(needle);"," })"," .map((document) => ({"," id: document.metadata.id,"," score: 1,",' matched_fields: ["title"],'," }));"," return { hits };"," },"," embed: async (context) => [context.input.length],","});","","// Vector-store adapters let packages own semantic index storage. This starter","// returns a stable in-memory hit so generated tests can exercise the adapter","// without external services.","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(s)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),a.push(" searchProviders: [searchProvider],"," vectorStoreAdapters: [vectorStoreAdapter],");break;case"importers":r.push("defineExporter","defineImporter"),i.push("","// Importers/exporters are the bridge between pm's context graph and another","// project-management system. Keep the starter deterministic so package tests can","// run without touching the network or filesystem; replace these payloads with","// your adapter's real mapping as the package grows.","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),a.push(" importers: ["," {",` name: ${JSON.stringify(c)},`," importer,"," options: {",` action: ${JSON.stringify(`${c} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," },"," },"," ],"," exporters: ["," {",` name: ${JSON.stringify(c)},`," exporter,"," options: {",` action: ${JSON.stringify(`${c} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," },"," },"," ],");break;case"schema":r.push("defineItemField","defineItemType","defineMigration"),i.push("","// Schema registrations let a package model its own project domain - the heart of",'// "project management = context management". Item types and fields are GLOBAL',"// contributions, so this package declares no `activation.commands` and pm","// activates it conservatively for every command.","export const noteField = defineItemField({",` name: ${JSON.stringify(f)},`,' type: "string",'," optional: true,","});","","export const itemType = defineItemType({",` name: ${JSON.stringify(l)},`," // Replace with your domain's canonical plural folder name.",` folder: ${JSON.stringify(d)},`,` aliases: ${JSON.stringify(m)},`," // Add field names here to force them at `pm create` time."," required_create_fields: [],","});","","// Migrations let a package evolve stored items as its schema changes. pm runs each","// migration ONCE through the preflight gate (not once per item), passing a context","// that identifies the migration itself: `context.id` is the migration id (not an","// item id), alongside `context.pm_root`. This starter is a deterministic no-op so","// package tests can invoke it without touching the corpus; replace the body with","// your real rewrite.","export const initMigration = defineMigration({",` id: ${JSON.stringify(p)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),a.push(" itemTypes: [itemType],"," itemFields: [noteField],"," migrations: [initMigration],");break;case"profile":r.push("defineProjectProfile"),i.push("","// A project profile is the broadest customization primitive pm has: one","// declarative bundle of item types, custom statuses, fields, a per-type workflow,","// config knobs, create templates, and package recommendations. Once installed it","// resolves by name through `pm profile list/show/apply`, which stages every","// dimension idempotently like a core archetype. A profile registration is a","// schema+config bundle, so the `schema` capability grants it.","export const starterProfile = defineProjectProfile({",...Gp(e),"});"),a.push(" profiles: [starterProfile],");break;case"renderers":r.push("defineRendererOverride"),i.push("","// Host-enforced command ownership prevents unrelated output from reaching","// this renderer callback; return a string to take over serialization.","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => {",` return ${JSON.stringify(`${e}: `)} + JSON.stringify(context.result);`," },","});"),a.push(" renderers: { toon: toonRenderer },");break;case"parser":r.push("defineParserOverride"),i.push("","// Parser overrides preprocess a command's parsed options BEFORE its handler runs,","// returning a delta - only the keys you set are merged over the parsed input. This","// override is scoped to THIS package's own command; here it rewrites the deprecated","// `--shout` boolean alias to the canonical `--upper` flag.","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) {"," options.upper = true;"," }"," delete options.shout;"," return { options };","});"),a.push(` parsers: { ${JSON.stringify(t)}: pingParser },`);break;case"preflight":r.push("definePreflightOverride"),i.push("","// Preflight overrides adjust pm's pre-run gate decision (extension migrations +","// item-format checks) for the commands it owns. Scoped ownership composes with","// other packages; overlapping or legacy global ownership is diagnosed.","// Return a delta of the keys you want to change (enforce_item_format_gate,","// run_preflight_item_format_sync, run_extension_migrations,","// enforce_mandatory_migration_gate); returning context.decision unchanged is a","// safe no-op - replace it with your policy, e.g. { run_extension_migrations: false }.","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),a.push(" preflights: [preflightOverride],");break;case"services":r.push("defineServiceOverride"),i.push("","// Service overrides replace a built-in pm service. The `output_format` service","// renders a command's structured result; returning the payload unchanged passes","// through to pm's default formatting. This override scopes itself to THIS","// package's own command and passes every other command through.","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) {`," return { handled: false };"," }",` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),a.push(" services: { output_format: outputService },");break}return{builderImports:r,definitions:i,blueprintFields:a}}function Vk(e,t,n){let r=Bk(e,t,n);return[`import { ${["composeExtension","defineCommand","defineExtensionBlueprint",...r.builderImports].sort((i,a)=>i.localeCompare(a)).join(", ")} } from "@unbrained/pm-cli/sdk";`,"",...r.definitions,"","// Declarative authoring: describe WHAT the package registers as a blueprint and","// let `composeExtension` generate the `activate` that wires every surface in order,","// instead of hand-writing each `api.register*` call. `defineExtensionBlueprint`","// contract-checks the blueprint where it is authored. Keep `manifest.json`'s","// `capabilities` equal to the set this blueprint derives.","export const blueprint = defineExtensionBlueprint({",...r.blueprintFields," // `deactivate` is the teardown counterpart to the generated `activate`: pm runs"," // it on host shutdown/reload to release anything the package opened (timers,"," // connections, caches). This starter holds none, so it stays a no-op."," deactivate: () => {},","});","","// `composeExtension(blueprint)` is the package's default export \u2014 the runtime","// `ExtensionModule` pm loads. Guard the blueprint with `assertExtensionPreflight`","// in index.test.ts before publishing.","export default composeExtension(blueprint);",""].join(`
45
+ `)}function ls(e,t,n,r){if(n==="commands")return[];let i=`${e}-search`,a=`${e}-vector`,o=`${e.replace(/-/g," ")} items`,s=e,c=`${e}s`,l=`${e.replace(/-/g,"_")}_note`,d=`${e}-0001-init`,u=[" const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${r},`," });"],m=f=>[...u," let deactivated = false;"," try {",...f.map(p=>p===""?p:` ${p}`)," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...tt];switch(n){case"hooks":return[`test(${JSON.stringify(`${e} reacts to commands via its after_command hook`)}, async () => {`,...m([" // assertHook throws unless an after_command hook is registered, so reaching the"," // next line already proves the hook is wired.",` ext.assertHook({ kind: "after_command", extensionName: ${JSON.stringify(e)} });`," // runHook fires the hook through pm's real runner with a synthetic context and"," // returns the warnings it produced; a clean hook returns none."," const warnings = await ext.runHook({",' kind: "after_command",'," context: {",` command: ${JSON.stringify(t)},`," args: [],",' pm_root: "",'," ok: true,"," affected: [],"," },"," });"," assert.deepEqual(warnings, []);"]),"});",""];case"search":return[`test(${JSON.stringify(`${e} registers and invokes search primitives`)}, async () => {`,...m([` ext.assertSearchProvider({ name: ${JSON.stringify(i)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertVectorStoreAdapter({ name: ${JSON.stringify(a)}, extensionName: ${JSON.stringify(e)} });`,""," // The starter provider reads only document title/id, so `settings` is a minimal"," // typed stub and `documents` carry just the fields it inspects."," const settings = {"," testing: {"," record_results_to_items: false,"," allow_untrusted_linked_tests: false,"," },"," } as PmSettings;"," const query = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "query",'," context: {",' query: "sync",',' mode: "semantic",',' tokens: ["sync"],'," options: {},"," settings,"," documents: [",' { metadata: { id: "pm-1", title: "Sync external context" }, body: "" },',' { metadata: { id: "pm-2", title: "Unrelated task" }, body: "" },'," ] as ItemDocument[],"," },"," });",' assert.deepEqual(query, { hits: [{ id: "pm-1", score: 1, matched_fields: ["title"] }] });',""," const embedding = await ext.runSearchProvider({",` provider: ${JSON.stringify(i)},`,' operation: "embed",',' context: { input: "abc", settings, model: "starter-model" },'," });"," assert.deepEqual(embedding, [3]);",""," const vectorHits = await ext.runVectorStoreAdapter({",` adapter: ${JSON.stringify(a)},`,' operation: "query",'," context: { vector: [0.1, 0.2], limit: 2, settings },"," });",' assert.deepEqual(vectorHits, [{ id: "starter-vector-hit", score: 2 }]);']),"});",""];case"importers":return[`test(${JSON.stringify(`${e} registers and invokes import/export primitives`)}, async () => {`,...m([` ext.assertImporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,` ext.assertExporter({ name: ${JSON.stringify(o)}, extensionName: ${JSON.stringify(e)} });`,""," const imported = await ext.runImporter({",` importer: ${JSON.stringify(o)},`,' options: { source: "tickets" },',' args: ["batch-1"],'," });"," assert.equal(imported.handled, true);",' assert.deepEqual(imported.result, { imported: 1, source: "tickets", args: ["batch-1"] });',""," const exported = await ext.runExporter({",` exporter: ${JSON.stringify(o)},`,' options: { destination: "archive" },',' args: ["done"],'," });"," assert.equal(exported.handled, true);",' assert.deepEqual(exported.result, { exported: true, destination: "archive", args: ["done"] });']),"});",""];case"schema":return[`test(${JSON.stringify(`${e} registers and runs its custom schema`)}, async () => {`,...m(jp({extensionName:e,itemTypeName:s,itemTypeFolder:c,fieldName:l,migrationId:d})),"});",""];case"profile":return[`test(${JSON.stringify(`${e} registers its project profile`)}, async () => {`,...m(Fp(e)),"});",""];case"renderers":return[`test(${JSON.stringify(`${e} registers and invokes its renderer override`)}, async () => {`,...m([" // assertRendererOverride throws unless a renderer is registered for the format,"," // so reaching the next line already proves the wiring.",` const override = ext.assertRendererOverride({ name: "toon", extensionName: ${JSON.stringify(e)} });`,' assert.equal(override.format, "toon");',""," // runRendererOverride renders through pm's real runner. The override customizes"," // only THIS package's command output and returns a string the host uses verbatim."," const rendered = await ext.runRendererOverride({",' format: "toon",',` command: ${JSON.stringify(t)},`," result: { ok: true },"," });"," assert.equal(rendered.overridden, true);"," assert.equal(rendered.rendered, JSON.stringify({ ok: true }));",""," // Output for any other command passes through to pm's default renderer."," const passthrough = await ext.runRendererOverride({",' format: "toon",',' command: "list",'," result: { ok: true },"," });"," assert.equal(passthrough.overridden, false);"]),"});",""];case"parser":return[`test(${JSON.stringify(`${e} rewrites command options via its parser override`)}, async () => {`,...m([" // assertParserOverride throws unless a parser is registered for the command, so"," // reaching the next line already proves the wiring.",` ext.assertParserOverride({ name: ${JSON.stringify(t)}, extensionName: ${JSON.stringify(e)} });`,""," // runParserOverride runs the override through pm's real parser runner and returns"," // the rewritten context. The starter rewrites the deprecated `shout` alias to the"," // canonical `upper` flag."," const result = await ext.runParserOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: { shout: true },"," global: {},",' pm_root: "",'," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.context.options, { upper: true });",""," // End to end: feed the rewritten options into the command handler to prove"," // `pm <command> --shout` surfaces the normalized `upper` flag in the result.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)}, options: result.context.options });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`," upper: true,",' message: "Starter extension scaffold is active.",'," });"]),"});",""];case"preflight":return[`test(${JSON.stringify(`${e} returns a preflight gate decision via its override`)}, async () => {`,...m([" // assertPreflightOverride throws unless a preflight override is registered, so"," // reaching the next line already proves the wiring.",` ext.assertPreflightOverride({ extensionName: ${JSON.stringify(e)} });`,""," // runPreflightOverride runs the override through pm's real runner with a synthetic"," // gate decision. The starter echoes the decision unchanged; replace the"," // values/assertions with your real policy."," const decision = {"," enforce_item_format_gate: true,"," run_preflight_item_format_sync: false,"," run_extension_migrations: true,"," enforce_mandatory_migration_gate: false,"," };"," const result = await ext.runPreflightOverride({",` command: ${JSON.stringify(t)},`," args: [],"," options: {},"," global: {},",' pm_root: "",'," decision,"," });"," assert.equal(result.overridden, true);"," assert.deepEqual(result.decision, decision);"]),"});",""];case"services":return[`test(${JSON.stringify(`${e} customizes command output via its service override`)}, async () => {`,...m([" // assertServiceOverride throws unless a service override is registered for the"," // service, so reaching the next line proves the wiring.",` ext.assertServiceOverride({ name: "output_format", extensionName: ${JSON.stringify(e)} });`,""," // runServiceOverride runs the override through pm's real service runner. The"," // override customizes only THIS package's command output (handled), passing every"," // other command through (not handled)."," const handled = await ext.runServiceOverride({",' service: "output_format",',` command: ${JSON.stringify(t)},`," payload: { ok: true },"," });"," assert.equal(handled.handled, true);",` assert.deepEqual(handled.result, { rendered_by: ${JSON.stringify(e)}, payload: { ok: true } });`,""," // Output for any other command passes through to pm's default formatter."," const passthrough = await ext.runServiceOverride({",' service: "output_format",',' command: "list",'," payload: { ok: true },"," });"," assert.equal(passthrough.handled, false);"]),"});",""]}}function Jk(e,t,n){let r=n==="parser",i=JSON.stringify([...Up[n]].sort());return['import assert from "node:assert/strict";','import { test } from "node:test";','import { assertExtensionDeactivated, assertExtensionManifestMatchesBlueprint, assertExtensionPreflight, createExtensionTestHarness } from "@unbrained/pm-cli/sdk/testing";',...n==="search"?['import type { ItemDocument, PmSettings } from "@unbrained/pm-cli/sdk";']:[],'import extension, { blueprint } from "./index.ts";','import manifest from "./manifest.json" with { type: "json" };',"",...Mp,`test(${JSON.stringify(`${e} passes author-time preflight`)}, () => {`," // assertExtensionPreflight is the author-time capstone: it lints the blueprint,"," // synthesizes the least-privilege manifest from `identity`, and checks the version"," // bounds against `target` in one call, throwing on any blocking finding. It returns"," // the full report so you can inspect the derived data."," const report = assertExtensionPreflight(blueprint, {"," identity: {",` name: ${JSON.stringify(e)},`,' version: "0.1.0",',' entry: "./index.ts",'," priority: 0,",` pm_min_version: ${JSON.stringify(Kt)},`," },",` target: { pmVersion: ${JSON.stringify(Kt)} },`," });"," // Fail the starter suite whenever the checked-in manifest drifts from the"," // capabilities derived from the blueprint."," assertExtensionManifestMatchesBlueprint(manifest, blueprint);"," // The capability set is DERIVED from the blueprint, never hand-synced. Keep"," // manifest.json's `capabilities` equal to this list (set match, sorted).",` assert.deepEqual(report.capabilities, ${i});`,` assert.deepEqual(report.manifest?.capabilities, ${i});`,"});","",`test(${JSON.stringify(`${e} registers and runs its starter command`)}, async () => {`," // createExtensionTestHarness activates the composed module once and binds the"," // assert*/run*/deactivate helpers to the right activation sub-registry, so you"," // never thread activation.registrations vs activation.commands by hand."," // `capabilities` mirrors manifest.json so the in-memory activation grants what the"," // blueprint needs."," const ext = await createExtensionTestHarness(extension, {",` name: ${JSON.stringify(e)},`,` capabilities: ${i},`," });"," let deactivated = false;"," try {"," // assertCommandContract throws unless the command is registered, so reaching"," // the next line already proves the wiring; assert on the returned definition"," // to demonstrate inspecting registered metadata.",` const registered = ext.assertCommandContract({ name: ${JSON.stringify(t)} });`,' assert.equal(typeof registered.command.description, "string");',""," // runCommand invokes the handler through pm's real dispatch engine, so this"," // asserts behavior - not just that the command is wired. Replace these"," // assertions as you flesh out your command.",` const invocation = await ext.runCommand({ command: ${JSON.stringify(t)} });`," assert.equal(invocation.handled, true);"," assert.deepEqual(invocation.result, {"," ok: true,",` source: ${JSON.stringify(e)},`,` command: ${JSON.stringify(t)},`,...r?[" upper: false,"]:[],' message: "Starter extension scaffold is active.",'," });"," // deactivate runs pm's real teardown engine over the module; exactly one"," // extension tears down with no failures."," const teardown = await ext.deactivate();"," assertExtensionDeactivated(teardown);"," deactivated = true;",...tt,"});","",...ls(e,t,n,i)].join(`
46
+ `)}function Kk(e,t,n){let r=zp(n,"package"),i=Wp(n,"package");return[`# ${e}`,"","Generated by `pm package init --declarative`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",r,`- \`index.ts\`: the TypeScript manifest entry \u2014 a \`defineExtensionBlueprint\` blueprint (${Wk[n]}) composed into the runtime module by \`composeExtension\`, plus a \`deactivate\` teardown stub.`,"- `index.test.ts`: sample `node:test` suite covering author-time preflight (`assertExtensionPreflight`) and runtime surface invocation/teardown via `createExtensionTestHarness`.",Hp,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Declarative Authoring","`index.ts` uses the SDK's declarative authoring loop instead of an imperative","`activate` body. You describe WHAT the package registers as an","`ExtensionBlueprint` and `composeExtension` generates the `activate` that wires","every surface in order:","- The `define*` builders author each surface with literal-type preservation and"," contextual handler inference (`defineCommand`, `defineSearchProvider`,"," `defineItemType`, `defineParserOverride`, ...).","- `defineExtensionBlueprint({ ... })` collects the definitions into the blueprint;",` this starter populates ${Gk[n]}. Add more`," fields as the package grows.","- `composeExtension(blueprint)` is the default export \u2014 the runtime module pm"," loads. Its generated `activate` requires exactly the capabilities the blueprint"," derives, so `manifest.json`'s `capabilities` never drift.","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`index.test.ts` exercises both authoring capstones: `assertExtensionPreflight`","(the author-time lint + manifest synthesis + version-compatibility check over the","exported `blueprint`) and `createExtensionTestHarness` (the runtime fixture whose","`assert*`/`run*`/`deactivate` methods bind to the right activation sub-registry).","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.",...i,"","## Compatibility Bounds","`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${cs}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Kt}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
47
+ `)}function Yk(e){let t=e,n=e.replace(/-/g,"");return{searchProviderName:`${e}-search`,vectorAdapterName:`${e}-vector`,adapterName:`${e.replace(/-/g," ")} items`,itemTypeName:t,itemTypeFolder:`${e}s`,itemTypeAliases:n===t?[]:[n],fieldName:`${e.replace(/-/g,"_")}_note`,migrationId:`${e}-0001-init`}}function Xk(e){return["defineCommand",...e==="hooks"?["defineAfterCommandHook"]:[],...e==="search"?["defineSearchProvider","defineVectorStoreAdapter"]:[],...e==="importers"?["defineImporter","defineExporter"]:[],...e==="schema"?["defineItemType","defineItemField","defineMigration"]:[],...e==="profile"?["defineProjectProfile"]:[],...e==="renderers"?["defineRendererOverride"]:[],...e==="parser"?["defineParserOverride"]:[],...e==="preflight"?["definePreflightOverride"]:[],...e==="services"?["defineServiceOverride"]:[]].join(", ")}function Zk(e,t,n,r){let i=["export const pingCommand = defineCommand({",` name: ${JSON.stringify(t)},`,' description: "Starter scaffold command. Replace with your own behavior.",',...n==="parser"?[" flags: [",' { long: "--shout", value_type: "boolean", description: "Deprecated alias for --upper." },',' { long: "--upper", value_type: "boolean", description: "Canonical flag the parser produces." },'," ],"," run: (context) => ({ ok: true, command: context.command, upper: context.options.upper === true }),"]:[" run: (context) => ({ ok: true, command: context.command }),"],"});"];return n==="hooks"&&i.push("","export const afterCommandHook = defineAfterCommandHook((context) => {"," if (!context.ok) return;"," // React to context.affected here as your package grows.","});"),n==="search"&&i.push("","export const searchProvider = defineSearchProvider({",` name: ${JSON.stringify(r.searchProviderName)},`," query: async (context) => ({"," hits: context.documents",' .filter((document) => String(document.metadata.title ?? "").toLowerCase().includes(context.query.toLowerCase()))',' .map((document) => ({ id: document.metadata.id, score: 1, matched_fields: ["title"] })),'," }),"," embed: async (context) => [context.input.length],","});","","export const vectorStoreAdapter = defineVectorStoreAdapter({",` name: ${JSON.stringify(r.vectorAdapterName)},`,' query: async (context) => [{ id: "starter-vector-hit", score: context.limit }],'," upsert: async (context) => ({ upserted: context.points.length }),"," delete: async (context) => ({ deleted: context.ids.length }),","});"),n==="importers"&&i.push("","export const importer = defineImporter(async (context) => ({"," imported: 1,",' source: context.options.source ?? "starter",'," args: context.args,","}));","","export const exporter = defineExporter(async (context) => ({"," exported: true,",' destination: context.options.destination ?? "stdout",'," args: context.args,","}));"),n==="schema"&&i.push("",`export const noteField = defineItemField({ name: ${JSON.stringify(r.fieldName)}, type: "string", optional: true });`,"","export const itemType = defineItemType({",` name: ${JSON.stringify(r.itemTypeName)},`,` folder: ${JSON.stringify(r.itemTypeFolder)},`,` aliases: ${JSON.stringify(r.itemTypeAliases)},`," required_create_fields: [],","});","","export const initMigration = defineMigration({",` id: ${JSON.stringify(r.migrationId)},`,` description: ${JSON.stringify(`Initialize ${e} schema state.`)},`," mandatory: false,"," run: async (context) => ({ migrated: true, id: context.id }),","});"),n==="profile"&&i.push("","export const starterProfile = defineProjectProfile({",` name: ${JSON.stringify(e)},`,` title: ${JSON.stringify(`${e} archetype`)},`,' summary: "Starter project profile. Replace these dimensions with your own archetype.",'," types: [",` { name: ${JSON.stringify(r.itemTypeName)}, folder: ${JSON.stringify(r.itemTypeFolder)} },`," ],"," // ...plus statuses, fields, workflows, config, templates, and packages.","});"),n==="renderers"&&i.push("","export const toonRenderer = defineRendererOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => JSON.stringify(context.result),","});"),n==="parser"&&i.push("","export const pingParser = defineParserOverride((context) => {"," const options = { ...context.options };"," if (options.shout === true) options.upper = true;"," delete options.shout;"," return { options };","});"),n==="preflight"&&i.push("","// Return a delta of the gate-decision keys you want to change; returning","// context.decision unchanged is a safe no-op (e.g. { run_extension_migrations: false }).","export const preflightOverride = definePreflightOverride({",` commands: [${JSON.stringify(t)}],`," run: (context) => context.decision,","});"),n==="services"&&i.push("","export const outputService = defineServiceOverride((context) => {",` if (context.command !== ${JSON.stringify(t)}) return { handled: false };`,` return { rendered_by: ${JSON.stringify(e)}, payload: context.payload };`,"});"),i}function Qk(e,t,n){let r=[];return t==="renderers"&&r.push(' api.registerRenderer("toon", toonRenderer.run, toonRenderer);'),t==="parser"&&r.push(` api.registerParser(${JSON.stringify(e)}, pingParser);`),t==="preflight"&&r.push(" api.registerPreflight(preflightOverride);"),t==="services"&&r.push(' api.registerService("output_format", outputService);'),t==="hooks"&&r.push(" api.hooks.afterCommand(afterCommandHook);"),t==="search"&&r.push(" api.registerSearchProvider(searchProvider);"," api.registerVectorStoreAdapter(vectorStoreAdapter);"),t==="schema"&&r.push(" api.registerItemFields([noteField]);"," api.registerItemTypes([itemType]);"," api.registerMigration(initMigration);"),t==="profile"&&r.push(" api.registerProfile(starterProfile);"),t==="importers"&&r.push(` api.registerImporter(${JSON.stringify(n.adapterName)}, importer, {`,` action: ${JSON.stringify(`${n.adapterName} import`)},`,' description: "Import starter records into pm context.",'," flags: ["," {",' long: "--source",',' value_name: "name",',' value_type: "string",',' description: "Source name or path to import from.",'," },"," ],"," });",` api.registerExporter(${JSON.stringify(n.adapterName)}, exporter, {`,` action: ${JSON.stringify(`${n.adapterName} export`)},`,' description: "Export pm context into starter records.",'," flags: ["," {",' long: "--destination",',' value_name: "name",',' value_type: "string",',' description: "Destination name or path to export to.",'," },"," ],"," });"),r}function eS(e,t,n,r="commands",i=!1){let a=`pm-${e}`,o=Up[r],s=zk(e,t,r),c=`${JSON.stringify({name:e,version:"0.1.0",entry:"./index.ts",manifest_version:cs,pm_min_version:Kt,trusted:!0,sandbox_profile:"strict",permissions:{...Rk},capabilities:o,...s.length>0?{activation:{commands:s}}:{}},null,2)}
48
+ `,l=['import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"","export function activate(api: ExtensionApi): void {",...Uk(e,t,r),"}","","// `deactivate` is the teardown counterpart to `activate`: pm runs it on host","// shutdown/reload (e.g. the MCP server between requests) to release anything","// `activate` opened - timers, connections, caches. This starter holds no such","// resources, so it stays a documented no-op; add cleanup here as you grow.","export function deactivate(): void {}","","export default {"," activate,"," deactivate,","};",""].join(`
49
+ `),d=`${JSON.stringify($k,null,2)}
50
+ `,u=Dk[r],m=zp(r,"package"),f=`${JSON.stringify({name:a,version:"0.1.0",private:!0,type:"module",keywords:["pm-package"],engines:{node:Ak},scripts:{typecheck:"tsc --noEmit","test:runtime":"node --test",test:"npm run typecheck && npm run test:runtime"},peerDependencies:{"@unbrained/pm-cli":`>=${Kt}`},devDependencies:{"@types/node":Tk,typescript:Ck},pm:{aliases:[e],extensions:["."],docs:["README.md"],examples:["README.md"],catalog:{display_name:e,category:"workflow",summary:"Starter pm package scaffold.",tags:["starter"]}}},null,2)}
51
+ `,p=Hk(e,t,r),h=Pk[r],_=["node_modules/","*.log","*.tsbuildinfo",""].join(`
52
+ `),w=Yk(e),v=["```ts",`import { ${Xk(r)} } from "@unbrained/pm-cli/sdk";`,'import type { ExtensionApi } from "@unbrained/pm-cli/sdk";',"",...Zk(e,t,r,w),"","export function activate(api: ExtensionApi): void {"," api.registerCommand(pingCommand);",...Qk(t,r,w),"}","","export function deactivate(): void {}","","export default { activate, deactivate };","```"],S=[`# ${a}`,"","Generated by `pm package init` or `pm extension init`.","","## Included Files","- `package.json`: package metadata, `typecheck`/`test` scripts, and `pm` resource manifest.",m,u,h,Hp,"- `.gitignore`: ignores `node_modules/`, logs, and the TypeScript build cache.","","## Quick Start","This package is authored AND loaded as TypeScript: the manifest `entry` is","`./index.ts` and pm imports it directly via Node's native type stripping","(Node >=22.18), so there is no build step \u2014 install and run:","```bash","npm install","pm install --project <package-path>",`pm ${t}`,"pm package doctor --project --detail summary","```","","## Validate the Package","`npm install` pulls the peer SDK and TypeScript. `npm test` is the default","validation gate: it type-checks the package, then runs the colocated sample:","```bash","npm install","npm test","```","`npm run typecheck` is available when you only want the SDK contract check.","`npm run test:runtime` runs just `node --test`, which strips types on load and","executes `index.test.ts` directly against the `@unbrained/pm-cli/sdk/testing`","helpers - no compile step and no extra test runner required.","","## Authoring With define* Builders","`index.ts` is authored fully in TypeScript so every registration is checked","against the SDK contracts at author time. Use the public SDK authoring","builders for exported definitions you want literal-type preservation,","contextual handler inference, and direct unit tests for:",...v,"The builders return their argument unchanged; runtime validation still lives","in `api.register*`, and behavior validation lives in `sdk/testing`.",...Nk[r],...Wp(r,"package"),"","## Compatibility Bounds",`- \`peerDependencies["@unbrained/pm-cli"]\` uses the stable range \`>=${Kt}\`. Keep a normal stable range instead of pinning a date ordinal: SemVer excludes prerelease ordinals such as \`2026.7.24-3\`, while daily stable releases continue to satisfy the range.`,"`manifest.json` cannot hold comments, so the version-compatibility fields are documented here:",`- \`manifest_version\` (integer): manifest schema generation. Leave at \`${cs}\` unless you adopt a newer manifest schema.`,`- \`pm_min_version\` (string): lowest pm CLI version that may load this package. Scaffolded as \`${Kt}\`. The loader blocks the package on older CLIs.`,"- `pm_max_version` (string, optional): highest pm CLI version that may load this package. Add it to block CLIs that are newer than the version you have validated against. The loader blocks the package when the CLI exceeds this bound.","","## Policy Metadata",'The starter command is pure compute, so `manifest.json` declares `trusted: true`, `sandbox_profile: "strict"`, and all six permission keys as `false`. Keep that least-privilege shape for pure packages; relax only the specific permission your package actually needs and verify with `pm package doctor --project --detail deep --trace`.',"","## Notes","- Author in `index.ts`; pm loads it directly (no build), so edits take effect on the next install/reload \u2014 there is no `.js` to regenerate.","- Move larger runtimes into sibling or subdirectory `*.ts` modules and import them with their real `.ts` extension; `tsconfig.json` type-checks every `*.ts` in the package (recursively).","- Add capabilities to the extension manifest only when the entrypoint uses the matching SDK API.","- Use `@unbrained/pm-cli/sdk` as the public SDK import for richer package runtimes.",""].join(`
53
+ `);return{"package.json":f,"manifest.json":c,"index.ts":i?Vk(e,t,r):l,"index.test.ts":i?Jk(e,t,r):p,"tsconfig.json":d,".gitignore":_,"README.md":i?Kk(a,t,r):S}}async function qp(e,t="extension",n="commands",r=!1){let i=n.trim().toLowerCase();if(!Lp.includes(i))throw new y(`Unknown scaffold capability "${n}". Supported capabilities: ${Lp.join(", ")}.`,g.USAGE);let a=i;if(r&&t!=="package")throw new y("--declarative scaffolds a package-mode blueprint starter (composeExtension is a runtime SDK import). Use `pm package init`, not `pm extension init`.",g.USAGE);let o=r?"declarative":"imperative",s=e.trim(),c=wr.resolve(process.cwd(),s),l=zi(wr.basename(c)).replace(/^(?:pm-)+/u,""),d=Fk(l),u=eS(l,d,t,a,r),m=!1;if(await O(c)){if(!(await yr.stat(c)).isDirectory())throw new y(`Scaffold target "${c}" exists and is not a directory.`,g.CONFLICT)}else await yr.mkdir(c,{recursive:!0}),m=!0;for(let[p,h]of Object.entries(u)){let _=wr.join(c,p);if(await O(_)&&await yr.readFile(_,"utf8")!==h)throw new y(`Scaffold file "${p}" already exists with different content in "${c}". Choose a new target path or remove conflicting files.`,g.CONFLICT)}let f=[];for(let[p,h]of Object.entries(u)){let _=wr.join(c,p);if(await O(_)){f.push({path:p,status:"unchanged"});continue}await yr.mkdir(wr.dirname(_),{recursive:!0}),await yr.writeFile(_,h,"utf8"),f.push({path:p,status:"created"})}return{extension_name:l,package_name:`pm-${l}`,command_name:d,invocation_command:`pm ${d}`,capability:a,style:o,target_path:c,created_directory:m,files:f}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d50733c-ced5-5ec8-b82e-2391a974ad0f")}catch{}})();function Bp(e,t){return`${e}:${A(t)}`}function tS(e,t){let n=[];for(let[r,i]of[["handler",e.commands.handlers],["override",e.commands.overrides]]){let a=new Map;for(let o of i){let s=a.get(o.command)??[];a.set(o.command,[...s,o])}for(let[o,s]of a){if(t!==null&&!s.some(l=>t.has(A(l.name))))continue;let c=s.at(-1);n.push({command:o,surface:r,policy:"last_activated_wins",collision:s.length>1,claimants:s.map(l=>({name:l.name,layer:l.layer,winner:l===c}))})}}return n.sort((r,i)=>r.command.localeCompare(i.command)||r.surface.localeCompare(i.surface))}function Vp(e,t,n){let r=new Set(n.failed.map(l=>Bp(l.layer,l.name))),i=[...t.loaded.map(l=>({name:l.name,layer:l.layer,version:l.version,activation_status:r.has(Bp(l.layer,l.name))?"failed":"ok",surfaces:Sn(n,{extensionName:l.name})})),...t.failed.map(l=>({name:l.name,layer:l.layer,version:"unknown",activation_status:"not_loaded",surfaces:Sn(n,{extensionName:l.name})}))].sort((l,d)=>l.name.localeCompare(d.name)||l.layer.localeCompare(d.layer)),a=typeof e=="string"?A(e):null,o=a===null?null:new Set(t.loaded.filter(l=>A(l.name)===a||typeof l.source_package=="string"&&A(l.source_package)===a||(l.source_aliases??[]).some(d=>A(d)===a)).map(l=>A(l.name)).concat(a)),s=o===null?i:i.filter(l=>o.has(A(l.name))),c=o===null?{}:{extensionNames:[...o]};return{target:typeof e=="string"?e.trim():null,total:s.length,extensions:s,union:Sn(n,c),command_ownership:tS(n,o)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1e6087f2-01b5-59c3-a471-433c722316b0")}catch{}})();function ds(e){return e.map(({layer:t,name:n,error:r})=>({layer:t,name:n,error:r}))}function Yi(e,t,n){let r=A(t),i=n.trim();if(r.length===0||i.length===0)return;let a=e.get(r)??new Set;a.add(i),e.set(r,a)}function nS(e){let t=new Map,n=new Map;for(let r of e.registrations.commands)Yi(t,r.name,r.command),Yi(n,r.name,r.action);for(let r of e.commands.handlers)Yi(t,r.name,r.command);for(let r of e.commands.overrides)Yi(t,r.name,r.command);return{commandPathsByExtension:t,actionPathsByExtension:n}}function Jp(e){if(!(!e||e.size===0))return[...e].sort((t,n)=>t.localeCompare(n))}function rS(e){let{enabled:t,normalizedName:n,loadedNames:r,loadFailedNames:i,activationFailedNames:a}=e;return t?i.has(n)||a.has(n)?{runtime_active:!1,activation_status:"failed"}:r.has(n)?{runtime_active:!0,activation_status:"ok"}:{runtime_active:!1,activation_status:"not_loaded"}:{runtime_active:!1,activation_status:"not_loaded"}}function Xi(e,t,n){let r=new Set(t.loaded.map(c=>A(c.name))),i=new Set(t.failed.map(c=>A(c.name))),a=new Set(n.failed.map(c=>A(c.name))),{commandPathsByExtension:o,actionPathsByExtension:s}=nS(n);return e.map(c=>{let l=A(c.name),d=Jp(o.get(l)),u=Jp(s.get(l)),m={...d?{command_paths:d}:{},...u?{action_paths:u}:{}},f=rS({enabled:c.enabled,normalizedName:l,loadedNames:r,loadFailedNames:i,activationFailedNames:a});return{...c,...f,...m}})}function iS(e){let t=0,n=0,r=0;for(let i of e)if(i.startsWith("extension_policy_")){if(t+=1,i.startsWith("extension_policy_violation_")){n+=1;continue}i.startsWith("extension_policy_blocked_")&&(r+=1)}return{warning_count:t,violation_count:n,blocked_count:r}}function me(e,t){return e.vocabulary==="package"?`pm package --${t}`:`pm extension --${t}`}var Xp=new Set(["extension_command_handler_collision","extension_command_override_collision","extension_command_override_handler_overlap","extension_parser_override_collision","extension_preflight_override_collision","extension_renderer_collision","extension_service_override_collision"]);function aS(e){return Xp.has(rf(e))}function Kp(e){return e==="project"||e==="global"}function Zp(e){let t=e.split(":"),n=t[0];if(!n||!Xp.has(n))return null;let r=t.at(-4),i=t.at(-3)?.trim(),a=t.at(-2),o=t.at(-1)?.trim();return!Kp(r)||!Kp(a)||!i||!o?null:{code:n,surface:t.slice(1,-4).join(":")||"global",winner:{layer:r,name:i},displaced:{layer:a,name:o}}}function oS(e){let t=new Set;for(let n of e){let r=Zp(n);r&&(t.add(r.winner.name),t.add(r.displaced.name))}return[...t].sort((n,r)=>n.localeCompare(r))}function us(e,t){let n=e.filter(aS);if(n.length===0)return null;let r=oS(n);return`Extension registration collisions or handler/override overlaps detected.${r.length>0?` Conflicting extensions: ${r.join(", ")}.`:""} Single-winner surfaces can hide earlier package behavior. Deactivate one conflicting package with ${t.deactivate}, or scope registration surfaces in extensions.policy.extension_overrides, then rerun ${t.doctor}.`}function sS(e,t,n,r){let i=t.map(u=>Zp(u)).filter(u=>u!==null).sort((u,m)=>`${u.code}:${u.surface}:${u.winner.name}:${u.displaced.name}`.localeCompare(`${m.code}:${m.surface}:${m.winner.name}:${m.displaced.name}`));if(i.length===0)return;let a=e==="global"?"--global":"--project",o=me(r,"deactivate"),s=`${me(r,"doctor")} ${a} --detail deep --trace`,c=new Map(n.map(u=>[A(u.name),u])),l=new Map;for(let u of i)for(let m of[u.winner.name,u.displaced.name]){let f=A(m);l.set(f,(l.get(f)??0)+1)}let d=[...l.entries()].map(([u,m])=>{let f=c.get(u),p=f?.name??u,h=f?.command_paths??[],_=f?.action_paths??[];return{action:"deactivate",extension:p,command:`${o} ${p} ${a}`,affected_collisions:m,feature_loss:{command_paths:[...h].sort((w,v)=>w.localeCompare(v)),action_paths:[..._].sort((w,v)=>w.localeCompare(v))}}}).sort((u,m)=>{let f=m.affected_collisions-u.affected_collisions;if(f!==0)return f;let p=u.feature_loss.command_paths.length+u.feature_loss.action_paths.length,h=m.feature_loss.command_paths.length+m.feature_loss.action_paths.length;return p!==h?p-h:u.extension.localeCompare(m.extension)});return{status:"conflicts_detected",collision_count:i.length,extension_count:l.size,next_best_command:s,collisions:i,remediation_candidates:d}}function Qp(e){let t=[];for(let n of e){let r=n.error.toLowerCase();(r.includes("cannot find package '@unbrained/pm-cli'")||r.includes('cannot find module "@unbrained/pm-cli"')||r.includes("cannot find module '@unbrained/pm-cli'"))&&t.push(`extension_load_failed_sdk_dependency_missing:${n.name}`),(r.includes("cannot use import statement outside a module")||r.includes("to load an es module")||r.includes("must use import to load es module"))&&t.push(`extension_load_failed_module_mode_mismatch:${n.name}`)}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}function ef(e=[]){let t=Array.isArray(e)?e:[],n=[];for(let r of t){if(!r||typeof r.name!="string")continue;let i=r.trace?.missing_capability??r.trace?.capability;typeof i=="string"&&i.trim().length>0&&n.push(`extension_capability_missing:${r.name}:${i.trim().toLowerCase()}`)}return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}function tf(e,t){let n=[];for(let r of Tl(e.loaded,t))for(let i of r.unused)n.push(`extension_capability_unused:${r.layer}:${r.name}:${i}`);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}var cS=[{matches:e=>e.some(t=>t.startsWith("extension_manifest_")),build:e=>`Run ${me(e.options,"explore")} ${e.scopeFlag} to inspect discovered manifests and directories.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unknown:")),build:()=>`Unknown extension capabilities detected. Allowed capabilities: ${Ur.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_legacy_alias:")),build:()=>"Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."},{matches:e=>e.some(t=>t.startsWith("extension_capability_missing:")),build:e=>`Extension activation failed because code registered a surface missing from manifest capabilities. Run ${me(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace and add the reported missing_capability to manifest.json before publishing.`},{matches:e=>e.some(t=>t.startsWith("extension_capability_unused:")),build:e=>`Extension manifests declare capabilities that are never registered against. Remove each reported unused capability from manifest.json to keep least privilege, or add the matching registration. Run ${me(e.options,"doctor")} ${e.scopeFlag} --detail deep --trace for per-extension registration counts.`},{matches:e=>e.some(t=>t.startsWith("extension_command_definition_legacy_handler_alias:")),build:()=>"Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."},{matches:e=>e.some(t=>t.startsWith("extension_output_service_override_global:")||t.startsWith("extension_output_renderer_override_global:")),build:()=>"Global output service/renderer overrides are active. For output_format, return context.payload/null/undefined unless the extension owns the command. For renderers, return null for unrelated payloads so pm falls back to native rendering."},{matches:e=>e.some(t=>t.startsWith("extension_schema_narrow_activation:")),build:()=>"A package registers custom item types/fields (a GLOBAL schema contribution) but also declares narrow activation.commands, so it never activates for built-in commands like pm create <type> and the custom type silently fails to register. Remove activation.commands from manifest.json so pm activates the package for every command, or \u2014 if the schema is intentionally command-scoped \u2014 knowingly ignore this advisory."},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_sdk_dependency_missing:")),build:e=>`Detected extension load failures caused by missing SDK dependency resolution. Ensure extension package dependencies include "@unbrained/pm-cli" and reinstall dependencies before running ${me(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_load_failed_module_mode_mismatch:")),build:e=>`Detected extension module-mode mismatches. For ESM-based extension entries/imports, set package.json "type": "module" or use an explicit .mjs entry and rerun ${me(e.options,"doctor")} ${e.scopeFlag}.`},{matches:e=>e.some(t=>t.startsWith("extension_pm_min_version_")||t.startsWith("extension_pm_max_version_")),build:e=>`Extension pm version-bound warnings detected. Align each package manifest's pm_min_version/pm_max_version with the installed pm CLI version (see the warning's required/allowed=...:current=... details), or upgrade/downgrade the pm CLI to satisfy the declared bounds, then rerun ${me(e.options,"doctor")} ${e.scopeFlag}.`},{matches:(e,t)=>t.updateCheckFailedTotal>0,build:e=>`Run ${me(e.options,"manage")} ${e.scopeFlag} after validating network and repository access.`},{matches:e=>e.some(t=>t.startsWith("extension_manager_state_")),build:e=>`Review and repair ${e.scope} managed extension state file if schema/read warnings persist.`},{matches:(e,t)=>t.policyWarningCount>0,build:()=>"Extension governance policy warnings detected. Review settings.extensions.policy mode and allow/block lists to confirm intended capabilities and registration surfaces."}];function lS(e){let{normalizedWarnings:t,options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:a,policyWarningCount:o,unmanagedActionRequiredTotal:s,notCheckedTotal:c,skippedNonGithubTotal:l,updateAvailableTotal:d}=e,u=[],m={options:n,scope:r,scopeFlag:i,updateCheckFailedTotal:a,policyWarningCount:o};if(t.length>0){let f=us(t,{deactivate:`${me(n,"deactivate")} <name> ${i}`,doctor:`${me(n,"doctor")} ${i} --detail deep --trace`});f&&u.push(f);for(let p of cS)p.matches(t,m)&&u.push(p.build(m))}return s>0&&u.push(`Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via ${me(n,"manage")} ${i} --fix-managed-state (or ${me(n,"adopt-all")} ${i}, ${me(n,"adopt")} <name> ${i}, or reinstall via ${me(n,"install")} ${i} <source>).`),l>0&&u.push("Update-check coverage is partial: non-GitHub managed sources were not checked. Inspect their registry or source directly; zero detected updates does not mean these packages are current. Runtime activation health is independent."),c>0&&u.push(`Update-check coverage is partial: some sources have no completed check. Run ${me(n,"manage")} ${i} to request update checks.`),d>0&&u.push(`Update available managed extensions via ${me(n,"install")} ${i} <source>.`),u.length===0&&u.push(`No immediate action required. Re-run ${me(n,"manage")} ${i} after extension changes.`),u}function Zi(e,t,n,r={}){let i=[...new Set(t)].sort((b,N)=>b.localeCompare(N)),a=n.filter(b=>b.managed).length,o=n.filter(b=>b.enabled).length,s=n.filter(b=>b.active).length,c=n.filter(b=>b.update_check_status==="checked"&&b.update_available===!0).length,l=n.filter(b=>b.managed===!1),d=l.filter(b=>Yp(b)).map(b=>b.name).sort((b,N)=>b.localeCompare(N)),u=l.filter(b=>!Yp(b)).map(b=>b.name).sort((b,N)=>b.localeCompare(N)),m={checked:0,skipped_unmanaged:0,skipped_non_github:0,failed:0,not_checked:0};for(let b of n)m[b.update_check_status]+=1;let f=m.failed,p=n.filter(b=>b.update_check_status==="skipped_non_github"&&b.source?.kind!=="builtin").length,h=Object.entries({skipped_unmanaged:u.length,skipped_non_github:p,failed:f,not_checked:m.not_checked}).filter(([,b])=>b>0).map(([b,N])=>`extension_update_health_partial_coverage:${b}:${N}`),_=h.length>0,w=_?"partial":"full",v=[...new Set([...i,...h])].sort((b,N)=>b.localeCompare(N)),S=[...new Set(v.map(b=>rf(b)))].sort((b,N)=>b.localeCompare(N)),k=iS(v),x=e==="global"?"--global":"--project",D=sS(e,i,n,r),E=lS({normalizedWarnings:v,options:r,scope:e,scopeFlag:x,updateCheckFailedTotal:f,policyWarningCount:k.warning_count,unmanagedActionRequiredTotal:u.length,notCheckedTotal:m.not_checked,skippedNonGithubTotal:p,updateAvailableTotal:c});return{status:v.length===0?"ok":"warn",warning_count:v.length,warning_codes:S,warnings:v,policy_warning_count:k.warning_count,policy_violation_count:k.violation_count,policy_blocked_count:k.blocked_count,total_extensions:n.length,managed_total:a,enabled_total:o,active_total:s,update_available_total:c,update_health_coverage:w,update_health_partial:_,unmanaged_loaded_extension_count:l.length,unmanaged_loaded_extensions:l.map(b=>b.name).sort((b,N)=>b.localeCompare(N)),unmanaged_expected_extension_count:d.length,unmanaged_expected_extensions:d,unmanaged_action_required_extension_count:u.length,unmanaged_action_required_extensions:u,update_check_status_totals:m,update_check_failed_total:f,top_warnings:v.slice(0,8),remediation:E,...D?{collision_plan:D}:{}}}function nf(e){if(!e||e.trim().length===0)return"summary";let t=e.trim().toLowerCase();if(t==="summary"||t==="deep")return t;throw new y(`Invalid --detail value "${e}". Expected summary or deep.`,g.USAGE)}function rf(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function vr(e){let t=new Set,n=[];for(let r of e){let i=(()=>{let a=Fc(r);return a?[a]:Uc(r)})();for(let a of i){let o=`${a.layer}:${a.name}:${a.capability}`;t.has(o)||(t.add(o),n.push(a))}}return n}function br(){return{version:Hr.version,capabilities:[...Hr.capabilities],legacy_aliases:{...Hr.legacy_aliases}}}function Yp(e){let t=A(e.name),n=A(e.directory);return t.startsWith("builtin-")?!0:n==="beads"||n==="todos"}function af(e,t,n,r,i){if(e!=="project"||i)return{warnings:[],summary:{active_project_count:0,loaded_project_count:0,active_project_names:[],loaded_project_names:[],missing_active_project_names:[]}};let a=[...new Set(t.filter(l=>l.active).map(l=>A(l.name)))].sort((l,d)=>l.localeCompare(d)),o=[...new Set(n.filter(l=>l.layer==="project").map(l=>A(l.name)))].sort((l,d)=>l.localeCompare(d)),s=new Set(r.map(l=>A(l.name))),c=a.filter(l=>!o.includes(l)&&!s.has(l)).sort((l,d)=>l.localeCompare(d));return{warnings:c.length>0?[`extension_doctor_consistency_active_not_loaded:${c.join(",")}`]:[],summary:{active_project_count:a.length,loaded_project_count:o.length,active_project_names:a,loaded_project_names:o,missing_active_project_names:c}}}import of from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="147fb29e-ad06-5850-b0b1-f643e32e9b1f")}catch{}})();function kr(e,t,n,r){let i=of.relative(e,n);if(i!==""&&!fe(e,n)||n===t||fe(t,n))return!1;let a=i.split(of.sep);return a.includes(".git")?!1:r?!a.some(o=>o===".agents"||o==="node_modules"||o.startsWith(".pm-extension-install-backup-")):!0}import{randomUUID as dS}from"node:crypto";import se from"node:fs/promises";import uS from"node:os";import ne from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cefb224d-a18f-599a-9cf9-3d3a22616440")}catch{}})();var sf=3,mS=120,cf=250,pS=12e4,fS=new Set(["EEXIST","ENOTEMPTY","ENOENT"]),lf=e=>typeof e=="object"&&e!==null&&"code"in e?e.code:void 0,df=e=>fS.has(String(lf(e))),Qi=(e,t)=>lf(e)===t,uf=e=>new Promise(t=>{setTimeout(t,e)}),mf=async e=>{let t=ne.join(e,"package.json");await O(t)||await se.writeFile(t,`${JSON.stringify({type:"module"},null,2)}
54
+ `,"utf8")},pf=async e=>{let t=Ne(import.meta.url,["../../.."]),n=ne.join(e,"node_modules","@unbrained"),r=ne.join(n,"pm-cli");await se.mkdir(n,{recursive:!0}),await se.rm(r,{recursive:!0,force:!0}),await se.symlink(t,r,process.platform==="win32"?"junction":"dir")},Sr=async e=>{let t=ne.resolve(e),n=ne.dirname(t),r=ne.parse(n).root,i=await se.realpath(r).catch(()=>r),a=ne.relative(r,n),o=a===""?[]:a.split(ne.sep);for(let[s,c]of o.entries()){let l=ne.join(i,c);try{i=await se.realpath(l)}catch{i=ne.join(i,...o.slice(s));break}}return ne.join(i,ne.basename(t))},ff=async(e,t,n,r=uS.tmpdir())=>jt("extension_install_copy",async()=>{let i=ne.resolve(e),a=await se.realpath(i).catch(()=>i),o=await Sr(t);if(a===o)return;if(!fe(a,o)){await n(a,t,{recursive:!0,force:!0,filter:u=>kr(a,o,ne.resolve(u),!1)});return}let s=await se.realpath(ne.resolve(r)).catch(()=>Sr(r)),c=fe(a,s)?ne.dirname(a):s;if(fe(a,c))throw new y(`Extension source "${e}" contains its install destination and no external staging directory is available. Install a narrower package directory instead.`,g.USAGE,{code:"extension_install_source_contains_destination"});let l=await se.mkdtemp(ne.join(c,"pm-extension-copy-")),d=ne.join(l,"extension");try{await n(a,d,{recursive:!0,force:!0,filter:u=>kr(a,o,ne.resolve(u),!0)}),await n(d,t,{recursive:!0,force:!0})}finally{await se.rm(l,{recursive:!0,force:!0})}}),hf=async(e,t,n=se.cp)=>{for(let r=1;r<=sf;r+=1)try{await jt("extension_install_copy",async()=>{await se.rm(t,{recursive:!0,force:!0}),await ff(e,t,n)});return}catch(i){if(!df(i)||r===sf)throw i;await uf(cf)}},ms=async e=>{let t;try{t=await se.readFile(ne.join(e,"owner.json"),"utf8")}catch(i){if(!bt(i))throw i;return null}let n;try{n=JSON.parse(t)}catch{return null}if(typeof n!="object"||n===null||!("token"in n))return null;let r=n.token;return typeof r=="string"&&r.length>0?r:null},_f=async(e,t)=>await ms(e)!==t?!1:(await se.rm(e,{recursive:!0,force:!0}),!0),hS=async(e,t)=>{let n;try{n=await se.stat(e)}catch{return!1}if(Date.now()-n.mtimeMs<=t)return!1;let r=await ms(e);return r===null?(await se.rm(e,{recursive:!0,force:!0}),!0):_f(e,r)},_S=(e,t,n)=>{let r=Promise.resolve(),i=setInterval(()=>{r=r.then(async()=>{if(await ms(e)!==t)return;let a=new Date;await se.utimes(e,a,a)}).catch(()=>{})},n);return i.unref(),async()=>{clearInterval(i),await r}},gS=async(e,t)=>{await se.mkdir(e);try{await se.writeFile(ne.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
55
+ `,"utf8")}catch(n){throw await se.rm(e,{recursive:!0,force:!0}).catch(()=>{}),n}},yS=async(e,t,n,r,i)=>{for(let a=1;a<=n;a+=1)try{return await gS(e,t),!0}catch(o){if(!Qi(o,"EEXIST"))throw o;await hS(e,i)?a-=1:await uf(r)}return!1},ps=async(e,t,n,r)=>jt("extension_install",async()=>{let i=ne.join(e,"runtime","extension-install-locks"),a=ne.join(i,"scope.lock");await se.mkdir(i,{recursive:!0});let{attempts:o=mS,delay_ms:s=cf,stale_ms:c=pS,heartbeat_ms:l}=r??{};if(![o,s,c,l].filter(w=>w!==void 0).every(Number.isFinite))throw new y("Extension install lock timings must be finite numbers.",g.USAGE);let d=Math.max(1,Math.floor(o)),u=Math.max(0,Math.floor(s)),m=Math.floor(c),f=Math.floor(l??m/3);if(m<=0||f<=0||f>=m)throw new y("Extension install lock timings require stale_ms > 0 and 0 < heartbeat_ms < stale_ms.",g.USAGE);let p={pid:process.pid,token:dS(),created_at:$(),destination:t};if(!await yS(a,p,d,u,m))throw new y(`Timed out waiting for extension install lock for "${t}".`,g.CONFLICT);let h=_S(a,p.token,f),_=!1;try{let w=await n();return _=!0,w}finally{await h(),await _f(a,p.token).catch(w=>{if(_)throw w})}});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eb830963-f036-5f98-ab26-786240b3e0fd")}catch{}})();var gf=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let r=new Array(e.length),i=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;i<e.length;){let o=i;i+=1,r[o]=await n(e[o])}});return await Promise.all(a),r};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accde468-de04-51b6-81ad-5c5ea218a87b")}catch{}})();function yf(e,t){let n=A(e),r=t.find(i=>A(i.name)===n);return{command_paths:[...r?.command_paths??[]].sort((i,a)=>i.localeCompare(a)),action_paths:[...r?.action_paths??[]].sort((i,a)=>i.localeCompare(a))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2cac210-bba0-5c7f-867b-8b59f8d36e11")}catch{}})();function wf(e,t){let n=new Set((t?.loaded??[]).flatMap(a=>(a.activation?.commands?.length??0)>0?[`${a.layer}:${A(a.name)}`]:[])),r=e.services.overrides.filter(a=>a.service==="output_format").filter(a=>a.passThrough!==!0).filter(a=>!n.has(`${a.layer}:${A(a.name)}`)).map(a=>`extension_output_service_override_global:${a.service}:${a.layer}:${a.name}`),i=e.renderers.overrides.filter(a=>(a.commands?.length??0)===0&&a.resultDiscriminator===void 0).map(a=>`extension_output_renderer_override_global:${a.format}:${a.layer}:${a.name}`);return[...new Set([...r,...i])].sort((a,o)=>a.localeCompare(o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a1803149-25ca-5bb0-a178-afa2d85d2ec9")}catch{}})();var vf=e=>[...e.registrations.item_fields.flatMap(t=>t.fields.map(n=>({layer:t.layer,extension:t.name,field:n.name}))),...e.registrations.profiles.flatMap(t=>t.profile.fields.map(n=>({layer:t.layer,extension:t.name,field:n.key??""})))].flatMap(t=>{let n=Qr(t.field);return n?[`extension_custom_field_mcp_input_collision:${t.layer}:${t.extension}:${n.field}:${n.property}:${n.owner}:use=${n.nested_path}`]:[]}).filter((t,n,r)=>r.indexOf(t)===n).sort((t,n)=>t.localeCompare(n));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eb2ad9e2-8e60-5cac-8874-ab9300621402")}catch{}})();var wS=1e4,vS=(e,t,n)=>{let r=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,c=""]=o.split(/\s+/);return{commit:s,ref:c}}),i=r.find(o=>o.ref.endsWith("^{}"))??r[0];if(!i)return{checked_at:n,available:null,error:"no_remote_reference_found"};let a=t?.trim();return a?{checked_at:n,remote_commit:i.commit,available:i.commit!==a}:{checked_at:n,remote_commit:i.commit,available:null,error:"missing_installed_commit"}},bf=async(e,t=qi)=>{let n=$();if(e.kind!=="github"||!e.repository)return{checked_at:n,available:null,error:"not_a_github_managed_source"};try{let r=[e.ref?.trim(),"HEAD"].find(Boolean),i=await t(["ls-remote",e.repository,r,`${r}^{}`],void 0,wS);return vS(i,e.commit,n)}catch(r){return{checked_at:n,available:null,error:r instanceof Error?r.message:String(r)}}};import bS from"node:fs/promises";import kS from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7be00b26-4a56-5399-94f6-f2f67cc5c1e6")}catch{}})();function fs(e){return kS.join(e,"extension-migrations.json")}function kf(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function Sf(e,t){return`${e.layer}:${e.name}:${t}`}async function SS(e){let t=fs(e);if(!await O(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await bS.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function hs(e,t){let n=await SS(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,a)=>{let o=kf(i,a),s=r.get(Sf(i,o));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function ES(e){let t=await hs(e.pmRoot,e.migrations),n=new Map(t.entries.map(d=>[d.key,d])),r=[],i=!1,a=e.migrations.map((d,u)=>({migration:d,index:u})).filter(({migration:d})=>e.scope===void 0||d.layer===e.scope);for(let{migration:d,index:u}of a){let m=kf(d,u),f=Sf(d,m),p=n.get(f),h=String(d.definition.status??"pending").toLowerCase(),_=p?.status??(h==="applied"||h==="failed"?h:"pending");if(_==="applied"){r.push({key:f,layer:d.layer,extension:d.name,id:m,before:_,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:f,layer:d.layer,extension:d.name,id:m,before:_,outcome:"pending"});continue}let w=d.runtime_definition?.run??d.definition.run;if(typeof w!="function"){r.push({key:f,layer:d.layer,extension:d.name,id:m,before:_,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:d.layer,extension:d.name,pm_root:e.pmRoot,status:_}));let S={key:f,layer:d.layer,extension:d.name,id:m,status:"applied",attempted_at:v};n.set(f,S),d.definition.status="applied",delete d.definition.reason,delete d.definition.error,delete d.definition.message,r.push({key:f,layer:d.layer,extension:d.name,id:m,before:_,outcome:"applied"}),i=!0}catch(S){let k=S instanceof Error?S.message:String(S),x={key:f,layer:d.layer,extension:d.name,id:m,status:"failed",attempted_at:v,error:k};n.set(f,x),d.definition.status="failed",d.definition.reason=k,r.push({key:f,layer:d.layer,extension:d.name,id:m,before:_,outcome:"failed",error:k}),i=!0}}if(i){let d=await C(e.pmRoot),u={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,f)=>m.key.localeCompare(f.key))};await li({pmRoot:e.pmRoot,filePath:fs(e.pmRoot),raw:`${JSON.stringify(u,null,2)}
56
+ `,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms})}let o=r.filter(d=>d.outcome==="pending").length,s=r.filter(d=>d.outcome==="applied").length,c=r.filter(d=>d.outcome==="skipped").length,l=r.filter(d=>d.outcome==="failed").length;return{ok:l===0,dry_run:e.dryRun===!0,state_path:fs(e.pmRoot),total:r.length,pending_count:o,applied_count:s,skipped_count:c,failed_count:l,migrations:r}}async function Ef(e){let t=await C(e.resolvedRoots.settings_root),n=await Je({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await Ke(n);e.warnings.push(...n.warnings,...r.warnings);let i=await ES({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},i.ok)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fcf7df06-e3b8-5476-a76a-cd391839c13d")}catch{}})();function xf(e,t){let n=e.filter(r=>r.result.ok).length;return{installed_all:!t&&n===e.length,installed_count:t?0:n,...t?{dry_run:!0,planned_count:n}:{},failed_count:e.length-n,packages:e.map(({alias:r,result:i})=>{let a=i.details;return{alias:r,ok:i.ok,extension:a.extension,source:a.source,source_resolution:a.source_resolution,install_plan:a.install_plan,dry_run:a.dry_run,destination_path:a.destination_path,activated:a.activated,settings_changed:a.settings_changed,command_paths:a.command_paths,action_paths:a.action_paths,command_discovery:a.command_discovery,verification:a.verification,runtime_activation_status:a.runtime_activation_status,activation_diagnostics:a.activation_diagnostics,warnings:i.warnings}})}}import ta from"node:fs/promises";import ea from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="18bf1015-c2c8-5530-a3ce-1531a8a1d0e2")}catch{}})();var xS=new Set(["node_modules",".git","dist","build","coverage"]);async function If(e,t,n,r){let i=e.source.kind==="local"?await ta.stat(e.source.absolute_path):void 0,a=e.source.kind==="local"?i.isDirectory()?"directory":"archive":e.source.kind,o=await IS(e.directory,t,r),s={source_mode:a,...a==="archive"?{archive_bytes:i.size}:{},copy:o},c=e.source_root??e.directory;if(a==="directory"&&(!o.complete||o.development_entries>0||o.bytes>=16*1024*1024)&&await O(ea.join(c,"package.json"))&&(s.packed_alternative={cwd:c,pack:{command:"npm",args:["pack","--ignore-scripts","--json"]},install:{command:"pm",args:["package","install","<archive-filename>",`--${n}`]},archive_argument:"pack_result[0].filename"}),a==="directory"&&!o.complete){let l=o.stop_reason==="entry_limit"?`${o.max_entries} entries`:`${o.max_depth} directory levels`;throw new y(`Local extension source scan stopped at ${l}; the directory snapshot is incomplete and installation was refused. ${s.packed_alternative?"Pack the package with npm pack --ignore-scripts --json, then install its archive.":"Install a smaller source directory or a packed archive."}`,g.USAGE,{code:"extension_install_incomplete_source_scan",reason:o.stop_reason,nextSteps:s.packed_alternative?[`Run npm pack --ignore-scripts --json from the package root, then pm package install <archive-filename> --${n}.`]:["Choose a smaller source directory or install a packed archive."]})}return s}async function IS(e,t,n={}){let{maxEntries:r=1e4,maxDepth:i=64,signal:a}=n;if(![r,i].every(u=>Number.isSafeInteger(u)&&u>0))throw new y("maxEntries and maxDepth must be positive safe integers.",g.USAGE);a?.throwIfAborted();let o=await ta.realpath(e),s=await Sr(t),c=await Ki(o,s);a?.throwIfAborted();let l=c?"in_place":fe(o,s)?"nested_filtered_snapshot":"directory_snapshot",d={copy_scope:l,source_directory:o,destination_directory:s,files:0,bytes:0,directories:0,symlinks:0,other_entries:0,scanned_entries:0,excluded_entries:0,development_entries:0,complete:!0,stop_reason:"complete",max_entries:r,max_depth:i};return l==="in_place"||await Af(o,0,d,a),d}async function Af(e,t,n,r){r?.throwIfAborted();let i=await ta.opendir(e);for await(let a of i){if(r?.throwIfAborted(),n.scanned_entries>=n.max_entries){n.complete=!1,n.stop_reason="entry_limit";return}n.scanned_entries+=1;let o=ea.join(e,a.name);if(!kr(n.source_directory,n.destination_directory,o,n.copy_scope==="nested_filtered_snapshot")){n.excluded_entries+=1;continue}if(ea.relative(n.source_directory,o).split(ea.sep).some(s=>xS.has(s))&&(n.development_entries+=1),await AS(o,t,n,r),!n.complete)return}}async function AS(e,t,n,r){let i=await ta.lstat(e);if(r?.throwIfAborted(),i.isDirectory()){if(n.directories+=1,t+1>=n.max_depth){n.complete=!1,n.stop_reason="depth_limit";return}await Af(e,t+1,n,r)}else i.isFile()?(n.files+=1,n.bytes+=i.size):i.isSymbolicLink()?n.symlinks+=1:n.other_entries+=1}import RS from"node:fs/promises";import CS from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="955d33c5-8c96-5ed6-bbd1-fc8a26801df4")}catch{}})();function TS(e){return typeof e.name=="string"&&e.name.trim().length>0?e.name.trim():"workspace-manifest"}function $S(e,t){return t.code==="manifest_unknown_key"?`extension_manifest_unknown_key:author:${e}:key=${t.path}${t.suggested_key?`:suggested=${t.suggested_key}`:""}`:`extension_manifest_no_version_bounds:author:${e}:suggested=pm_min_version`}async function _s(e){let t=CS.join(e,"manifest.json"),n;try{n=await RS.readFile(t,"utf8")}catch(s){if(bt(s))return{path:t,present:!1,parse_status:"absent",package_metadata_location:"package.json#pm",schema_findings:[],warnings:[],remediation:[]};throw s}let r;try{r=JSON.parse(n)}catch{return{path:t,present:!0,parse_status:"invalid_json",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_json:manifest.json"],remediation:["Repair manifest.json so it contains one valid JSON object, then rerun pm package doctor --project."]}}if(typeof r!="object"||r===null||Array.isArray(r))return{path:t,present:!0,parse_status:"invalid_shape",package_metadata_location:"package.json#pm",schema_findings:[],warnings:["extension_author_manifest_invalid_shape:manifest.json"],remediation:["Replace manifest.json with one JSON object, then rerun pm package doctor --project."]};let i=r,a=Bc(i),o=TS(i);return{path:t,present:!0,parse_status:"valid",package_metadata_location:"package.json#pm",schema_findings:a.findings,warnings:a.findings.map(s=>$S(o,s)),remediation:a.findings.map(s=>s.message)}}function Rf(e){return _s(Ve(e))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7bda052f-809f-5c09-bb28-ccb56a7f22b7")}catch{}})();async function Cf(e,t,n){let r=typeof t=="string"?null:await gr(e),i=r===null?null:e.trim().toLowerCase(),a=i===null?null:await kp(i),o=Vi(r??e,{forceGithub:typeof t=="string",ref:n}),s=i===null?null:await Ap(e);return{bundledAliasName:i,bundledPackageName:a,installSource:o,sourceResolution:{requested:e,selected:{kind:i===null?o.kind:"builtin",input:i??o.input,...a===null?{}:{package:a}},ambiguous:s!==null,precedence:"bundled_alias_before_installed_npm",candidates:[...i===null?[]:[{kind:"builtin",input:i,...a===null?{}:{package:a},command:`pm install ${i}`}],...s===null?[]:[{kind:"npm",input:`npm:${s.package}`,package:s.package,...s.version===void 0?{}:{version:s.version},directory:s.directory,command:`pm install npm:${s.package}`}]]}}}import Yt from"node:fs/promises";import OS from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="776854e4-6df4-507e-b21b-a4d320946642")}catch{}})();var gs=async e=>Yt.readFile(e).catch(t=>{if(Qi(t,"ENOENT"))return null;throw t}),Tf=async(e,t,n,r,i)=>jt("extension_install_backup",async()=>{let a=fr(e),o=Lt(t),[s,c]=await Promise.all([gs(a),gs(o)]);return r&&await Yt.cp(n,i,{recursive:!0,force:!0}),{backupDirectory:i,destinationDirectory:n,destinationExists:r,managedStatePath:a,managedStateContents:s,settingsPath:o,settingsContents:c}}),$f=async e=>jt("extension_install_rollback",async()=>{await Yt.rm(e.destinationDirectory,{recursive:!0,force:!0}),e.destinationExists&&await Yt.cp(e.backupDirectory,e.destinationDirectory,{recursive:!0,force:!0});for(let[t,n]of[[e.managedStatePath,e.managedStateContents],[e.settingsPath,e.settingsContents]])n===null?await Yt.rm(t,{force:!0}):(await Yt.mkdir(OS.dirname(t),{recursive:!0}),await Yt.writeFile(t,n))});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f34e0f7f-952c-5673-82b2-6bf87c10c7be")}catch{}})();var DS=4,Nf=[["install","install","--install"],["uninstall","uninstall","--uninstall"],["explore","explore","--explore"],["list","explore","--explore"],["manage","manage","--manage"],["describe","describe","--describe"],["reload","reload","--reload"],["doctor","doctor","--doctor"],["catalog","catalog","--catalog"],["init","init","--init"],["scaffold","init","--scaffold"],["adopt","adopt","--adopt"],["adopt-all","adopt-all","--adopt-all"],["activate","activate","--activate"],["deactivate","deactivate","--deactivate"],["migrate","migrate","--migrate"]],PS=Nf.map(([,,e])=>e).filter((e,t,n)=>n.indexOf(e)===t).join(", "),NS={install:"--install",uninstall:"--uninstall",explore:"--explore",manage:"--manage",describe:"--describe",reload:"--reload",doctor:"--doctor",catalog:"--catalog",adopt:"--adopt","adopt-all":"--adopt-all",activate:"--activate",deactivate:"--deactivate",migrate:"--migrate",init:"--init"},LS="__pm_native_output",MS=["trusted_extensions","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],Lf=["allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"],jS=["disabled","require_trusted","require_provenance"],Mf={mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]},FS=e=>{let t=e??Mf,n={};for(let r of MS)n[r]=Oe(t[r]??[]);return n},US=(e,t)=>{for(let n of Lf)t[n].length>0&&(e[n]=t[n]);return e},HS=(e,t)=>{for(let n of jS)t[n]===!0&&(e[n]=!0);return t.sandbox_profile&&(e.sandbox_profile=t.sandbox_profile),e},zS=e=>{let t={};for(let n of Lf)t[n]=Oe(e[n]??[]);return t},WS=e=>{let t=typeof e.name=="string"?e.name.trim():"";return t.length===0?null:US(HS({name:t},e),zS(e))},GS=e=>(e??[]).map(t=>WS(t)).filter(t=>t!==null).sort((t,n)=>t.name.localeCompare(n.name)),qS=e=>{let t=Object.assign({},Mf,e??{}),n=FS(e),r=GS(t.extension_overrides);return{mode:t.mode,trust_mode:t.trust_mode,require_provenance:t.require_provenance===!0,trusted_extensions:n.trusted_extensions,default_sandbox_profile:t.default_sandbox_profile,allowed_extensions:n.allowed_extensions,blocked_extensions:n.blocked_extensions,allowed_capabilities:n.allowed_capabilities,blocked_capabilities:n.blocked_capabilities,allowed_surfaces:n.allowed_surfaces,blocked_surfaces:n.blocked_surfaces,allowed_commands:n.allowed_commands,blocked_commands:n.blocked_commands,allowed_actions:n.allowed_actions,blocked_actions:n.blocked_actions,allowed_services:n.allowed_services,blocked_services:n.blocked_services,extension_overrides:r}},jf=async(e,t)=>{let n=[t],r=await Sp(t);r&&n.push(r);let i=[...new Set(n.map(a=>A(a)).filter(a=>a.length>0))];for(let a of i){let o=e.find(c=>A(c.name)===a);if(o)return o;let s=e.find(c=>A(c.directory)===a);if(s)return s}},Ff=(e,t)=>{let n=t.trim(),r=new Set(Oe(e.extensions.enabled));return new Set(Oe(e.extensions.disabled)).has(n)?!1:r.size===0?!0:r.has(n)},Uf=(e,t)=>{let n=t.trim(),r=new Set(Oe(e.extensions.enabled)),i=new Set(Oe(e.extensions.disabled)),a=[...r],o=[...i];return i.delete(n),r.size>0&&r.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},BS=(e,t)=>{let n=t.trim(),r=new Set(Oe(e.extensions.enabled)),i=new Set(Oe(e.extensions.disabled)),a=[...r],o=[...i];return r.delete(n),i.add(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},VS=(e,t)=>{let n=t.trim(),r=new Set(Oe(e.extensions.enabled)),i=new Set(Oe(e.extensions.disabled)),a=[...r],o=[...i];return r.delete(n),i.delete(n),e.extensions.enabled=[...r].sort((s,c)=>s.localeCompare(c)),e.extensions.disabled=[...i].sort((s,c)=>s.localeCompare(c)),e.extensions.enabled.join("\0")!==a.join("\0")||e.extensions.disabled.join("\0")!==o.join("\0")},JS=e=>{let t=e.trim().toLowerCase(),n=Math.min(2,Math.max(1,Math.ceil(t.length/4))),r=Nf.map(([i,a,o])=>({action:a,flag:o,distance:jc(t,i,n)})).filter(i=>i.distance!==null).sort((i,a)=>i.distance-a.distance)[0];return r?{action:r.action,flag:r.flag}:null},KS=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=JS(e);if(!r)return new y(`One action flag is required. Use one of: ${PS}. Bare \`pm package\` and \`pm extension\` default to --explore.`,g.USAGE);let i=`pm ${n} ${r.flag}`;return ui({command_path:n,display_name:`${n} lifecycle`,token_kind:"action",token:e,allowed:Object.keys(Hf),retry_command:i,message_suffix:`. Did you mean "${r.flag}"?`,fallback_candidates:[{source:"lifecycle_action",command:i,reason:`nearest lifecycle action for "${e}"`}]})},YS=[["install","install"],["uninstall","uninstall"],["explore","explore"],["manage","manage"],["describe","describe"],["reload","reload"],["doctor","doctor"],["catalog","catalog"],["init","init"],["scaffold","init"],["adopt","adopt"],["adoptAll","adopt-all"],["activate","activate"],["deactivate","deactivate"],["migrate","migrate"]],Hf={doctor:"doctor",reload:"reload",catalog:"catalog",init:"init",scaffold:"init",explore:"explore",manage:"manage",migrate:"migrate",list:"explore","":"explore"},XS=e=>Hf[e]??null,ZS=(e,t)=>{let n=[...new Set(YS.filter(([r])=>t[r]===!0).map(([,r])=>r))];if(n.length===0){if(e===void 0)return"explore";let r=XS(e.trim().toLowerCase());if(r)return r;throw KS(e,t)}if(n.length>1)throw new y("Extension action flags are mutually exclusive.",g.USAGE);return n[0]},QS=e=>{let t=e.project===!0||e.local===!0,n=e.global===!0;if(t&&n)throw new y('Options "--project/--local" and "--global" are mutually exclusive.',g.USAGE);return n?"global":"project"},eE=[e=>e?null:{status:"skipped_unmanaged",reason:"extension_not_managed"},e=>e&&e.source.kind!=="github"?{status:"skipped_non_github",reason:`managed_source_kind_${e.source.kind}`}:null,e=>{let t=typeof e?.update_error=="string"?e.update_error.trim():"";return t.length>0?{status:"failed",reason:t}:null},e=>{let t=e;return(typeof t.last_update_check_at=="string"?t.last_update_check_at.trim():"").length===0?null:{status:"checked",reason:{true:"update_available",false:"up_to_date"}[String(t.update_available)]??"checked_without_commit_baseline"}}],zf=e=>{for(let t of eE){let n=t(e);if(n)return n}return{status:"not_checked",reason:"no_update_check_recorded"}},Wf=(e,t,n,r)=>{let i=n??{};return{name:e.name,directory:e.directory,version:e.version,entry:e.entry,scope:t,active:e.enabled,enabled:e.enabled,runtime_active:null,activation_status:"unknown",contributions:i.contributions,managed:!!n,source:i.source,update_available:i.update_available,last_update_check_at:i.last_update_check_at,last_update_remote_commit:i.last_update_remote_commit,update_error:i.update_error,update_check_status:r.status,update_check_reason:r.reason}},tE=(e,t,n,r)=>{let i=Object.assign({name:e,manifest_version:"unknown",manifest_entry:"unknown"},r),a=r?Ff(n,r.name):!1;return{warning:`extension_manifest_missing:${t}:${e}`,summary:Wf({name:i.name,directory:e,version:i.manifest_version,entry:i.manifest_entry,enabled:a},t,r,zf(r))}},nE=async(e,t,n,r,i,a)=>{let o=Pe.join(e,t),s=Pe.join(o,"manifest.json"),c=a.get(A(t));if(!await O(s))return tE(t,n,r,c);let l=Symbol("invalid-extension-manifest-json"),d=await Ot.readFile(s,"utf8").then(f=>JSON.parse(f)).catch(()=>l);if(d===l)return{warning:`extension_manifest_invalid_json:${n}:${t}`};let u=es(d);if(!u)return{warning:`extension_manifest_invalid:${n}:${t}`};let m=i.get(A(u.name))??a.get(A(t));return{summary:Wf({name:u.name,directory:t,version:u.version,entry:u.entry,enabled:Ff(r,u.name)},n,m,zf(m))}},nt=async(e,t,n,r)=>{if(!await O(e))return{extensions:[],warnings:[]};let i=(await Ot.readdir(e,{withFileTypes:!0})).filter(l=>l.isDirectory()).map(l=>l.name).sort((l,d)=>l.localeCompare(d)),a=new Map(r.entries.map(l=>[A(l.name),l])),o=new Map(r.entries.map(l=>[A(l.directory),l])),s=[],c=[];for(let l of i){let d=await nE(e,l,t,n,a,o);d.warning&&s.push(d.warning),d.summary&&c.push(d.summary)}return{extensions:c.sort((l,d)=>l.name.localeCompare(d.name)),warnings:s.sort((l,d)=>l.localeCompare(d))}},rE=Rl(),iE=(e,t)=>[t.package,t.kind==="builtin"?t.name:void 0].find(n=>n?.trim())?.trim()??e,aE=(e,t,n,r)=>{let i=n.command_paths.map(s=>`pm ${s} --help`),a=r?.error.toLowerCase().includes("@unbrained/pm-cli")===!0,o=n.command_paths.length>0?[...i]:["Run pm package doctor --project --detail deep if expected package commands are missing."];return a&&o.unshift("Install @unbrained/pm-cli in the target workspace so declarative package runtime imports resolve, then reinstall the package."),{package_name:iE(e,t),extension_name:e,command_paths:n.command_paths,action_paths:n.action_paths,help_commands:i,next_steps:o,...a?{sdk_dependency_status:"missing"}:{}}},oE=e=>{let t=e.trace,n={layer:e.layer,name:e.name,entry_path:e.entry_path,error:e.error};return t&&(n.trace=Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0)),t.missing_capability&&(n.missing_capability=t.missing_capability),t.hint&&(n.hint=t.hint)),n},Gf=e=>e.map(t=>oE(t)).sort((t,n)=>`${t.layer}:${t.name}`.localeCompare(`${n.layer}:${n.name}`)),qf=(e,t,n)=>{let r=A(e);return t.find(i=>(n===void 0||i.layer===n)&&A(i.name)===r)},sE=(e,t,n,r)=>n.find(i=>i.scope===t&&A(i.name)===A(e))?.activation_status??(r?"failed":"unknown"),Bf=(e,t,n,r,i)=>rE.enqueue(async()=>{let a=process.env.PM_CLI_PACKAGE_ROOT,o=await Ot.mkdtemp(Pe.join(t,".pm-module-graph-"));process.env.PM_CLI_PACKAGE_ROOT=Ne(import.meta.url,["../.."]);try{let s=await Je({pmRoot:e,settings:n,cwd:process.cwd(),noExtensions:i.noExtensions===!0,reload_token:ja(),cache_bust:!0,module_graph_snapshot_root:o}),c=await Ke({...s}),l=[...s.failed.map(u=>({layer:u.layer,name:u.name,entry_path:u.entry_path,error:u.error})),...Gf(c.failed)],d=Object.fromEntries(s.loaded.map(u=>[A(u.name),nl(Sn(c,{extensionName:u.name}))]));return{installed:Xi(r,s,c),warnings:[...s.warnings,...c.warnings],activation_failures:l,extensions_disabled:s.disabled_by_flag,item_type_registrations:c.registrations.item_types,contribution_inventories:d}}finally{await Ot.rm(o,{recursive:!0,force:!0}),a===void 0?delete process.env.PM_CLI_PACKAGE_ROOT:process.env.PM_CLI_PACKAGE_ROOT=a}}),ws=async(e,t,n,r)=>{let i=n.filter(c=>!c.managed),a=[...i].sort((c,l)=>{let d=c.name.localeCompare(l.name);return d!==0?d:c.directory.localeCompare(l.directory)}),o=r,s=[];for(let c of a){let l=Pe.join(e,c.directory),d=await $n(l),u=$(),m={kind:"local",input:c.name,location:l};o=_r(o,{name:d.manifest.name,directory:c.directory,scope:t,manifest_version:d.manifest.version,manifest_entry:d.manifest.entry,capabilities:[...d.manifest.capabilities],contributions:d.manifest.contributions,installed_at:u,updated_at:u,source:m}),s.push({name:d.manifest.name,directory:c.directory,version:d.manifest.version,entry:d.manifest.entry,source:m})}return s.length>0&&await Jt(e,o),{state:o,adopted_entries:s,unmanaged_candidates:a,already_managed_count:n.length-i.length}},cE=(e,t)=>{let n=L(process.cwd(),t.path),r=nn(n,process.cwd()),i=e==="global"?Wr(process.cwd()):n,a=e==="global"?r.global:r.project;return{pm_root:n,scope:e,settings_root:i,selected_root:a,roots:r}},na=e=>{let t=[e.gh,e.github].filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean),n=[...new Set(t)];if(n.length>1)throw new y('Options "--gh" and "--github" must match when both are provided.',g.USAGE);return n[0]},lE=e=>NS[e],dE=(e,t)=>{let n=t.vocabulary==="package"?"package":"extension",r=e==="install"?"source":"name",i=`${n} ${r}`,a=lE(e),o=`<${r}>`,s=`pm ${n} ${a} ${o}`;throw new y(`Action "${e}" requires ${i} input.`,g.USAGE,{code:"missing_lifecycle_target",required:`Provide a ${r} target for ${e}.`,examples:[`pm ${n} ${e} ${o}`,s,`pm ${n} --help`],recovery:{attempted_command:`pm ${n} ${e}`,suggested_retry:s,fallback_candidates:[{source:"lifecycle_action",command:s,reason:`flag-form ${e} command with required ${r} target`}]}})},ra=(e,t,n={})=>{let r=e?.trim();if(r)return r;if(t==="init")throw new y('Action "init" requires a scaffold target path (for example: pm package init ./my-package or pm extension init ./my-extension).',g.USAGE);return dE(t,n)},uE=(e,t)=>{let n=new Set([...t.registrations.item_types.map(r=>({entry:r,count:r.types.length})),...t.registrations.item_fields.map(r=>({entry:r,count:r.fields.length}))].filter(({count:r})=>r>0).map(({entry:r})=>`${r.layer}:${A(r.name)}`));return e.loaded.filter(r=>(r.activation?.commands??[]).length>0).filter(r=>n.has(`${r.layer}:${A(r.name)}`)).map(r=>`extension_schema_narrow_activation:${r.layer}:${r.name}`).filter((r,i,a)=>a.indexOf(r)===i).sort((r,i)=>r.localeCompare(i))},mE=(e,t)=>{let n=[{triggered:t.strictExit===!0||t.failOnWarn===!0,allowed:e==="doctor",message:"--strict-exit and --fail-on-warn are only valid with --doctor."},{triggered:t.trace===!0,allowed:e==="doctor",message:"--trace is only valid with --doctor."},{triggered:t.watch===!0,allowed:e==="reload",message:"--watch is only valid with --reload."},{triggered:t.runtimeProbe===!0,allowed:e==="manage",message:"--runtime-probe is only valid with --manage."},{triggered:t.fixManagedState===!0,allowed:e==="manage"||e==="doctor",message:"--fix-managed-state is only valid with --manage or --doctor."},{triggered:t.isolated===!0||t.ignoreGlobal===!0,allowed:e==="doctor",message:"--isolated and --ignore-global are only valid with --doctor."},{triggered:t.capability!==void 0,allowed:e==="init",message:"--capability is only valid with --init/--scaffold."},{triggered:t.declarative===!0,allowed:e==="init",message:"--declarative is only valid with --init/--scaffold."},{triggered:t.dryRun===!0,allowed:e==="migrate"||e==="install",message:"--dry-run is only valid with --migrate or --install."}].find(r=>r.triggered&&!r.allowed);if(n)throw new y(n.message,g.USAGE)},pE=(e,t,n)=>{let r=String(e??"").trim().toLowerCase(),i=[n.init,n.scaffold].includes(!0);return({doctor:["doctor"],reload:["reload"],catalog:["catalog"],init:i?[]:["init","scaffold"]}[t]??[]).includes(r)?void 0:e},fE=e=>[e.action==="catalog",typeof e.options.fields=="string",String(e.options.fields).trim().length>0].every(Boolean)?{project:"project",global:"global",selected:e.scope,settings_root:"project"}:{project:e.resolvedRoots.roots.project,global:e.resolvedRoots.roots.global,selected:e.resolvedRoots.selected_root,settings_root:e.resolvedRoots.settings_root},hE=(e,t,n)=>{let r={ok:n,action:e.action,scope:e.scope,roots:fE(e),warnings:[...new Set(e.warnings)].sort((i,a)=>i.localeCompare(a)),details:t};return e.action==="doctor"&&Object.defineProperty(r,LS,{value:!0,enumerable:!1,configurable:!1}),r},vs=async(e,t,n)=>{let r=ZS(e,t);mE(r,t);let i=pE(e,r,t),a=QS(t),o=cE(a,n),s={action:r,normalizedTarget:i,scope:a,resolvedRoots:o,warnings:[],options:t,global:n},c={...s,withResult:(l,d=!0)=>hE(s,l,d)};return await JE(c)},_E=(e,t)=>{let n=t.vocabulary??"extension",r=e.target_path.replace(/\\/g,"/"),i=Dl(r),a={package:`Install dependencies: cd ${i}, then run "npm install"`,extension:`Install type-check dependencies: cd ${i}, then run "npm install -D typescript @types/node @unbrained/pm-cli"`},o={package:`Validate the package: cd ${i}, then run "npm run typecheck" and "npm test"`,extension:`Type-check the source (optional): cd ${i}, then run "npx tsc --noEmit"`},s=[];return[n==="package",t.declarative===!0].every(Boolean)&&s.push("Ensure the target workspace can resolve @unbrained/pm-cli before installing this declarative package."),[a[n],...s,`Install the scaffold: ${Xe(n==="package"?["install","--project",r]:["extension","--install","--project",r])}`,`Smoke-test command path: pm ${e.command_name}`,o[n],`Run diagnostics: ${n==="package"?"pm package doctor":"pm extension --doctor"} --project --detail summary`]},gE=async e=>{let{action:t,normalizedTarget:n,options:r,withResult:i}=e;if([na(r),r.ref].filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean).length>0)throw new y('Action "init" does not accept --gh/--github/--ref options.',g.USAGE);let a=ra(n,t,r),o=await qp(a,r.vocabulary??"extension",r.capability,r.declarative===!0);return i({scaffolded:o.created_directory||o.files.some(s=>s.status==="created"),extension:{name:o.extension_name,command:o.command_name},capability:o.capability,style:o.style,target_path:o.target_path,created_directory:o.created_directory,files:o.files,next_steps:_E(o,r)})},yE=async e=>{let{normalizedTarget:t,resolvedRoots:n,warnings:r,options:i,global:a,withResult:o}=e;if(t!==void 0)throw new y('Action "reload" does not accept a target argument.',g.USAGE);let s=await C(n.settings_root),c=ja(),l=await Je({pmRoot:n.settings_root,settings:s,cwd:process.cwd(),noExtensions:a.noExtensions,reload_token:c,cache_bust:!0});r.push(...l.warnings);let d=await Ke(l);r.push(...d.warnings);let u={reload:{token:c,cache_bust:!0,watch:i.watch===!0},loaded_count:l.loaded.length,failed_count:l.failed.length,activated_count:Math.max(0,l.loaded.length-d.failed.length),activation_failed_count:d.failed.length,loaded_extensions:l.loaded.map(m=>({name:m.name,layer:m.layer,version:m.version})),failed_extensions:l.failed.map(m=>({name:m.name,layer:m.layer,error:m.error})),activation_failures:d.failed.map(m=>({name:m.name,layer:m.layer,error:m.error}))};return i.watch===!0&&r.push("extension_reload_watch_hint:watch_mode_requested_non_interactive_single_pass_only"),o(u)},wE=async e=>{let{normalizedTarget:t,scope:n,options:r,global:i,withResult:a}=e;if(typeof t=="string"&&t.length>0&&t!=="catalog")throw new y('Action "catalog" does not accept a package target.',g.USAGE);return a(await Ep(n,i,r))},vE=(e,t)=>({kind:"builtin",input:e,location:e,name:e,...t===null?{}:{package:t}}),bE=e=>({kind:"local",input:e.input,location:e.absolute_path}),kE=(e,t)=>({kind:"npm",input:e.input,location:t.resolved_subpath??".",package:t.npm_package,version:t.npm_version}),SE=(e,t)=>({kind:"github",input:e.input,location:t.resolved_subpath??e.subpath??".",repository:e.repository,owner:e.owner,repo:e.repo,ref:e.ref,subpath:t.resolved_subpath??e.subpath,commit:t.commit}),EE=(e,t,n,r)=>e?vE(e,t):n.kind==="local"?bE(n):n.kind==="npm"?kE(n,r):SE(n,r),xE=(e,t,n,r)=>e?e.manifest_version!==t?{installed_at:e.installed_at,updated_at:r}:gp(e.source,n)?{installed_at:e.installed_at,updated_at:e.updated_at}:{installed_at:e.installed_at,updated_at:r}:{installed_at:r,updated_at:r},IE=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i}=e,{validated:a,destinationDirectoryName:o}=t,s=await C(r.settings_root),c=await be(r.selected_root);i.push(...c.warnings);let l=Pe.join(r.selected_root,o),d=await O(l),u=await Ki(a.directory,l);await Ot.mkdir(r.selected_root,{recursive:!0});let m=await Ot.mkdtemp(Pe.join(r.selected_root,".pm-extension-install-backup-")),f=Pe.join(m,"destination");try{let p=await Tf(r.selected_root,r.settings_root,l,d,f),h=EE(t.bundledAliasName,t.bundledPackageName,t.installSource,t.resolvedSource),_=c.state.entries.find(k=>A(k.name)===A(a.manifest.name)),w=xE(_,a.manifest.version,h,$()),v=_r(c.state,{name:a.manifest.name,directory:o,scope:n,manifest_version:a.manifest.version,manifest_entry:a.manifest.entry,capabilities:[...a.manifest.capabilities],contributions:a.manifest.contributions,...w,source:h}),S=Uf(s,a.manifest.name);try{u||await hf(a.directory,l),await mf(l),await pf(l),await Jt(r.selected_root,v),S&&await di(r.settings_root,s,"settings:write")}catch(k){try{await $f(p)}catch(x){throw new AggregateError([k,x],`Extension install failed: ${String(k)}; rollback failed: ${String(x)}`,{cause:x})}throw k}return{settings:s,managedState:v,sourceRecord:h,destinationDirectory:l,destinationExists:d,installInPlace:u,activationChanged:S}}finally{await Ot.rm(m,{recursive:!0,force:!0}).catch(()=>{})}},AE=async(e,t,n)=>{let r=n.filter(i=>A(i.name)===A(t)).flatMap(i=>i.types.map(a=>({name:a.name,folder:a.folder})));return e.scope==="project"&&r.length>0&&await mr(e.resolvedRoots.pm_root,r,e.warnings,"install:type-folder"),r},RE=(e,t,n,r,i)=>{let a=qf(t,n.activation_failures,e.scope),o=sE(t,e.scope,n.installed,a),s=[!n.extensions_disabled,o==="ok"].every(Boolean);s||e.warnings.push(`extension_install_activation_failed:${e.scope}:${t}:${o}`);let c={true:{status:"ok",blocking_failure_count:0},false:{status:"degraded",blocking_failure_count:1}};return{activated:s,status:o,failure:a,verification:{status:c[String(s)].status,target_pm_root:e.resolvedRoots.pm_root,activation_status:o,activated:s,registered_commands:r.command_paths,registered_actions:r.action_paths,registered_item_types:i,module_graph_verification:"fresh_in_topology_snapshot",health:c[String(s)]}}},CE=async(e,t)=>{let{scope:n,resolvedRoots:r,warnings:i,global:a,withResult:o}=e,{validated:s,destinationDirectoryName:c}=t,l=await IE(e,t),d=await nt(r.selected_root,n,l.settings,l.managedState);i.push(...d.warnings);let u=await Bf(r.pm_root,Pe.dirname(r.selected_root),l.settings,d.extensions,a);i.push(...u.warnings);let m=await AE(e,s.manifest.name,u.item_type_registrations),f=yf(s.manifest.name,u.installed),p=RE(e,s.manifest.name,u,f,m),h=u.contribution_inventories[A(s.manifest.name)];return h&&(l.managedState=await yp(r.selected_root,l.managedState,s.manifest.name,h)),o({extension:{name:s.manifest.name,version:s.manifest.version,entry:s.manifest.entry,capabilities:s.manifest.capabilities,directory:c},source:l.sourceRecord,source_resolution:t.sourceResolution,...t.installPlan?{install_plan:t.installPlan}:{},destination_path:l.destinationDirectory,overwritten:[l.destinationExists,!l.installInPlace].every(Boolean),installed_in_place:l.installInPlace,activated:p.activated,settings_changed:l.activationChanged,runtime_activation_status:p.status,command_paths:f.command_paths,action_paths:f.action_paths,contributions:h,command_discovery:aE(s.manifest.name,l.sourceRecord,f,p.failure),verification:p.verification,activation_diagnostics:{failed_count:u.activation_failures.length,failed:u.activation_failures,installed_extension_failed:p.failure??null}},p.activated)},TE=async e=>{let{options:t,global:n,warnings:r,withResult:i}=e;if(typeof t.ref=="string"&&t.ref.trim().length>0)throw new y('Action "install all" does not accept --ref.',g.USAGE);let a=[],o=new Map;for(let s of await Gi()){let c=await gr(s),l=Pe.resolve(c),d=o.get(l);d===void 0&&(d=await vs(s,{...t,install:!0},n),o.set(l,d)),a.push({alias:s,result:d})}return r.push(...a.flatMap(s=>s.result.warnings)),i(xf(a,t.dryRun===!0),a.every(s=>s.result.ok))},$E=async(e,t,n)=>{let{resolvedRoots:r}=e,{bundledAliasName:i,bundledPackageName:a,installSource:o,sourceResolution:s}=await Cf(t,n,e.options.ref);if(s.ambiguous){let l=s.candidates.find(d=>d.kind==="npm");e.warnings.push(`extension_install_source_ambiguous:${t}:builtin:${i}:npm:${l.package}`)}let c=await Dp(o);try{let l=await $n(c.directory,{source_kind:o.kind,source_input:o.input,source_root:c.source_root}),d=zi(l.manifest.name),u=e.options.dryRun===!0||o.kind==="local"&&i===null?await If(c,Pe.join(r.selected_root,d),e.scope,e.options.copyPlan):void 0;return e.options.dryRun===!0?e.withResult({dry_run:!0,installed:!1,activated:!1,extension:{name:l.manifest.name,version:l.manifest.version},source_resolution:s,install_plan:u}):await ps(r.settings_root,d,()=>CE(e,{validated:l,destinationDirectoryName:d,bundledAliasName:i,bundledPackageName:a,sourceResolution:s,installSource:o,resolvedSource:c,installPlan:u}))}finally{c.cleanup&&await c.cleanup()}},OE=async e=>{let t=na(e.options),n=t??ra(e.normalizedTarget,e.action,e.options);return[t===void 0,vp(n)].every(Boolean)?TE(e):$E(e,n,t)},DE=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,withResult:o}=e;if(t!==void 0)throw new y('Action "adopt-all" does not accept a target argument.',g.USAGE);if(na(a)!==void 0||typeof a.ref=="string"&&a.ref.trim().length>0)throw new y('Action "adopt-all" does not accept --gh/--github/--ref options.',g.USAGE);let s=await C(r.settings_root),c=await be(r.selected_root);i.push(...c.warnings);let l=await nt(r.selected_root,n,s,c.state);i.push(...l.warnings);let d=await ws(r.selected_root,n,l.extensions,c.state),u=await nt(r.selected_root,n,s,d.state);i.push(...u.warnings);let m=Zi(n,i,u.extensions,a);i.push(...m.warnings);let f=new Map(u.extensions.map(_=>[`${A(_.name)}:${A(_.directory)}`,_])),p=new Map(u.extensions.map(_=>[A(_.directory),_])),h=d.adopted_entries.map(_=>{let w=A(_.directory),v=f.get(`${A(_.name)}:${w}`)??p.get(w);return{..._,...Vf(v)}});return o({adopted_all:h.length>0,adopted_count:h.length,already_managed_count:d.already_managed_count,extensions:h,triage:m,warning_codes:m.warning_codes,update_health_partial:m.update_health_partial,update_health_coverage:m.update_health_coverage})},Vf=e=>({update_check_status:e?.update_check_status??null,update_check_reason:e?.update_check_reason??null}),PE=(e,t,n,r)=>{if(e===void 0)return{kind:"local",input:t,location:n};let i=Vi(e,{forceGithub:!0,ref:r});if(i.kind!=="github")throw new y(`Invalid GitHub shorthand "${e}".`,g.USAGE);return{kind:"github",input:i.input,location:i.subpath??".",repository:i.repository,owner:i.owner,repo:i.repo,ref:i.ref,subpath:i.subpath}},NE=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:a,options:o,withResult:s}=e,c=ra(n,t,o),l=na(o),d=await C(i.settings_root),u=await be(i.selected_root);a.push(...u.warnings);let m=await nt(i.selected_root,r,d,u.state);a.push(...m.warnings);let f=await jf(m.extensions,c);if(!f)throw new y(`Installed extension "${c}" was not found in ${r} scope.`,g.NOT_FOUND);if(f.managed)return s({adopted:!1,already_managed:!0,extension:{name:f.name,directory:f.directory}});let p=Pe.join(i.selected_root,f.directory),h=await $n(p),_=$(),w=PE(l,c,p,o.ref),v=_r(u.state,{name:h.manifest.name,directory:f.directory,scope:r,manifest_version:h.manifest.version,manifest_entry:h.manifest.entry,capabilities:[...h.manifest.capabilities],contributions:h.manifest.contributions,installed_at:_,updated_at:_,source:w});await Jt(i.selected_root,v);let S=await nt(i.selected_root,r,d,v);a.push(...S.warnings);let k=S.extensions.find(x=>A(x.name)===A(h.manifest.name))??S.extensions.find(x=>A(x.directory)===A(f.directory));return s({adopted:!0,extension:{name:h.manifest.name,directory:f.directory,version:h.manifest.version,entry:h.manifest.entry},source:w,...Vf(k)})},Jf=async e=>{let{action:t,normalizedTarget:n,scope:r,resolvedRoots:i,warnings:a,options:o}=e,s=ra(n,t,o),c=await C(i.settings_root),l=await be(i.selected_root);a.push(...l.warnings);let d=await nt(i.selected_root,r,c,l.state);a.push(...d.warnings);let u=await jf(d.extensions,s);if(!u)throw new y(`Installed extension "${s}" was not found in ${r} scope.`,g.NOT_FOUND);return{settings:c,managedStateRead:l,candidate:u}},LE=async e=>{let{resolvedRoots:t,withResult:n}=e,{settings:r,managedStateRead:i,candidate:a}=await Jf(e),o=Pe.join(t.selected_root,a.directory);await Ot.rm(o,{recursive:!0,force:!0});let s={...i.state,updated_at:$(),entries:i.state.entries.filter(l=>A(l.name)!==A(a.name)&&A(l.directory)!==A(a.directory))};await Jt(t.selected_root,s);let c=VS(r,a.name);return c&&await di(t.settings_root,r,"settings:write"),n({removed:!0,extension:{name:a.name,directory:a.directory},destination_path:o,settings_changed:c})},Of=async e=>{let{action:t,resolvedRoots:n,warnings:r,global:i,withResult:a}=e,{settings:o,candidate:s}=await Jf(e),c=t==="activate"?Uf(o,s.name):BS(o,s.name);c&&await di(n.settings_root,o,"settings:write");let l=t==="activate"?await Bf(n.pm_root,Pe.dirname(n.selected_root),o,[s],i).then(d=>(r.push(...d.warnings),qf(s.name,d.activation_failures,e.scope))):void 0;return l&&r.push(`extension_activate_failed:${e.scope}:${s.name}`),a({extension:{name:s.name,directory:s.directory},active:t==="activate"&&l===void 0,runtime_active:t==="activate"&&l===void 0,activation_failure:l??null,settings_changed:c,settings:{enabled:[...o.extensions.enabled],disabled:[...o.extensions.disabled]}},l===void 0)},ME=(e,t,n,r,i,a)=>{let o=r==="package"?"package":"extension",s={package:"doctor",extension:"--doctor"}[o],c=i?.adopted_entries.length??0,l=[[a!==null,a??""],[t>0,`Run pm ${o} explore --project and pm ${o} explore --global to inspect load failures.`],[n>0,`Review activation failures in pm ${o} ${s} --detail deep output.`],[c>0,`Managed-state fix adopted ${c} extension(s).`]];return[...new Set([...e,...l.filter(([d])=>d).map(([,d])=>d)].map(d=>d.trim()).filter(d=>d.length>0))]},ys=e=>e.loaded.some(t=>t.layer==="global")||e.failed.some(t=>t.layer==="global")||e.warnings.some(t=>t.includes(":global:")),jE=(e,t,n,r)=>{if(e!=="project"||t||!ys(r))return null;let i=n==="package"?"package":"extension";return`Global ${i} registrations are included in project diagnostics. For hermetic ${i} smoke tests, rerun pm ${i} doctor --project --isolated --detail deep --trace, or set PM_GLOBAL_PATH to a temporary directory for the whole test process.`},FE=(e,t,n)=>{if(String(e??"").trim().length>0)throw new y('Action "doctor" does not accept a target argument.',g.USAGE);let r=[n.isolated,n.ignoreGlobal].includes(!0);if([r,t==="global"].every(Boolean))throw new y("--isolated and --ignore-global are only valid with project-scope doctor diagnostics.",g.USAGE);let i=nf(n.detail),a=n.trace===!0;if([a,i!=="deep"].every(Boolean))throw new y("--trace requires --detail deep with --doctor.",g.USAGE);return{isolated:r,detailMode:i,includeTrace:a}},UE=async(e,t,n)=>{if(e.options.fixManagedState!==!0)return{state:n,fix:null};let r=await ws(e.resolvedRoots.selected_root,e.scope,t,n);return{state:r.state,fix:r}},HE=(e,t,n,r)=>{let i=n==="package"?"package":"extension";if(e!=="project")return{isolated:t,global_extensions_included:!1,global_diagnostics_present:ys(r),rerun_command:null,pm_global_path_recipe:null};let a=`pm ${i} doctor --project --isolated --detail deep --trace`;return{isolated:t,global_extensions_included:!t,global_diagnostics_present:ys(r),rerun_command:t?null:a,pm_global_path_recipe:`PM_GLOBAL_PATH=$(mktemp -d) pm ${i} doctor --project --detail deep --trace`}},zE=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,global:o,withResult:s}=e,{isolated:c,detailMode:l,includeTrace:d}=FE(t,n,a),u=await C(r.settings_root),m=await be(r.selected_root);i.push(...m.warnings);let f=await nt(r.selected_root,n,u,m.state);i.push(...f.warnings);let{state:p,fix:h}=await UE(e,f.extensions,m.state),_=await nt(r.selected_root,n,u,p);i.push(..._.warnings);let w=await Je({pmRoot:r.pm_root,settings:u,cwd:process.cwd(),noExtensions:o.noExtensions===!0,ignoreGlobalExtensions:c}),v=await Ke({...w,loaded:w.loaded}),S=await Rf(r.pm_root);i.push(...S.warnings,...w.warnings),i.push(...Qp(w.failed)),i.push(...v.warnings),i.push(...ef(v.failed)),i.push(...tf(w,v)),i.push(...wf(v,w)),i.push(...uE(w,v)),i.push(...vf(v));let k=Xi(_.extensions,w,v),x=af(n,k,w.loaded.map(z=>({layer:z.layer,name:z.name})),w.failed.map(z=>({name:z.name})),w.disabled_by_flag);i.push(...x.warnings);let D=k.filter(z=>z.update_check_status==="failed").map(z=>`extension_update_check_failed:${z.name}`);i.push(...D);let E=Zi(n,i,k,a);i.push(...E.warnings);let b=[...E.warnings],N={mode:w.policy.mode,trust_mode:w.policy.trust_mode,require_provenance:w.policy.require_provenance,default_sandbox_profile:w.policy.default_sandbox_profile,sandbox_enforcement:"advisory: sandbox_profile/permissions are declaration-based load gates, not runtime isolation (ADR pm-6ef3)",trusted_extensions_count:w.policy.trusted_extensions.length,allowed_extensions_count:w.policy.allowed_extensions.length,blocked_extensions_count:w.policy.blocked_extensions.length,allowed_capabilities_count:w.policy.allowed_capabilities.length,blocked_capabilities_count:w.policy.blocked_capabilities.length,allowed_surfaces_count:w.policy.allowed_surfaces.length,blocked_surfaces_count:w.policy.blocked_surfaces.length,allowed_commands_count:w.policy.allowed_commands.length,blocked_commands_count:w.policy.blocked_commands.length,allowed_actions_count:w.policy.allowed_actions.length,blocked_actions_count:w.policy.blocked_actions.length,allowed_services_count:w.policy.allowed_services.length,blocked_services_count:w.policy.blocked_services.length,extension_override_count:w.policy.extension_overrides.length},I=vr(b),R=br(),Q=E.warning_codes,xe=jE(n,c,a.vocabulary,w),ye=ME(E.remediation,w.failed.length,v.failed.length,a.vocabulary,h,xe),he=HE(n,c,a.vocabulary,w),He={status:E.status,scope:n,warning_count:E.warning_count,warning_codes:Q,total_extensions:k.length,managed_total:k.filter(z=>z.managed).length,enabled_total:k.filter(z=>z.enabled).length,active_total:k.filter(z=>z.active).length,unmanaged_loaded_extension_count:E.unmanaged_loaded_extension_count,unmanaged_action_required_extension_count:E.unmanaged_action_required_extension_count,unmanaged_expected_extension_count:E.unmanaged_expected_extension_count,runtime_active_total:k.filter(z=>z.runtime_active===!0).length,activation_status_totals:{ok:k.filter(z=>z.activation_status==="ok").length,failed:k.filter(z=>z.activation_status==="failed").length,not_loaded:k.filter(z=>z.activation_status==="not_loaded").length,unknown:k.filter(z=>z.activation_status==="unknown").length},unknown_capability_count:I.length,capability_contract_version:R.version,update_available_total:E.update_available_total,update_check_status_totals:E.update_check_status_totals,update_health_coverage:E.update_health_coverage,update_health_partial:E.update_health_partial,update_check_failed_total:k.filter(z=>z.update_check_status==="failed").length,load_failure_count:w.failed.length,activation_failure_count:v.failed.length,load_failures:ds(w.failed),activation_failures:ds(v.failed),blocking_failure_count:w.failed.length+v.failed.length,has_blocking_failures:w.failed.length+v.failed.length>0,consistency_warning_count:x.warnings.length,trace_enabled:d,isolation:he,policy:N,remediation:ye},Mr=h?{requested:!0,applied:h.adopted_entries.length>0,adopted_count:h.adopted_entries.length,already_managed_count:h.already_managed_count,adopted_extensions:h.adopted_entries.map(z=>z.name)}:{requested:!1,applied:!1,adopted_count:0,already_managed_count:_.extensions.filter(z=>z.managed).length,adopted_extensions:[]},Gn={mode:l,summary:He,triage:E,trace_enabled:d,capability_contract:R,capability_guidance:I,managed_state_fix:Mr,author_manifest:S,isolation:he,policy:w.policy};if(l==="deep"){let z=d?v.failed:v.failed.map(B=>{let{trace:jr,...Fr}=B;return Fr});Gn.deep={warnings:b,warning_codes:Q,capability_contract:R,capability_guidance:I,trace_enabled:d,managed_state:{path:m.path,count:p.entries.length,entries:p.entries},installed_extensions:k,load:{roots:w.roots,policy:w.policy,warnings:w.warnings,failed:w.failed,loaded:w.loaded.map(B=>({layer:B.layer,directory:B.directory,name:B.name,version:B.version,entry:B.entry,priority:B.priority}))},activation:{failed:z,warnings:v.warnings,hook_counts:v.hook_counts,registration_counts:v.registration_counts,parser_override_count:v.parser_override_count,preflight_override_count:v.preflight_override_count,service_override_count:v.service_override_count,renderer_override_count:v.renderer_override_count},consistency:x.summary},d&&(Gn.deep.trace={activation_failures:v.failed.filter(B=>B.trace!==void 0).map(B=>({layer:B.layer,name:B.name,entry_path:B.entry_path,error:B.error,method:B.trace.method,command:B.trace.command,capability:B.trace.capability,missing_capability:B.trace.missing_capability,registration_index:B.trace.registration_index,expected_schema:B.trace.expected_schema,hint:B.trace.hint,received:B.trace.received}))})}return s(Gn)},WE=async e=>{let{normalizedTarget:t,scope:n,resolvedRoots:r,warnings:i,options:a,global:o,withResult:s}=e,c=await C(r.settings_root),l=await Je({pmRoot:r.pm_root,settings:c,cwd:process.cwd(),noExtensions:o.noExtensions===!0}),d=await Ke(l);i.push(...l.warnings),i.push(...d.warnings);let u=Vp(t,l,d);if(t!==void 0&&u.extensions.length===0){let m=a.vocabulary==="package"?"package":"extension",f=[...new Set(l.loaded.map(h=>a.vocabulary==="package"&&typeof h.source_package=="string"&&h.source_package.trim().length>0?h.source_package.trim():h.name))].sort((h,_)=>h.localeCompare(_)),p=f.length>0?` Loaded ${m} names: ${f.join(", ")}.`:"";throw new y(`No loaded ${m} named "${t}" was found in ${n} scope.${p} Run pm ${m} explore to list discovered ${m}s.`,g.NOT_FOUND)}return s({target:u.target,total:u.total,extensions:u.extensions,union:u.union,command_ownership:u.command_ownership})},GE=async(e,t,n)=>{let r=n,i=null;if([e.action==="manage",e.options.fixManagedState===!0].every(Boolean)&&(i=await ws(e.resolvedRoots.selected_root,e.scope,t,n),r=i.state),e.action==="manage"){let a=await gf(r.entries,DS,async o=>{if(o.source.kind!=="github")return o;let s=await bf(o.source);return{...o,last_update_check_at:s.checked_at,last_update_remote_commit:s.remote_commit,update_available:s.available,update_error:s.error}});r={...r,updated_at:$(),entries:hr(a)},await Jt(e.resolvedRoots.selected_root,r)}return{state:r,fix:i}},qE=async(e,t,n)=>{let r=await Je({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),i=await Ke({...r,loaded:r.loaded});return e.warnings.push(...r.warnings,...i.warnings),{installed:Xi(n,r,i),failures:Gf(i.failed),summary:{requested:!0,executed:!0,reason:e.action==="explore"?"explore_defaults_to_runtime_probe":e.options.runtimeProbe===!0?"runtime_probe_requested":"manage_defaults_to_runtime_probe",load_failure_count:r.failed.length,activation_failure_count:i.failed.length,warning_count:[...new Set([...r.warnings,...i.warnings])].length,policy:r.policy}}},BE=(e,t)=>e?{requested:!0,applied:e.adopted_entries.length>0,adopted_count:e.adopted_entries.length,adopted_extensions:e.adopted_entries.map(n=>n.name),already_managed_count:e.already_managed_count}:{requested:!1,applied:!1,adopted_count:0,adopted_extensions:[],already_managed_count:t.filter(n=>n.managed).length},Df=async e=>{let{action:t,scope:n,resolvedRoots:r,warnings:i,options:a,withResult:o}=e,s=await C(r.settings_root),c=qS(s.extensions.policy),l=await be(r.selected_root);i.push(...l.warnings);let d=await nt(r.selected_root,n,s,l.state);i.push(...d.warnings);let{state:u,fix:m}=await GE(e,d.extensions,l.state),f=await nt(r.selected_root,n,s,u);if(i.push(...f.warnings),t==="manage"){let v=f.extensions.filter(S=>S.update_check_status==="failed").map(S=>`extension_update_check_failed:${S.name}`);i.push(...v)}let p=await qE(e,s,f.extensions),h=p.installed,_=Zi(n,i,h,a);i.push(..._.warnings);let w={total:h.length,managed_total:h.filter(v=>v.managed).length,enabled_total:h.filter(v=>v.enabled).length,active_total:h.filter(v=>v.active).length,extensions:h,triage:_,policy:c};return p.failures!==void 0&&(w.activation_diagnostics={failed_count:p.failures.length,failed:p.failures}),t==="explore"&&(w.runtime_probe=p.summary),t==="manage"&&(w.runtime_probe=p.summary,w.managed_state_fix=BE(m,h)),o(w)},Pf={init:gE,install:OE,uninstall:LE,explore:Df,manage:Df,describe:WE,reload:yE,doctor:zE,catalog:wE,adopt:NE,"adopt-all":DE,activate:Of,deactivate:Of,migrate:Ef},VE=e=>[e.action==="uninstall",e.action==="manage",e.action==="adopt",e.action==="adopt-all",e.action==="activate",e.action==="deactivate",e.action==="migrate",[e.action==="doctor",e.options.fixManagedState===!0].every(Boolean)].some(Boolean),JE=e=>VE(e)?ps(e.resolvedRoots.settings_root,`${e.action}-state`,()=>Pf[e.action](e)):Pf[e.action](e);import{execFile as KE}from"node:child_process";import{realpath as YE}from"node:fs/promises";import Kf from"node:path";import{promisify as XE}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9af87d55-dbe2-561b-9f3f-6f12c0416147")}catch{}})();var ZE=XE(KE),QE=32*1024*1024,e0=1e4,t0=["search/eval-queries.json"];function bs(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function n0(e){return`'${e.replaceAll("'","'\\''")}'`}async function r0(e,t=YE){return t(e).catch(()=>Kf.resolve(e))}async function ia(e){let t=await et(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await r0(e),r=bs(Kf.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=Po.map(a=>`${r}/${bs(a)}`);try{let{stdout:a}=await ZE("git",["ls-files","-z","--",...i.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:QE,windowsHide:!0,timeout:e0}),o=new Set(t0.map(l=>`${r}/${l}`)),s=[...new Set(a.split("\0").filter(l=>l.length>0&&!o.has(bs(l))))].sort((l,d)=>l.localeCompare(d)),c=i.filter(l=>s.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:s,tracked_path_count:s.length,remediation_command:s.length===0?null:`git rm --cached -r -- ${c.map(l=>n0(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2e510b32-f27f-5ba5-94b2-8268343359dc")}catch{}})();async function Yf(e,t,n,r){if(t===null)return{audit:null,count:0,warnings:[]};let i=await In(e,At(n));if(i.status==="ok")return{audit:i,count:0,warnings:[]};let a=Math.max(1,i.missing_patterns.length+i.stale_patterns.length);return{audit:i,count:a,warnings:r?[`merge_fence_${i.status==="not_installed"?"missing":"drift"}:${a}`]:[]}}function Xf(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),t}import{execFile as q0}from"node:child_process";import{randomUUID as B0}from"node:crypto";import{readdir as V0,stat as J0}from"node:fs/promises";import ge from"node:path";import{promisify as K0}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5134bd12-d808-588f-af5d-fc71e5153e95")}catch{}})();var i0=Object.freeze({pm_item_scalar_missing:!0});function On(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===1&&e.pm_item_scalar_missing===!0}function Y(e){return e===void 0?i0:e}function Dt(e){return Ie(T(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function ks(e,t){let n=Me(e);if(n)throw new y(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,a]of e.split(/\r?\n/).entries()){let o=a.trim();if(o)try{let s=JSON.parse(o);if(typeof s!="object"||s===null||Array.isArray(s))throw new TypeError("history entry must be an object");r.push(s)}catch{throw new y(`History merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}}return r}function ht(e){return T({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function a0(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&ht(e[r])===ht(t[r]);)r+=1;return r}function Jj(e,t,n){let r=ks(e,"base"),i=ks(t,"ours"),a=ks(n,"theirs"),o=[r,i,a].map(f=>f.filter(p=>p.op==="create"));if(o[0].length===0&&o.slice(1).every(f=>f.length>0)||o.some(f=>f.length>1)||new Set(o.flat().map(ht)).size>1)throw new y("Duplicate item identity: history contains independent or unproven create events. Preserve both branches and assign distinct item ids before merging.",g.CONFLICT,{code:"item_identity_conflict"});let s=a0(i,a);if(s===i.length&&s===a.length)return{merged:Ht(i),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:i.length,reanchored:!1};if(s===a.length)return{merged:Ht(i),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:i.length-s,entries_from_theirs:0,entries_total:i.length,reanchored:!1};if(s===i.length)return{merged:Ht(a),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:a.length-s,entries_total:a.length,reanchored:!1};let c=i.slice(s),l=new Set(c.map(ht)),d=a.slice(s).filter(f=>!l.has(ht(f))),u=[...c,...d].sort((f,p)=>{let h=Ft(f.ts,p.ts);if(h!==0)return h;let _=l.has(ht(f)),w=l.has(ht(p));return _!==w?Number(w)-Number(_):ht(f).localeCompare(ht(p))}),m=oi([...i.slice(0,s),...u],void 0,{continuousHashSurface:!0});if(m.skippedOps>0)throw new y(`History union cannot preserve ${m.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,g.GENERIC_FAILURE);return{merged:Ht(m.entries),strategy:"union_reanchor",common_entries:s,entries_from_ours:c.length,entries_from_theirs:d.length,entries_total:m.entries.length,reanchored:!0}}function Ss(e,t){let n=Me(e);if(n)throw new y(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,a]of e.split(/\r?\n/).entries()){let o=a.trim();if(!o)continue;let s;try{s=JSON.parse(o)}catch{throw new y(`Relationship merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}if(typeof s!="object"||s===null||Array.isArray(s)||typeof s.eventId!="string"||typeof s.sequence!="number")throw new y(`Relationship merge input (${t}) line ${i+1} is not a relationship event (eventId + sequence required).`,g.GENERIC_FAILURE);r.push(s)}return r}function aa(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
57
+ `)}
58
+ `}function o0(e){return e.map((t,n)=>({...t,sequence:n+1}))}function Kj(e,t,n){Ss(e,"base");let r=Ss(t,"ours"),i=Ss(n,"theirs"),a=Math.min(r.length,i.length),o=0;for(;o<a&&r[o].eventId===i[o].eventId;)o+=1;if(o===r.length&&o===i.length)return{merged:aa(r),strategy:"identical",common_entries:o,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===i.length)return{merged:aa(r),strategy:"fast_forward_ours",common_entries:o,entries_from_ours:r.length-o,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(o===r.length)return{merged:aa(i),strategy:"fast_forward_theirs",common_entries:o,entries_from_ours:0,entries_from_theirs:i.length-o,entries_total:i.length,reanchored:!1};let s=r.slice(o),c=new Set(s.map(m=>m.eventId)),l=i.slice(o).filter(m=>!c.has(m.eventId)),d=[...s,...l].sort((m,f)=>{if(m.timestamp!==void 0&&f.timestamp!==void 0){let _=Ft(m.timestamp,f.timestamp);if(_!==0)return _}else{if(m.timestamp===void 0&&f.timestamp!==void 0)return 1;if(m.timestamp!==void 0)return-1}let p=c.has(m.eventId),h=c.has(f.eventId);return p!==h?Number(h)-Number(p):0}),u=o0([...r.slice(0,o),...d]);return{merged:aa(u),strategy:"union_reanchor",common_entries:o,entries_from_ours:s.length,entries_from_theirs:l.length,entries_total:u.length,reanchored:!0}}var s0=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],c0=["acceptance_criteria"],l0=["updated_at"];function Xt(e,t){return e===void 0||t===void 0?e===void 0&&t===void 0:T(e)===T(t)}function Zf(e,t,n){let r=d=>Array.isArray(d)?d:[],i=new Set(r(e).map(d=>T(d))),a=r(t),o=new Set(a.map(d=>T(d))),s=r(n),c=new Set(s.map(d=>T(d))),l=a.filter(d=>{let u=T(d);return!i.has(u)||c.has(u)});for(let d of s){let u=T(d);!o.has(u)&&!i.has(u)&&l.push(d)}return l}function Er(e){if(typeof e!="object"||e===null||Array.isArray(e))return T(e);let{provenance:t,...n}=e;return T(n)}function d0(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function u0(e,t,n){let r=d=>Array.isArray(d)?d:[],i=new Set(r(e).map(Er)),a=r(t),o=new Set(a.map(Er)),s=r(n),c=new Set(s.map(Er)),l=a.filter(d=>{let u=Er(d);return!i.has(u)||c.has(u)});for(let d of s){let u=Er(d);!o.has(u)&&!i.has(u)&&l.push(d0(d))}return l}function m0(e,t){return Ft(String(e),String(t))>=0?e:t}function Qf(e,t,n,r){return Xt(t,n)?{value:t,from_theirs:!1,conflict:!1}:Xt(e,t)?{value:n,from_theirs:!0,conflict:!1}:Xt(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function eh(e,t,n,r,i,a,o){let s=Qf(e,t,n,r);if(!s.conflict)return{...s,conflict:!1};if(i==="preferred_side")return{...s,resolution_basis:"requested_preference",retained_side:s.from_theirs?"theirs":"ours"};let c=Ft(a,o);if(i==="latest_document_update"&&c!==0){let d=c<0;return{value:d?n:t,from_theirs:d,conflict:!0,resolution_basis:"document_updated_at",retained_side:d?"theirs":"ours"}}let l=T(Y(n)).localeCompare(T(Y(t)))<0;return{value:l?n:t,from_theirs:l,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:l?"theirs":"ours"}}function Es(e){return{...e.metadata}}function xs(e,t,n){try{let r=ql(Et(e,n),n),i=Object.entries(r.metadata).find(([,a])=>On(a))?.[0];if(i!==void 0)throw new TypeError(`metadata field ${i} uses the reserved missing-scalar evidence marker`);return r}catch(r){throw new y(`Item merge input (${t}) is not a readable item document: ${String(r)}`,g.GENERIC_FAILURE)}}function p0(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?u0(e.baseValue,e.oursValue,e.theirsValue):e.field==="acceptance_criteria"?Zf(mi(e.baseValue),mi(e.oursValue),mi(e.theirsValue)).join("; "):Zf(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,Xt(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function f0(e){let t=eh(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution,e.oursUpdatedAt,e.theirsUpdatedAt);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:Y(e.baseValue),ours:Y(e.oursValue),theirs:Y(e.theirsValue),retained:Y(t.value),discarded:Y(t.from_theirs?e.oursValue:e.theirsValue),retained_side:t.retained_side,resolution_basis:t.resolution_basis})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function h0(e,t,n,r,i,a,o){let s=new Set([...s0,...c0]),c=new Set(l0),l=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,m)=>u.localeCompare(m)),d={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let u of l){let m=e[u],f=t[u],p=n[u];if(!p0({field:u,baseValue:m,oursValue:f,theirsValue:p,unionFieldSet:s,accumulator:d})){if(c.has(u)){d.merged[u]=m0(f,p);continue}f0({field:u,baseValue:m,oursValue:f,theirsValue:p,preferred:r,conflictResolution:i,oursUpdatedAt:a,theirsUpdatedAt:o,accumulator:d})}}return d}function Yj(e,t,n,r={}){let i=r.preferred??"ours",a=r.conflictResolution??"preferred_side",o=xs(t,"ours",r),s=xs(n,"theirs",r);if(e.trim().length===0)throw new y("Duplicate item identity: add/add item documents have no common ancestor. Preserve both branches and assign distinct item ids before merging.",g.CONFLICT,{code:"item_identity_conflict",item_id:o.metadata.id});let c=xs(e,"base",r);if(c.metadata.id!==o.metadata.id||c.metadata.id!==s.metadata.id)throw new y("Duplicate or mismatched item identity: all merge sides must address the common ancestor's item id.",g.CONFLICT,{code:"item_identity_conflict",item_id:c.metadata.id});let l=Es(c),d=Es(o),u=Es(s),{merged:m,conflictFields:f,fieldsFromTheirs:p,unionFields:h,conflictDecisions:_}=h0(l,d,u,i,a,o.metadata.updated_at,s.metadata.updated_at),w=eh(c.body,o.body,s.body,i,a,o.metadata.updated_at,s.metadata.updated_at);return w.conflict?(f.push("body"),_.push({field:"body",base:Y(c.body),ours:Y(o.body),theirs:Y(s.body),retained:Y(w.value),discarded:Y(w.from_theirs?o.body:s.body),retained_side:w.retained_side,resolution_basis:w.resolution_basis})):w.from_theirs&&p.push("body"),{merged:Gl({metadata:m,body:w.value},r),conflict_fields:f,fields_from_theirs:p,union_fields:h,conflict_decisions:_,requested_preference:i,requested_preference_applied:a==="preferred_side",conflict_resolution:a}}function Is(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function As(e,t){let n=Me(e);if(n)throw new y(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,g.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new y(`JSON merge input (${t}) is not valid JSON.`,g.GENERIC_FAILURE)}}function _0(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=l=>{let d=new Map;for(let u of l){let m=T(u);d.set(m,(d.get(m)??0)+1)}return d},i=r(e),a=r(t),o=r(n);for(let[l,d]of i)if((a.get(l)??0)<d||(o.get(l)??0)<d)return null;let s=new Map(a),c=[];for(let l of n){let d=T(l),u=s.get(d)??0;u>0?s.set(d,u-1):c.push(l)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function g0(e,t,n,r,i,a,o){if(!Is(t)||!Is(n))return null;let s=Is(e)?e:{},c={},l=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((d,u)=>d.localeCompare(u));for(let d of l){let u=i.length>0?`${i}.${d}`:d,m=y0(s,t,n,d,r,u,a,o);m!==void 0&&(c[d]=m)}return c}function th(e,t,n,r,i,a,o){if(Xt(t,n))return t;let s=_0(e,t,n);if(s!==null)return s.acceptedTheirs&&o.push(i),s.merged;let c=g0(e,t,n,r,i,a,o);if(c!==null)return c;let l=Qf(e,t,n,r);return l.conflict?a.push(i):l.from_theirs&&o.push(i),l.value}function y0(e,t,n,r,i,a,o,s){let c=Object.prototype.hasOwnProperty.call(t,r),l=Object.prototype.hasOwnProperty.call(n,r),d=Object.prototype.hasOwnProperty.call(e,r);if(c&&l)return th(e[r],t[r],n[r],i,a,o,s);if(c){if(d&&Xt(e[r],t[r])){s.push(a);return}return d?(o.push(a),i==="theirs"?void 0:t[r]):t[r]}if(!(d&&Xt(e[r],n[r])))return d?(o.push(a),i==="theirs"?n[r]:void 0):(s.push(a),n[r])}function Xj(e,t,n,r={}){let i=r.preferred??"ours",a=As(e,"base"),o=As(t,"ours"),s=As(n,"theirs"),c=[],l=[],d=th(a,o,s,i,"",c,l);return{merged:`${JSON.stringify(d??null,null,2)}
59
+ `,conflict_paths:c,paths_from_theirs:l,preferred:i}}import{constants as nh}from"node:fs";import{lstat as w0,open as v0}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b063a672-991a-5251-a2f3-6a1c7bcafd2f")}catch{}})();var b0={lstat:w0,open:v0};function k0(e){return e.O_NOFOLLOW??0}async function xr(e,t,n=b0){let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||r.size>t)return null;let i=await n.open(e,nh.O_RDONLY|k0(nh));try{let a=await i.stat();if(!a.isFile()||a.size>t)return null;let o=Buffer.alloc(a.size),s=0;for(;s<o.length;){let{bytesRead:c}=await i.read(o,s,o.length-s,s);if(c===0)break;s+=c}return(await i.stat()).size===a.size&&s===a.size?o.toString("utf8",0,s):null}finally{await i.close()}}import oa from"node:path";import{execFile as S0}from"node:child_process";import{createHash as E0}from"node:crypto";import{readdir as x0}from"node:fs/promises";import I0 from"node:path";import{promisify as A0}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ff7b12a2-17f8-5989-b153-3b8e5f9e628b")}catch{}})();var Zt=A0(S0),Rs=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function cF(e,t){let n=t.trim(),r=/^(['"])(.*)\1$/su.exec(n)?.[2]??n;for(let i of["rebase-merge","rebase-apply"])try{let{stdout:a}=await Zt("git",["rev-parse","--path-format=absolute","--git-path",`${i}/orig-head`],{cwd:e,timeout:1e4}),o=(await xr(a.trim(),128))?.trim();if(o===void 0||!Rs.test(o))continue;let{stdout:s}=await Zt("git",["rev-parse","--verify",`${o}:${r}`],{cwd:e,timeout:1e4}),c=s.trim();return{kind:"rebase",original_head:o,original_blob:c}}catch{}}function rh(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&t.kind==="rebase"&&typeof t.original_head=="string"&&Rs.test(t.original_head)&&typeof t.original_blob=="string"&&Rs.test(t.original_blob)}async function ih(e,t,n,r){if(r!==void 0&&E0(n.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(r)}\0`).update(r).digest("hex")!==n.original_blob)return!1;try{let{stdout:i}=await Zt("git",["rev-parse","--absolute-git-dir"],{cwd:e,timeout:1e4}),a=new Set(["rebase-merge","rebase-apply","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD"]);if((await x0(i.trim())).some(l=>a.has(l)))return!1;let{stdout:o}=await Zt("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(o.trim()!==n.original_head)return!1;let{stdout:s}=await Zt("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(s.trim()!==n.original_blob)return!1;let{stdout:c}=await Zt("git",["hash-object","--",I0.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await Zt("git",["diff","--cached","--quiet","HEAD","--",t],{cwd:e,timeout:1e4}),!0)}catch{return!1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35c5d9a8-5ae0-5e97-9ea3-f8a70a5fd7d0")}catch{}})();var R0=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,C0=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,ca=2048,T0=64,$0=1e5,O0=new Set(["version","id","item_path","item_id","requested_preference","requested_preference_applied","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","value_policy","evidence_source","operation","settlement"]);function _t(e){return R0.test(e)}var D0=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),la="bounded_non_sensitive_scalars_v1",P0=new Set(["open","in_progress","blocked","closed","canceled"]),N0=new Set(["risk","confidence","severity"]),L0=new Set(["low","medium","high","critical"]),oh=new Map([["priority",new Set([0,1,2,3,4].map(T))],["status",new Set([...P0].map(T))],...[...N0].map(e=>[e,new Set([...L0].map(T))])]);function rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sh(e,t){return Object.keys(e).every(n=>t.has(n))}function sa(e){return Array.isArray(e)&&e.length<=ca&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function Ir(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>$0||r.depth>T0)return!1;if(Array.isArray(r.value))for(let i of r.value)t.push({value:i,depth:r.depth+1});else if(rt(r.value))for(let i of Object.values(r.value))t.push({value:i,depth:r.depth+1})}return!0}function ch(e){if(!rt(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[sh(e,D0),typeof e.field=="string",typeof e.field=="string"&&e.field.length>0,typeof e.field=="string"&&e.field.length<=256,Object.hasOwn(e,"base"),Object.hasOwn(e,"ours"),Object.hasOwn(e,"theirs"),Object.hasOwn(e,"retained"),Object.hasOwn(e,"discarded"),Ir(e.base),Ir(e.ours),Ir(e.theirs),Ir(e.retained),Ir(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function M0(e){if(!rt(e))return!1;let t=Object.entries(e);return t.length<=ca&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function j0(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||oa.posix.isAbsolute(e))return!1;let n=oa.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&oa.posix.basename(n,oa.posix.extname(n))===t}function F0(e){return!sa(e.fields_from_theirs)||!sa(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>ca||!e.decisions.every(ch)?!1:e.merged_field_hashes===void 0||M0(e.merged_field_hashes)}function U0(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order","latest_document_update"],r=[void 0,"clone_local","hash_only","bounded_inline","mixed"],i=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&(e.requested_preference_applied===void 0||typeof e.requested_preference_applied=="boolean")&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&r.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===la)&&i.includes(e.evidence_source)}function H0(e){return typeof e.created_at=="string"&&ln(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&ln(e.reconciled_at))}function ah(e,t){if(!rt(t)||da(t)===void 0)return!1;let n=Object.keys(t);if(!n.every(i=>i==="pm_value_hash"||i==="pm_value"))return!1;if(!Object.hasOwn(t,"pm_value"))return n.length===1;let r=t.pm_value;return(r===null||oh.get(e)?.has(T(r))===!0)&&Dt(r)===t.pm_value_hash}function z0(e){if(!e.decisions.every(r=>r.base===null&&r.ours===null&&r.theirs===null&&ah(r.field,r.retained)&&ah(r.field,r.discarded)))return!1;let t=e.decisions.reduce((r,i)=>r+(rt(i.retained)&&Object.hasOwn(i.retained,"pm_value")?1:0)+(rt(i.discarded)&&Object.hasOwn(i.discarded,"pm_value")?1:0),0),n=t===0?"hash_only":t===e.decisions.length*2?"bounded_inline":"mixed";return e.value_availability===n&&(t===0||e.value_policy===la)}function W0(e){return e.operation!==void 0&&!rh(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function G0(e){for(let t of["version","id","item_path","item_id","fields_from_theirs","union_fields","decisions","state","created_at"])if(!Object.hasOwn(e,t))return"required_fields";return e.version!==1||!sh(e,O0)?"required_fields":typeof e.id!="string"||!_t(e.id)?"receipt_id":typeof e.item_id!="string"||!C0.test(e.item_id)?"item_id":j0(e.item_path,e.item_id)?null:"item_path"}function Cs(e,t){if(!rt(e))return"required_fields";let n=G0(e);return n!==null?n:W0(e)?F0(e)?U0(e)?H0(e)?t==="durable"&&!z0(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function Ts(e){if(!rt(e)||e.version!==1||e.value_policy!==void 0||!Array.isArray(e.decisions))return e;let t=(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0,n=(e.requested_preference==="ours"||e.requested_preference==="theirs")&&e.value_availability==="clone_local";return!t&&!n?e:{...e,decisions:e.decisions.map(r=>!rt(r)||!Object.hasOwn(r,"retained")||!Object.hasOwn(r,"discarded")?r:{base:Y(void 0),ours:Y(void 0),theirs:Y(void 0),...r})}}function lh(e){if(!rt(e))return;if(!sa(e.fields_from_theirs))return"fields_from_theirs";if(!sa(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>ca)return"decisions";let t=e.decisions.findIndex(n=>!ch(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function $s(e,t){return Cs(e,t)===null}function da(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function Os(e,t){let n=On(t),r=Dt(n?void 0:t);return!n&&(t===null||oh.get(e)?.has(T(t))===!0)?{pm_value_hash:r,pm_value:t}:{pm_value_hash:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="03b0537b-0444-5351-b1ff-250d8bbfbd95")}catch{}})();var Y0=K0(q0),mh=16*1024*1024,ua=100;async function Ds(e){try{let{stdout:t}=await Y0("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function ph(e,t){let n=ge.dirname(ge.resolve(e,t));for(let r=0;r<12;r+=1){if(await O(ge.join(n,"settings.json")))return n;let i=ge.dirname(n);if(i===n)break;n=i}return null}function Ps(e){return ge.join(e,"merge-receipts")}function Dn(e){return`${e}.json`}async function dh(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await xr(e.receiptPath,mh)}catch(a){if(bt(a))return null;throw a}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=Ts(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!$s(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||ge.basename(e.receiptPath)!==Dn(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:r,...i}=n;return{path:e.receiptPath,fingerprints:Ns(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
60
+ `}}function Ar(e,t=!1){return Ie(T({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,operation:e.operation??null,decisions:t?e.decisions.map(n=>({field:n.field,retained_hash:Ie(T(Y(n.retained))),discarded_hash:Ie(T(Y(n.discarded)))})):Ls(e).decisions}))}function Ns(e){let t=[Ar(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push(Ar(e,!0)),t}function X0(e,t){if(e.state==="reconciled"&&t.state==="reconciled"&&e.settlement===t.settlement)return e;let{reconciled_at:n,settlement:r,...i}=e;return{...i,state:"pending"}}function Ls(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:da(t.retained)??Dt(On(t.retained)?void 0:t.retained),discarded_hash:da(t.discarded)??Dt(On(t.discarded)?void 0:t.discarded)}))}}async function RF(e){let t=await Ds(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,i=ge.basename(r,ge.extname(r)),a={version:1,id:B0(),item_path:r.replaceAll("\\","/"),item_id:i,requested_preference:e.preferred,requested_preference_applied:(e.conflictResolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions).map(s=>({...s,base:Y(s.base),ours:Y(s.ours),theirs:Y(s.theirs),retained:Y(s.retained),discarded:Y(s.discarded)})),...e.operation?{operation:e.operation}:{},state:"pending",created_at:$(),value_availability:"clone_local"};await qn(t),await Z(ge.join(t,Dn(a.id)),`${JSON.stringify(a,null,2)}
61
+ `);let o=await ph(e.cwd,a.item_path);if(o!==null){let s=Ps(o),c=a.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:Os(u.field,u.retained),discarded:Os(u.field,u.discarded),retained_side:u.retained_side,resolution_basis:u.resolution_basis})),l=c.reduce((u,m)=>u+(Object.hasOwn(m.retained,"pm_value")?1:0)+(Object.hasOwn(m.discarded,"pm_value")?1:0),0),d={...a,decisions:c,value_availability:l===0?"hash_only":l===c.length*2?"bounded_inline":"mixed",value_policy:la};await qn(s),await Z(ge.join(s,Dn(a.id)),`${JSON.stringify(d,null,2)}
62
+ `)}return a}async function uh(e,t){let n;try{n=await V0(e)}catch(s){let c=await Z0(e,s);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let r=[],i=0,a=[],o=(s,c)=>{if(i+=1,a.length>=ua)return;let l=s.slice(0,-5);a.push({evidence_source:t,reason:c.reason,...c.validation_path?{validation_path:c.validation_path}:{},...c.validation_error===void 0?{}:{validation_error:c.validation_error},..._t(l)?{receipt_id:l}:{candidate_name_hash:Ie(s)}})};for(let s of n.sort((c,l)=>c.localeCompare(l))){if(!s.endsWith(".json"))continue;let c=await Q0(e,s,t);c.receipt!==void 0?r.push(c.receipt):o(s,c)}return{receipts:r,invalid_evidence_count:i,invalid_evidence:a,invalid_evidence_truncated:i>a.length}}async function Z0(e,t,n=J0){if(!U(t))return!1;let r=e;for(;;)try{return(await n(r)).isDirectory()}catch(i){if(!U(i))return!1;let a=ge.dirname(r);if(a===r)return!0;r=a}}async function Q0(e,t,n){let r;try{r=await xr(ge.join(e,t),mh)}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let i;try{i=Ts(JSON.parse(r))}catch{return{reason:"candidate_invalid_json"}}let a=Cs(i,n);if(a!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(a)?"identity_invalid":"schema_invalid",validation_error:a,...a==="collections"?{validation_path:lh(i)}:{}};let o=i;if(t!==Dn(o.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:s,evidence_source:c,...l}=o;return{receipt:{...l,requested_preference:o.requested_preference??s??"ours",requested_preference_applied:o.requested_preference_applied??(o.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:o.conflict_resolution??"preferred_side",evidence_source:n}}}async function gt(e,t={}){let n=await Ds(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await uh(n,"clone_local"),i=t.pmRoot??ge.join(e,".agents","pm"),a=await uh(Ps(i),"durable"),o=new Map(a.receipts.map(l=>[l.id,l])),s=0,c=[];for(let l of r.receipts){let d=o.get(l.id);if(d!==void 0&&!(d.value_policy===void 0?Ns(l):[Ar(l)]).includes(Ar(d))){o.delete(l.id),s+=1,r.invalid_evidence.length+a.invalid_evidence.length+c.length<ua&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:l.id});continue}o.set(l.id,d===void 0?l:X0(l,d))}return{receipts:[...o.values()].filter(l=>(t.includeReconciled||l.state==="pending")&&(t.includeLossless!==!1||l.decisions.length>0)).sort((l,d)=>l.created_at.localeCompare(d.created_at)),invalid_evidence_count:r.invalid_evidence_count+a.invalid_evidence_count+s,invalid_evidence:[...r.invalid_evidence,...a.invalid_evidence,...c].slice(0,ua),invalid_evidence_truncated:r.invalid_evidence_truncated||a.invalid_evidence_truncated||r.invalid_evidence_count+a.invalid_evidence_count+s>ua,clone_local_evidence_resolved:n!==null}}function Pn(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function CF(e,t,n={}){let r=await Ds(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let i=t.evidence_source??"clone_local";if(!$s(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=$(),o=ge.join(r,Dn(t.id)),s=await ph(e,t.item_path),c=s===null?null:ge.join(Ps(s),Dn(t.id)),l=(await Promise.all([dh({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[dh({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:a,settlement:n.settlement})]])).filter(d=>d!==null);if(l.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(l.some(d=>d.modern)?[Ar(t)]:Ns(t)).some(d=>l.every(u=>u.fingerprints.includes(d))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let d of l)await Z(d.path,d.content)}async function TF(e){let t=await gt(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:$()}}import{createHash as ex}from"node:crypto";import ma from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36749195-9194-546a-bc3e-718f09c3b8d6")}catch{}})();var tx="2026-08-09T16:15:18.000Z",hh=Symbol("pre-durable-disposition-eligible");function yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ms(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let r=e[n];if(!(n in e)||typeof r!="string"||r.length===0||r.length>256||r.includes("\0")||t.has(r))return!1;t.add(r)}return!0}function fh(e){return yt(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function _h(e,t){if(typeof e!="string")return!1;let n=ma.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!ma.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(ma.posix.basename(n)===`${t}.toon`||ma.posix.basename(n)===`${t}.md`)}function nx(e,t){return typeof e.receipt_id=="string"&&_t(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&_h(e.item_path,t)}function gh(e){let t=e.conflict_fields,n=e.fields_from_theirs,r=e.union_fields,i=e.decisions,a=Array.isArray(i)?new Set(i.flatMap(o=>fh(o)?[o.field]:[])):new Set;return Ms(t)&&Ms(n)&&Ms(r)&&Array.isArray(i)&&i.length>0&&i.length<=256&&Object.keys(i).length===i.length&&i.every(fh)&&a.size===i.length&&t.length===a.size&&t.every(o=>a.has(o))}function rx(e,t){return nx(e,t)&&gh(e)}function ix(e,t){return typeof e.receipt_id=="string"&&_t(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&_h(e.item_path,t)&&gh(e)}function ax(e){return e[hh]===!0}function yh(e,t){if(!yt(e)||!yt(e.context))return[];let n=e.context.merge;return!yt(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(r=>!yt(r)||typeof r.receipt_id!="string"||r.receipt_id.trim().length===0?[]:[{receiptId:r.receipt_id,legacySummaryAccepted:rx(r,t),[hh]:ix(r,t),...typeof e.ts=="string"&&ln(e.ts)?{eventTimestamp:e.ts}:{}}])}function wh(e,t,n){if(!yt(e)||e.op!=="merge_reconcile")return[];if(!yt(e.context)||!yt(e.context.merge))return[];let r=e.context.merge.missing_receipt_dispositions;return!Array.isArray(r)||r.length>256?[]:r.flatMap(i=>!yt(i)||typeof i.receipt_id!="string"||!_t(i.receipt_id)||typeof i.original_history_line!="number"||!Number.isSafeInteger(i.original_history_line)||i.original_history_line<1||typeof i.original_event_ts!="string"||!ln(i.original_event_ts)||i.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:i.receipt_id,originalHistoryLine:i.original_history_line,originalEventTimestamp:i.original_event_ts,auditHistoryLine:n,reason:i.reason}])}function vh(e,t,n=[]){let r=new Map;for(let a of n){let o=`${a.itemId}\0${a.originalHistoryLine}\0${a.receiptId}\0${a.originalEventTimestamp}`;r.set(o,Math.max(r.get(o)??0,a.auditHistoryLine))}let i=a=>ax(a)&&a.eventTimestamp!==void 0&&Ft(a.eventTimestamp,tx)<0&&(r.get(`${a.itemId}\0${a.line}\0${a.receiptId}\0${a.eventTimestamp}`)??0)>a.line;return{missing:e.filter(a=>!a.legacySummaryAccepted&&!t.has(a.receiptId)&&!i(a)).map(a=>({item_id:a.itemId,history_line:a.line,..._t(a.receiptId)?{receipt_id:a.receiptId}:{receipt_reference_hash:ex("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(i).length}}import{isUtf8 as ox}from"node:buffer";import{readFile as sx}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cca38e64-dd53-5086-8825-dc1c8f1cc587")}catch{}})();function cx(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new y("History salvage cannot discard a potentially complete record with trailing corruption.",g.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new y("History salvage would conceal interior corruption or a malformed record.",g.CONFLICT,{code:"history_salvage_refused"});let n=t;if(!Array.isArray(n.patch)||![n.ts,n.author,n.op,n.before_hash,n.after_hash].every(r=>typeof r=="string"))throw new y("History salvage requires complete history records before the invalid tail.",g.CONFLICT,{code:"history_salvage_refused"});return n}function lx(e){if(Me(e))throw new y("Resolve history merge conflicts before salvage.",g.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,r,i=0;for(let[o,s]of e.split(`
63
+ `).entries()){if(!s.trim()){n+=s.length+1;continue}let c=cx(s);if(c===null){r===void 0&&(r=n,i=o+1),n+=s.length+1;continue}if(r!==void 0)throw new y("History salvage would discard a record or conceal interior corruption.",g.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});t.push(c),n+=s.length+1}let a=mn(t);if(!a.ok||a.item_hash_version===void 0)throw new y("History salvage requires a nonempty verified prefix.",g.CONFLICT,{code:"history_salvage_refused",verification_errors:a.errors,required:"Recover an intact history prefix from version control or a backup."});return{entries:t,itemHashVersion:a.item_hash_version,prefix:r===void 0?e:e.slice(0,r),receipt:r===void 0?null:{first_invalid_line:i,discarded_bytes:Buffer.byteLength(e.slice(r)),discarded_sha256:Ie(e.slice(r)),retained_entries:t.length}}}async function dx(e,t,n){if(!e.located)return{itemRaw:null,document:n};let r=await Ad(e.located,{schema:t.schema});return{itemRaw:r.raw,document:r.document??n}}async function bh(e){let t;try{t=await sx(e)}catch(n){if(U(n))return null;throw n}if(!ox(t))throw new y("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",g.CONFLICT,{code:"history_salvage_refused"});return t.toString("utf8")}async function kh(e){let{subject:t,settings:n,options:r,author:i}=e;if([r.normalizeProvenance,r.auditOperation,r.auditContext,r.auditContextById,r.forceAuditEntry,r.mergeReceiptProof,r.mergeReceiptProofById].some(Boolean))throw new y("Tail salvage cannot be combined with other repair modes.",g.USAGE);let a=await bh(t.historyPath);if(a===null)throw new y(`No history stream exists for ${t.id}.`,g.NOT_FOUND);await ze({path:t.historyPath,scope:"project"});let o=lx(a),s=wd(o.entries,o.entries.length-1),c=td(s);if(typeof s.metadata.id=="string"&&s.metadata.id!==t.id)throw new y("History belongs to another item; salvage refused.",g.CONFLICT,{code:"history_salvage_refused"});let l=await dx(t,n,c),d=Io({itemDocument:l.document,subjectId:t.id,author:i,force:r.force,settings:n}),u=o.itemHashVersion,m=r.dryRun===!0,f=o.receipt!==null;if(f&&!m){let p=await re(e.pmRoot,t.id,n.locks.ttl_seconds,i,!!r.force,n.governance.force_required_for_stale_lock,n.locks.wait_ms);try{let h=await bh(t.historyPath),_=await we(e.pmRoot,t.id,n.id_prefix,n.item_format,e.typeRegistry.type_to_folder),w=_?await V(_.itemPath):null;if(h!==a||w!==l.itemRaw)throw new y("History or item changed while waiting for salvage lock; retry.",g.CONFLICT);let v=ai({...Zl({hashAlgorithm:Re(o.entries.at(-1).hash_algorithm),nowIso:$(),author:i,op:"history_salvage",before:c,after:c,message:r.message,context:{history_salvage:o.receipt}}),before_hash:o.entries.at(-1).after_hash,after_hash:o.entries.at(-1).after_hash,item_hash_version:u});await $i({historyPath:t.historyPath,historyRawUnderLock:a,nextHistoryRaw:`${o.prefix}${JSON.stringify(v)}
64
+ `}),d.push(...await X({path:t.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await p()}}return{id:t.id,dry_run:m,changed:f,history:{path:t.historyPath,entries_scanned:o.entries.length,chain_drift_before:!1,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:f&&!m,verify_ok:!0,verify_errors:[],item_hash_version_before:u,item_hash_version_after:u,version_disposition:"preserved"},item:{exists:t.located!==null,path:t.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...o.receipt?{salvage:o.receipt}:{},warnings:d,generated_at:$()}}import{realpath as Ih}from"node:fs/promises";import js from"node:path";import Ah from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5df05541-b114-52bd-9540-d741b2657edf")}catch{}})();function Sh(e,t){return t==="body"?e.body:e.metadata[t]}function Fs(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(i=>{let a=t.findIndex((o,s)=>!r.has(s)&&Fs(i,o));return a<0?!1:(r.add(a),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,i])=>Object.hasOwn(n,r)&&Fs(i,n[r]))}function Eh(e,t){let n=new Set(t),r=[];for(let i=e.length-1;i>=0&&n.size>0;i-=1){let a=e[i],o=new Set;for(let c of rd(a.patch))o.add(pi(c.path)),c.from&&o.add(pi(c.from));let s=[...n].filter(c=>o.has(c));if(s.length!==0){for(let c of s)n.delete(c);r.push({index:i+1,ts:a.ts,author:a.author,op:a.op,fields:s.sort((c,l)=>c.localeCompare(l))})}}return r.reverse()}function ux(e,t,n){let r=Ah.compare(t,n);if(r.length===0)return;let i=new Set;for(let p of r)i.add(pi(p.path));let a=new Set([...i].filter(p=>Fs(Sh(t,p),Sh(n,p)))),o=new Set([...i].filter(p=>!a.has(p))),s=Eh(e,o),c=Eh(e,a),l=[...i].sort((p,h)=>p.localeCompare(h)),d=[...o].sort((p,h)=>p.localeCompare(h)),u=[...a].sort((p,h)=>p.localeCompare(h)),m=[...new Set(s.map(p=>p.author))].sort((p,h)=>p.localeCompare(h)),f=[...new Set(c.map(p=>p.author))].sort((p,h)=>p.localeCompare(h));return{reconciled_field_count:i.size,reconciled_fields:l,reverted_field_count:o.size,reverted_fields:d,discarded_events:s,discarded_authors:m,preserved_field_count:a.size,preserved_fields:u,preserved_events:c,preserved_authors:f,recovery_hint:s.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function mx(e){try{return await Ih(e)}catch{return null}}async function px(e){if(await mx(js.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let t=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),n=e.receipt.merged_field_hashes;if(!n||t.length===0)return null;let r=Object.keys(n).sort();if(t.length!==r.length||t.some((a,o)=>a!==r[o]))return null;let i=e.currentItemReplay.metadata;return t.every(a=>{let o=a==="body"?e.currentItemReplay.body:i[a];return[Dt(o),Ie(T(Y(o)))].includes(n[a])})?{receipt:e.receipt,declaredFields:t}:null}async function fx(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(o=>o.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await Ih(e.itemPath),r=[];for(let o of t){let s=await px({receipt:o,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});s&&r.push(s)}let i=new Set(r.flatMap(({declaredFields:o})=>o)),a=e.reconciliation?.reconciled_fields;return r.length>0&&(a===void 0||a.length>0&&a.every(o=>i.has(o)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:o})=>o.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function xh(e,t,n,r){if(e===void 0)return;let{receipt:i,gitWorkspaceRoot:a}=e,o=t.currentItemPath===null?null:js.relative(a,t.currentItemPath).split(js.sep).join("/");if(!n||r.entriesRehashed!==0||r.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||o!==i.item_path||i.operation===void 0||!await ih(a,i.item_path,i.operation,t.currentItemRawBeforeLock))throw new y("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function hx(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(a=>a.item_id===e.subjectId).map(a=>a.id)??[]),n=(e.options.mergeReceiptProof?await gt(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0)?.receipts.filter(a=>a.item_id===e.subjectId&&t.has(a.id))??[],r=e.options.mergeReceiptProof?await fx({proof:{...e.options.mergeReceiptProof,receipts:n},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(r&&!r.trusted&&e.options.force!==!0)throw new y(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${r.reason}).`,g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let i=r?.trusted?n.filter(a=>r.receipt_ids.includes(a.id)):[];return{mergeReceiptProof:r,effectiveAuditContext:i.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:i.map(Ls)}}:e.options.auditContext}}function _x(e,t,n){let r=e.located?.itemPath??null,i=t.loadedItem,a=t.entries;if(!i)return{currentItemReplay:null,currentItemPath:r,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let o=nd(i.document),s=a[a.length-1].after_hash;return{currentItemReplay:o,currentItemPath:r,matchedChainBefore:un(o,n,Re(a.at(-1)?.hash_algorithm)).includes(s),currentItemRawBeforeLock:i.raw,loadedItem:i}}function gx(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function yx(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=Re(e.reanchorEntries.at(-1)?.hash_algorithm),i=un(e.finalReplay,e.itemHashVersion,r),a=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=i.indexOf(a),s=un(n,e.itemHashVersion,r),c={hash_algorithm:r,ts:$(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Ah.compare(e.finalReplay,e.currentItemReplay):[],before_hash:i[o],after_hash:s[o],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(ai({...c,event_class:Vl(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function wx(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function Us(e,t,n){let{pmRoot:r,settings:i,typeRegistry:a}=await oo(n.path),o=await Jd(r,e,i,a.type_to_folder);return t.salvageTail===!0?kh({pmRoot:r,subject:o,settings:i,typeRegistry:a,options:t,author:G(t.author,i.author_default)}):nm({pmRoot:r,subject:o,settings:i,typeRegistry:a,operation:"history-repair",options:t,transform:s=>bx({pmRoot:r,subject:o,options:t},s)})}function vx(e,t){let n=e.mergeAbandonmentProof!==void 0&&e.auditContext!==void 0&&t.some(r=>r.op==="merge_reconcile"&&T(r.context)===T(e.auditContext));return e.forceAuditEntry===!0&&!n}async function bx(e,t){let{pmRoot:n,subject:r,options:i}=e,a=t.entries,o=t.verification,s=mn(a),c=i.normalizeProvenance?Yu(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},l=id(c.entries),d=new Set(c.entries.map(I=>I.item_hash_version).filter(I=>I!==void 0)),u=oi(c.entries,l),m=_x(r,t,l);await xh(i.mergeAbandonmentProof,m,o.ok,u);let f=u.finalDocument,p=un(f,l),h=!1;if(m.currentItemReplay!==null){let I=un(m.currentItemReplay,l);h=!p.some((R,Q)=>R===I[Q])}let _=h&&m.currentItemReplay?ux(u.entries,f,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await hx({options:i,pmRoot:n,subjectId:r.id,itemReplayContext:m,reconciliation:_}),S=[u.entriesRehashed>0,u.entriesPatchRepaired>0,h,vx(i,a),c.receipt.changed].some(Boolean),k=t.author,x=!!i.dryRun,D=gx({message:i.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:E,auditEntryAdded:b}=yx({reanchorEntries:u.entries,changed:S,reconcileNeeded:h,currentItemReplay:m.currentItemReplay,finalReplay:f,author:k,message:D,auditOperation:i.auditOperation??"history_repair",auditContext:c.receipt.changed?{...v,provenance_normalization:c.receipt}:v,itemHashVersion:l,explicitItemHashVersion:u.explicitItemHashVersion}),N=wx(S,u.skippedOps,_);return{changed:S,rewrittenEntries:E,beforeWrite:async()=>xh(i.mergeAbandonmentProof,m,o.ok,u),report:({verification:I,warnings:R})=>({id:r.id,dry_run:x,changed:S,history:{path:r.historyPath,entries_scanned:a.length,chain_drift_before:!o.ok,entries_rehashed:u.entriesRehashed,entries_patch_repaired:u.entriesPatchRepaired,converted_replace_to_add:u.convertedReplaceToAdd,skipped_ops:u.skippedOps,reconciled_with_item:h,audit_entry_added:b,verify_ok:I.ok,verify_errors:I.errors,item_hash_version_before:s.item_hash_version??null,item_hash_version_after:l,version_disposition:d.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:m.currentItemPath!==null,path:m.currentItemPath,matched_chain_before:m.matchedChainBefore},provenance_normalization:{requested:i.normalizeProvenance===!0,...c.receipt},..._?{reconciliation:_}:{},...w?{merge_receipt_proof:w}:{},warnings:[...new Set([...N,...R])].sort((Q,xe)=>Q.localeCompare(xe)),generated_at:$()})}}function S1(e,t){if(t&&e!==void 0)throw new y("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",g.USAGE);if(!t&&e===void 0)throw new y("history-repair: provide an item <id> or pass --all to repair every drifted stream.",g.USAGE)}async function E1(e,t){if(e.salvageTail===!0)throw new y("Tail salvage requires one explicit item ID; --all is not supported.",g.USAGE);let{pmRoot:n,settings:r,typeRegistry:i}=await oo(t.path),a=[],o=await zt(n,r.item_format,i.type_to_folder,a,r.schema,{forceSourceScan:!0}),s=await qt(n,o),c=e.normalizeProvenance?await Xu(n):[],l=[...new Set([...s.driftedItems,...c])].sort((f,p)=>f.localeCompare(p)),d=[],u=[],m={repaired:0,skipped_clean:0,failed:0};for(let f of l)try{let p=await Us(f,{...e,auditContext:e.auditContextById?.[f],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[f]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),h=p.changed?"repaired":"skipped_clean";m[h]+=1,u.push(...p.warnings.map(_=>`${f}:${_}`)),d.push({id:f,outcome:h,entries_rehashed:p.history.entries_rehashed,entries_patch_repaired:p.history.entries_patch_repaired,reconciled_with_item:p.history.reconciled_with_item,...p.reconciliation?{reconciliation:p.reconciliation}:{},...p.merge_receipt_proof?{merge_receipt_proof:p.merge_receipt_proof}:{},warnings:p.warnings})}catch(p){m.failed+=1,d.push({id:f,outcome:"failed",error:p instanceof Error?p.message:String(p)})}return e.dryRun||await Jl(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:o.length,drifted_streams:s.driftedItems.length,provenance_invalid_streams:c.length,streams:d,totals:m,warnings:[...new Set([...a,...u])].sort((f,p)=>f.localeCompare(p)),generated_at:$()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cef9096e-5150-5fda-a0b6-cb1376d8c9b3")}catch{}})();var kx=new Set(Ud),Ch=25,Nn=8,Qt=100,Sx=ke.join("runtime","telemetry","events.jsonl"),Ex=ke.join("runtime","telemetry","state.json"),xx=2500,Ix=500,Th=Gd-3,Ax=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function Bs(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function Vs(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Ln(e){return e.trim().toLowerCase()}function Ws(e,t){let n=Ln(e),r=Ln(t);return n.startsWith("builtin-")?!0:r==="beads"||r==="todos"}async function Js(e){try{return(await wt.stat(e)).isDirectory()}catch{return!1}}async function Rx(e){let t=(await wt.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()),n=await Promise.all(t.map(r=>wt.readdir(ke.join(e,r.name),{withFileTypes:!0})));return new Set(n.flatMap(r=>r.filter(i=>i.isFile()).filter(i=>Bn.some(a=>i.name.endsWith(a))).map(i=>ke.parse(i.name).name)))}async function Cx(e,t,n,r){let i=await ze({path:e,scope:"project"}),a=t!=="_workspace"&&!r.has(t);if(!n.enabled&&!a)return{warnings:i,overThreshold:!1,classification:"live"};let o;try{o=await wt.readFile(e,"utf8")}catch{return{warnings:i,overThreshold:!1,classification:"unreadable"}}let s="live";if(a){let l=o.split(/\r?\n/).map(d=>d.trim()).filter(Boolean).at(-1);try{s=JSON.parse(l??"{}").op==="delete"?"tombstone":"orphaned"}catch{s="orphaned"}}let c=n.enabled?o.split(/\r?\n/).filter(l=>l.trim().length>0).length:0;return{warnings:i,overThreshold:n.enabled&&c>n.max_entries,classification:s}}async function Tx(e,t,n){let r=ke.join(e,"history");if(!await Js(r))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let i=(await wt.readdir(r)).filter(d=>d.endsWith(".jsonl")).sort((d,u)=>d.localeCompare(u)),a=t.enabled?t.max_entries:null,o=[],s=[],c=[],l=[];for(let d of i){let u=ke.join(r,d),m=d.slice(0,-6),f=await Cx(u,m,t,n);o.push(...f.warnings),f.classification==="tombstone"&&c.push(m),f.classification==="orphaned"&&l.push(m),f.overThreshold&&s.push(m)}return{count:i.length,warnings:[...o,...s.map(d=>`history_stream_over_compact_threshold:${d}`),...l.map(d=>`history_orphaned_stream:${d}`)],over_threshold:s,max_entries:a,tombstones:c,orphaned:l}}function Gs(e,t){return ke.relative(e,t).replaceAll("\\","/")}async function $h(e,t){let n=[...new Set(Object.values(t))].sort((i,a)=>i.localeCompare(a)),r=[];for(let i of n){let a=ke.join(e,i),o=[];try{o=await wt.readdir(a)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&U(s))continue;continue}for(let s of o)Bn.some(c=>s.toLowerCase().endsWith(c))&&r.push(ke.join(a,s))}return r.sort((i,a)=>Gs(e,i).localeCompare(Gs(e,a))),r}function $x(e){return!(typeof e=="object"&&e!==null&&"code"in e&&U(e))}async function Ox(e,t,n){let r=await $h(e,t),i=[],a=[],o=[],s=[],c=tn(H());for(let l of r){let d=Gs(e,l),u;try{u=await wt.readFile(l,"utf8")}catch{i.push(d);continue}let m=Me(u);if(m){a.push({path:d,...m});continue}try{let f=Et(u,{format:Qc(l),schema:n,extensionFieldNames:c});s.push({ref:d,version:ti(f.metadata)})}catch{o.push(d)}}return{paths:r,unreadable:i,conflictMarkers:a,parseFailures:o,formatVersions:s}}async function Dx(e){let t=ke.join(e,"history"),n=[],r=[],i=[],a=[],o=[],s=[];try{s=(await wt.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,l)=>c.localeCompare(l))}catch(c){$x(c)&&n.push("history")}for(let c of s){let l=c.slice(0,-6),d;try{d=await wt.readFile(ke.join(t,c),"utf8")}catch{n.push(l);continue}let u=Me(d);if(u){r.push({id:l,...u});continue}d.split(/\r?\n/).forEach((m,f)=>{if(m.trim())try{let p=JSON.parse(m);a.push(...yh(p,l).map(h=>({itemId:l,line:f+1,...h}))),o.push(...wh(p,l,f+1))}catch{i.push({id:l,line:f+1})}})}return{files:s,unreadable:n,conflictMarkers:r,invalidJson:i,mergeReceiptReferences:a,mergeReceiptDispositions:o}}function Oh(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function Px(e,t,n,r,i,a){let o=await Ox(e,t,n),s=await Dx(e),c=ni(o.formatVersions),l=_e(n),d=gi(a,I=>Wl(I,l),Xn()),u=await ia(e),m=await et(e),f=await Yf(e,m,r,i),p=m===null?null:await An(m),h=await gt(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),_=new Set(h.receipts.map(I=>I.id)),w=vh(s.mergeReceiptReferences,_,s.mergeReceiptDispositions),v=w.missing,S=h.receipts.filter(I=>I.state==="pending"),{pendingDecisions:k,lossless:x}=Pn(S),D=p?.status==="missing"&&p.missing_keys.length===5&&p.drifted_keys.length===0,E=[...o.unreadable.map(I=>`integrity_item_unreadable:${I}`),...o.conflictMarkers.map(I=>`integrity_item_conflict_marker:${I.path}:L${I.line}`),...o.parseFailures.map(I=>`integrity_item_parse_failed:${I}`),...s.unreadable.map(I=>`integrity_history_unreadable:${I}`),...s.conflictMarkers.map(I=>`integrity_history_conflict_marker:${I.id}:L${I.line}`),...s.invalidJson.map(I=>`integrity_history_invalid_json:${I.id}:L${I.line}`),...c.outdated.map(I=>`integrity_item_outdated_format_version:${I}`),...c.ahead.map(I=>`integrity_item_ahead_format_version:${I}`),...Oh(d),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...p!==null&&p.status!=="ok"?[`merge_driver_configuration_${D?"missing":"drift"}:${p.missing_keys.length+p.drifted_keys.length}`]:[],...f.warnings,...k.length>0?[`merge_decisions_unreviewed:${k.length}`]:[],...x.length>0?[`merge_receipts_pending:${x.length}`]:[],...Xf({invalidEvidenceCount:h.invalid_evidence_count,missingHistoryReferenceCount:v.length})],b=[...new Set(E)].sort((I,R)=>I.localeCompare(R)),N=b.filter(I=>!I.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:N.length===0?"ok":"warn",ok:N.length===0,details:{checked_item_files:o.paths.length,checked_history_streams:s.files.length,counts:{item_unreadable:o.unreadable.length,item_conflict_markers:o.conflictMarkers.length,item_parse_failures:o.parseFailures.length,history_unreadable:s.unreadable.length,history_conflict_markers:s.conflictMarkers.length,history_invalid_json:s.invalidJson.length,item_outdated_format_version:c.outdated.length,item_ahead_format_version:c.ahead.length,hierarchy_cycles:d.cycles.length,hierarchy_cardinality_violations:d.cardinality_violations.length,hierarchy_parent_divergences:d.divergences.length,tracked_runtime_cache_files:u.tracked_path_count,merge_driver_configuration:p===null||p.status==="ok"?0:p.missing_keys.length+p.drifted_keys.length,merge_fence:f.count,pending_merge_decisions:k.length,lossless_merge_receipts:x.length,invalid_merge_receipt_evidence:h.invalid_evidence_count,missing_merge_receipt_history_references:v.length,accepted_legacy_merge_receipt_references:w.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:w.acceptedDispositionCount},item_unreadable:o.unreadable,item_conflict_markers:o.conflictMarkers,item_parse_failures:o.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,hierarchy_integrity:{...d,relations:it(d.relations,Nn)},history_unreadable:s.unreadable,history_conflict_markers:s.conflictMarkers,history_invalid_json:s.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:p===null?null:{...p,required:i},merge_fence:f.audit,pending_merge_decision_items:[...new Set(k.map(I=>I.item_id))].sort((I,R)=>I.localeCompare(R)),lossless_merge_receipt_items:[...new Set(x.map(I=>I.item_id))].sort((I,R)=>I.localeCompare(R)),invalid_merge_receipt_evidence_details:h.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:h.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:v.slice(0,Qt),missing_merge_receipt_history_reference_details_truncated:v.length>Qt}},warnings:b,gitWorkspaceRoot:m,pendingMergeReceipts:S}}function Nx(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function Lx(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:Nx(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function Mx(e,t){return ee(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function jx(e){let t=ee(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function Fx(e){return ee(e.reason)??ee(e.error)??ee(e.message)}function Hs(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let r=(e.name??"").localeCompare(t.name??"");return r!==0?r:(e.id??"").localeCompare(t.id??"")}function Ux(e){let t=[],n=[],r=[];e.forEach((a,o)=>{let s=Mx(a.definition,o),c=jx(a.definition);if(c==="applied"){t.push({layer:a.layer,name:a.name,id:s,status:c});return}if(c==="failed"){r.push({layer:a.layer,name:a.name,id:s,status:c,reason:Fx(a.definition)});return}n.push({layer:a.layer,name:a.name,id:s,status:c})}),t.sort(Hs),n.sort(Hs),r.sort(Hs);let i=[...r.map(a=>`extension_migration_failed:${a.layer}:${a.name}:${a.id}`),...n.map(a=>`extension_migration_pending:${a.layer}:${a.name}:${a.id}`)];return{summary:{applied:t,pending:n,failed:r,applied_count:t.length,pending_count:n.length,failed_count:r.length},warnings:i}}function Dh(e,t,n,r,i,a,o,s,c){let l=[...new Set(e)].sort((_,w)=>_.localeCompare(w)),d=[...new Set(l.map(_=>Vs(_)))].sort((_,w)=>_.localeCompare(w)),u=l.filter(_=>_.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=[],h=us(l,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&p.push(h),t>0&&p.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&p.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(r.failed_count>0||r.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),i>0&&p.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&p.push(`Unknown extension capabilities detected. Allowed capabilities: ${Ur.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),l.some(_=>_.startsWith("extension_capability_legacy_alias:"))&&p.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),l.some(_=>_.startsWith("extension_command_definition_legacy_handler_alias:"))&&p.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?p.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):o.length>0&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:l.length===0?"ok":"warn",warning_count:l.length,warning_codes:d,load_failure_count:t,activation_failure_count:n,migration_failed_count:r.failed_count,migration_pending_count:r.pending_count,managed_state_warning_count:i,managed_extension_entries_count:a,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:s.length,unmanaged_expected_extensions:s,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:f,update_health_partial:m,unknown_capability_count:u,top_warnings:l.slice(0,8),remediation:p}}async function Hx(e,t,n){let r=await _s(Ve(e)),i=await Je({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),a=i.loaded.map(E=>Lx(E)),o=await Ju(i.loaded,Ve(e)),s=await Ke({...i,loaded:i.loaded}),[c,l]=await Promise.all([be(i.roots.project),be(i.roots.global)]);await hs(e,s.registrations.migrations);let d=Ux(s.registrations.migrations),u={failed:s.failed,warnings:s.warnings,hook_counts:s.hook_counts,command_override_count:s.command_override_count,command_handler_count:s.command_handler_count,parser_override_count:s.parser_override_count,preflight_override_count:s.preflight_override_count,service_override_count:s.service_override_count,renderer_override_count:s.renderer_override_count,registration_counts:s.registration_counts,registrations:s.registrations,migration_status:d.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:l.path,count:l.state.entries.length,entries:l.state.entries}}},m=new Set(c.state.entries.map(E=>Ln(E.name))),f=new Set(l.state.entries.map(E=>Ln(E.name))),p=[...new Map(i.loaded.filter(E=>!(E.layer==="project"?m:f).has(Ln(E.name))).map(E=>[`${E.layer}:${E.name}`,{layer:E.layer,name:E.name,directory:E.directory}])).values()].sort((E,b)=>{let N=`${E.layer}:${E.name}`,I=`${b.layer}:${b.name}`;return N.localeCompare(I)}),h=p.map(E=>`${E.layer}:${E.name}`).sort((E,b)=>E.localeCompare(b)),_=p.filter(E=>Ws(E.name,E.directory)).map(E=>`${E.layer}:${E.name}`).sort((E,b)=>E.localeCompare(b)),w=p.filter(E=>!Ws(E.name,E.directory)).map(E=>`${E.layer}:${E.name}`).sort((E,b)=>E.localeCompare(b)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],S=[...r.warnings,...i.warnings,...u.warnings,...d.warnings,...c.warnings,...l.warnings,...v,...o.warnings],k=vr(S),x=br(),D=Dh(S,i.failed.length,s.failed.length,d.summary,c.warnings.length+l.warnings.length,c.state.entries.length+l.state.entries.length,h,_,w);return{check:{name:"extensions",status:S.length===0?"ok":"warn",ok:S.length===0,details:{...i,loaded:a,warnings:S,activation:u,author_manifest:r,triage:D,...d.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:x,capability_guidance:k,host_version_census:o}},warnings:S}}function zx(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function it(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function Wx(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function pa(e,t){let n=it(e,t);return{...n,sample:n.sample.map(r=>Wx(r))}}function q(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(r=>typeof r=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function Gx(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var qx={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:q(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:q(e.missing_required,t),missing_optional:q(e.missing_optional,t),missing:q(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:q(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:pa(e.discovered,t),effective:pa(e.effective,t),loaded:pa(e.loaded,t),failed:it(e.failed,t),warnings:q(e.warnings,t),activation:{failed:it(n.failed,t),warnings:q(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:Gx(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:it(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:q(n.affected_item_ids,t),samples:it(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:q(e.item_unreadable,t),item_conflict_markers:it(e.item_conflict_markers,t),item_parse_failures:q(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:q(n.tracked_paths,t)},history_unreadable:q(e.history_unreadable,t),history_conflict_markers:it(e.history_conflict_markers,t),history_invalid_json:it(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:q(n.candidate_items,t),confirmed_items:q(n.confirmed_items,t),resolved_false_positive_items:q(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:q(e.drifted_items,t),merge_receipt_attributed_items:q(e.merge_receipt_attributed_items,t),missing_streams:q(e.missing_streams,t),unreadable_streams:q(e.unreadable_streams,t),hash_mismatches:q(e.hash_mismatches,t),chain_mismatches:q(e.chain_mismatches,t),version_skews:q(e.version_skews,t),workspace_state_mismatches:q(e.workspace_state_mismatches,t),workspace_state_missing:q(e.workspace_state_missing,t),workspace_state_unreadable:q(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:q(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:q(e.stale_items_after,t),skipped:e.skipped})};function Ph(e,t){let n=qx[e.name];return n?n(e.details,t):e.details}function Bx(e){let t=q(e.warnings,Nn);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:Ph(n,Nn)})),warnings:t.sample,findings:e.findings.filter(n=>t.sample.includes(n.warning)||e.failed_because.includes(n.warning)),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:Nn},generated_at:e.generated_at}}function Rh(e){return e.details.skipped===!0}function Vx(e){let t=q(e.warnings,Nn),n=e.checks.filter(Rh).map(r=>r.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(r=>!Rh(r)).map(r=>({name:r.name,status:r.status,ok:r.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:e.findings.filter(r=>t.sample.includes(r.warning)||e.failed_because.includes(r.warning)),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:Nn,omitted_checks:n},generated_at:e.generated_at}}function qs(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=zx(e,Ch);return{values:n.values,truncated:n.truncated,total:e.length}}function fa(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Jx(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return kx.has(e)?e:null}function ha(e){let t=e.trim();if(t.length===0)return"";try{let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return t}}function Nh(e){let t=0,n=0,r=0,i=0,a=0;for(let o of e.split(`
65
+ `)){let s=o.trim();if(s.length!==0){r+=1;try{let c=JSON.parse(s);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let l=Math.max(0,Math.trunc(c.attempts));t+=1,a=Math.max(a,l),l>=Th&&(i+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:r,highRetryEntries:i,maxAttempts:a}}function Kx(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function Yx(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function Xx(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||ao().telemetry_disabled?void 0:{attempted:!0,...await Lh(n)}}function Zx(e,t,n){let r=[];if(t.invalidRows>0&&r.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return r;let i=n.last_successful_flush_at,a=n.last_failed_flush_at,o=a&&(!i||a>i),s=!i,c=t.validEntries>=Ix;return(o||s||c)&&r.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&r.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),r}function Qx(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function eI(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Wd?[`telemetry_schema_version_behind:${t}`]:[]}function tI(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,r=t.last_otel_success_at,i=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&i&&(!r||i>=r)?[`telemetry_otel_export_failing:${n}`]:[]}function nI(){return{...ao(),pm_no_telemetry:fa("PM_NO_TELEMETRY"),telemetry_otel_disabled:fa("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:fa("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:Jx()}}function rI(e,t){return e.telemetry.enabled&&t.validEntries>0}function iI(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Lh(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(xx)});return{probe_url:ha(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let r of Ax){let i=n.headers.get(r)?.trim();if(i&&i.length>0)return i}})()}}catch(n){return{probe_url:ha(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function aI(e,t){let n=Wr(process.cwd()),r=ke.join(n,Sx),i=ke.join(n,Ex),a=await V(r),o=a!==null,s=a?Buffer.byteLength(a,"utf8"):0,c=a?Nh(a):Kx(),l=await V(i),{runtimeState:d,stateParseFailed:u}=Yx(l),m=e.telemetry.endpoint.trim(),f=ha(m),p=await Xx(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...Zx(e,c,d),...Qx(p),...eI(p),...tI(e,d));let _=rI(e,c),w=typeof d.pending_otel_spans=="number"?d.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:f,global_pm_root:n,queue_path:r,queue_exists:o,queue_entries:c.validEntries,queue_draining:iI(_,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:s,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:Th,queue_max_attempts:c.maxAttempts,runtime_state_path:i,last_attempted_flush_at:d.last_attempted_flush_at??null,last_successful_flush_at:d.last_successful_flush_at??null,last_failed_flush_at:d.last_failed_flush_at??null,last_failed_flush_error:d.last_failed_flush_error??null,pending_otel_spans:w,last_otel_attempt_at:d.last_otel_attempt_at??null,last_otel_success_at:d.last_otel_success_at??null,last_otel_failure_at:d.last_otel_failure_at??null,last_otel_failure_error:d.last_otel_failure_error??null,endpoint_probe:p??{attempted:!1},env_overrides:nI()}},warnings:h}}async function oI(e){let t;try{t=await km(e)}catch(r){let i=r instanceof Error?r.message:String(r);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:i,pm_root:e}},warnings:[`locks_scan_failed:${i}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function sI(e){let t="metadata",n=e.items,r=await qt(e.pmRoot,n,{cacheHitVerification:t}),i=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((w,v)=>w.localeCompare(v)),a=[],o=[];if(i.length>0){n=await zt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),r=await qt(e.pmRoot,n),a=[...new Set([...r.hashMismatches,...r.chainMismatches,...r.versionSkews])].sort((v,S)=>v.localeCompare(S));let w=new Set(a);o=i.filter(v=>!w.has(v))}let{missingStreams:s,unreadableStreams:c,hashMismatches:l,chainMismatches:d,versionSkews:u,driftedItems:m,workspaceStateMismatches:f,workspaceStateMissing:p,workspaceStateUnreadable:h}=r,_=[...s.map(w=>`history_drift_missing_stream:${w}`),...c.map(w=>`history_drift_unreadable_stream:${w}`),...l.map(w=>`history_drift_hash_mismatch:${w}`),...d.map(w=>`history_drift_chain_mismatch:${w}`),...u.map(w=>`history_drift_version_skew:${w}`),...f.map(w=>`history_drift_workspace_state_mismatch:${w}`),...p.map(w=>`history_drift_workspace_state_missing:${w}`),...h.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:_.length===0?"ok":"warn",ok:_.length===0,details:{checked_items:n.length,cache_hit_verification:i.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:i.length>0,reason:i.length>0?"cached_corruption_candidate":null,candidate_items:i,confirmed_items:a,resolved_false_positive_items:o,authoritative_item_source:i.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:s.length,unreadable_streams:c.length,hash_mismatches:l.length,chain_mismatches:d.length,version_skews:u.length,workspace_state_mismatches:f.length,workspace_state_missing:p.length,workspace_state_unreadable:h.length},missing_streams:s,unreadable_streams:c,hash_mismatches:l,chain_mismatches:d,version_skews:u,workspace_state_mismatches:f,workspace_state_missing:p,workspace_state_unreadable:h}},warnings:_}}function cI(e,t){let n=fi(e),r=Yn(n.settings),i=_i(n.settings,t),a=r.active?Wt(r.active.name,r.active.model):null;return{runtimeDefaults:n,providerResolution:r,vectorStoreResolution:i,runtimeEmbeddingIdentity:a,semanticRuntimeAvailable:!!(r.active&&i.active)}}function lI(){return{refreshed:[],skipped:[],warnings:[]}}async function dI(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?lI():Fd(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function uI(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&hn(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function mI(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,r)=>n.localeCompare(r))}function pI(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Mh(e,t){let n=t.providerResolution.active?.name??null,r=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:no(n,e.search?.provider??null),vector_store_active:r,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:no(r,e.vector_store?.adapter??null)}}function fI(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function hI(e,t,n){return e.enabled&&n.length>0&&t}async function _I(e,t,n,r,i){let a=cI(t,e),o=await _n(e),s=a.semanticRuntimeAvailable?so(n,o.entries):[],c=await dI({pmRoot:e,snapshot:a,refreshPolicy:r,staleBefore:s}),l=await _n(e),d=a.semanticRuntimeAvailable?so(n,l.entries):[],u=!a.runtimeDefaults.auto_ollama_defaults_applied,m=uI({strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:a.runtimeEmbeddingIdentity}),f=mI({ledgerBefore:o,ledgerAfter:l,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:d}),p=qs(s,i),h=qs(d,i),_=hI(r,a.semanticRuntimeAvailable,s);return{check:{name:"vectorization",status:f.length===0?"ok":"warn",ok:f.length===0,details:{semantic_runtime_available:a.semanticRuntimeAvailable,compatibility_mode_auto_defaults:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:a.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:a.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:fI(r),...Mh(t,a),embedding_identity_changed:m,embedding_identity_before:o.embedding??null,embedding_identity_runtime:a.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:i?"full":"summary",stale_items_summary_limit:Ch,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:_,refresh_skipped_reason:pI(r,a.semanticRuntimeAvailable,s),refresh_result:c,ledger_entries_after:Object.keys(l.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:f}}function gI(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function jh(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new y("--check-only cannot be combined with --refresh-vectors",g.USAGE);if(n&&e.noRefresh===!0)throw new y("--no-refresh cannot be combined with --refresh-vectors",g.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var yI=new Set(["extensions","locks","search"]);function wI(e){let t=new Set(zc.filter(i=>i.length>0)),n=new Set,r=new Set(Object.values(Wc));for(let i of e.folders)t.has(i)&&!r.has(i)||(t.delete(i),n.add(i));for(let i of yI)t.delete(i),n.add(i);return{requiredDirs:[...t].sort((i,a)=>i.localeCompare(a)),optionalDirs:[...n].sort((i,a)=>i.localeCompare(a)),optionalDirSet:n}}async function vI(e,t,n){let{requiredDirs:r,optionalDirs:i,optionalDirSet:a}=wI(t),o=[],s=[],c=[];for(let l of[...r,...i]){let d=ke.join(e,l);c.push(...await ze({path:d,scope:"project"})),!await Js(d)&&(a.has(l)?s.push(l):o.push(l))}return{requiredDirs:r,optionalDirs:i,missingRequiredDirs:o,missingOptionalDirs:s,missingDirs:n?[...o,...s]:[...o],hookWarnings:c}}function Fh(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,r=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||r)&&e.full!==!0,skipDrift:(e.skipDrift===!0||r)&&e.full!==!0,skipVectors:(e.skipVectors===!0||r)&&e.full!==!0}}async function bI(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?st(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):zt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function zs(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function kI(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function SI(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function EI(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var Ks=e=>e.unknown_event_count??0,Ys=e=>e.actionable_unknown_event_count??Ks(e);function xI(e,t,n,r,i,a){let o=Ks(r),s=Ys(r),c=o>0,l=s>0,d=i.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!d?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!l&&!d,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...c?{author_attribution:r}:{},...d?{stale_in_progress:i}:{},...a.outcomes.length>0?{provenance_resolver_outcomes:a.outcomes}:{},...a.invalid_values.length>0?{provenance_invalid_values:a.invalid_values}:{},provenance_sample:a.sample,...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function Uh(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function II(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function AI(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function RI(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function Hh(e){let t=new Map;for(let[r,i]of Object.entries(e.remediationSources))for(let a of i)t.has(a)||t.set(a,r);let n=new Map(e.checks.map(r=>[r.name,r]));return e.warnings.map(r=>{let i=t.get(r)??"integrity",a=$o(r)?.code??Vs(r),o=n.get(i)?.details,s=typeof o?.remediation_map=="object"&&o.remediation_map!==null?o.remediation_map:{},c=a==="agent_guidance_outdated"?"pm init --agent-guidance add":a==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":s[a],l=Bs(r,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:r,code:a,check:i,severity:l,...typeof c=="string"?{remediation:c}:l==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function CI(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&t!=="history_drift_version_skew"&&(e.remediationMap[t]="pm history-repair --all");if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function TI(e){for(let t of e.checks){let n=Oo(e.remediationSources[t.name]);CI({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function $I(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(o=>typeof o=="string"):[],r=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(o=>Array.isArray(o)?o:[])),i=new Map;for(let o of e.pendingMergeReceipts){if(o.evidence_source!=="clone_local")continue;let s=i.get(o.item_id)??[];s.push(o),i.set(o.item_id,s)}let a=[];for(let o of n){if(r.has(o))continue;let s=i.get(o);if(!(!s||s.length===0))try{await Us(o,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:s}},e.global),a.push(o)}catch{}}return[...new Set(a)].sort((o,s)=>o.localeCompare(s))}function OI(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(r=>r.startsWith("history_drift_hash_mismatch:")?!n.has(r.slice(r.indexOf(":")+1)):!0),...t.map(r=>`history_drift_merge_receipt:${r}`)].sort((r,i)=>r.localeCompare(i)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}function zh(e,t,n){let r=e.warning_count??e.warnings.length,i={...e,warning_count:r,warning_limit:Qt,warnings_truncated:r>Qt,warnings:e.warnings.slice(0,Qt),findings:(e.findings??[]).filter(o=>e.warnings.slice(0,Qt).includes(o.warning)||e.failed_because.includes(o.warning))},a=n?Vx(i):t.brief===!0?Bx(i):i;return{...a,warning_count:r,warning_limit:Qt,warnings_truncated:r>a.warnings.length,...a.projection?{projection:{...a.projection,warning_count:r,warnings_truncated:r>a.warnings.length}}:{}}}async function Wh(e,t={}){let n=L(process.cwd(),e.path);await te(n);let r=Lt(n),{settings:i,warnings:a}=await sd(n),o=[...new Set(a)],s=W(i,H()),c=t.strictDirectories===!0,l=t.strictExit===!0||t.failOnWarn===!0,d=t.requireMergeDrivers===!0||l,u=jh(t),m=await vI(n,s,c),f=gI(i),p=await aI(i,{checkTelemetry:t.checkTelemetry===!0}),h=await Hx(n,i,!!e.noExtensions),_=Fh(t),w=[],v=await bI({pmRoot:n,settings:i,typeRegistry:s,skipPolicy:_,itemReadWarnings:w}),S=v,k=Oi(_e(i.schema),v),x=[...(await um({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:i}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(pe=>pe.startsWith("agent_guidance_")),...f,...Di(k)],D=_.skipDrift?{warnings:[]}:await _d({pmRoot:n,settings:i,itemIds:v.map(pe=>pe.id),commandLabel:"health"}),E=await Tx(n,i.history.compact_policy,await Rx(n)),b=await ir(n,20,t.verboseAuthorEvents===!0),N=Ys(b),I=N>0?[`history_unknown_author_events:${N}`]:[],R=Uh(await Hd(n,v,{in_progress_status:i.schema.workflow.in_progress_status,threshold_hours:i.mutation_guard.stale_in_progress_hours})),Q=await em(n),xe=Q.warnings,ye=await oI(n),he=_.skipIntegrity&&!d?{...zs("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await Px(n,s.type_to_folder,i.schema,i,d,v),He=_.skipDrift?zs("history_drift"):await sI({pmRoot:n,items:S,settings:i,typeRegistry:s,itemReadWarnings:w}),Mr=[...new Set(w)],Gn=await $I({gitWorkspaceRoot:he.gitWorkspaceRoot,pendingMergeReceipts:he.pendingMergeReceipts,historyDriftCheck:He,global:e});OI(He,Gn);let z=_.skipVectors?zs("vectorization"):await _I(n,i,S,u,t.verboseStaleItems===!0),B=[kI(r,i,o),SI(m,c),EI(x,k),p.check,h.check,xI(v,i,E,b,R.scan,Q),ye.check,he.check,He.check,z.check],jr=II({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:x,normalizedItemReadWarnings:Mr,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:D.warnings,historySummary:E,authorAttributionWarnings:I,staleInProgressWarnings:R.warnings,provenanceWarnings:xe,locksCheck:ye,integrityCheck:he,historyDriftCheck:He,vectorizationCheck:z}),Fr=RI({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:x,normalizedItemReadWarnings:Mr,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:D.warnings,historySummary:E,authorAttributionWarnings:I,staleInProgressWarnings:R.warnings,provenanceWarnings:xe,locksCheck:ye,integrityCheck:he,historyDriftCheck:He,vectorizationCheck:z});TI({checks:B,remediationSources:Fr,historyDriftedCount:AI(He),overThresholdCount:E.over_threshold.length});let Pa=jr.filter(pe=>!Bs(pe,d)),Na=Hh({warnings:jr,checks:B,remediationSources:Fr,requireMergeDrivers:d}),jg=new Set(Na.filter(pe=>pe.severity==="gate_failing").map(pe=>pe.check)),Fg=new Set(Na.map(pe=>pe.check));for(let pe of B)pe.ok=!jg.has(pe.name),Fg.has(pe.name)&&(pe.status="warn");let Ug={ok:Pa.length===0,verdict:{authority:"ok",...l?{strict_exit:!0}:{},...d?{require_merge_drivers:!0}:{},exit_code:l&&Pa.length>0?g.GENERIC_FAILURE:0},checks:B,warnings:jr,findings:Na,failed_because:Pa,generated_at:$()};return zh(Ug,t,_.summaryMode)}var kU={buildHierarchyIntegrityWarnings:Oh,buildExtensionHealthTriageSummary:Dh,buildHealthFindings:Hh,buildCapabilityContractMetadata:br,buildStaleInProgressHealthSummary:Uh,buildVectorizationProviderDetails:Mh,collectUnknownCapabilityGuidance:vr,isAdvisoryHealthWarning:Bs,isDirectory:Js,isExpectedUnmanagedExtension:Ws,listItemDocumentPaths:$h,normalizeEndpointForDisplay:ha,normalizeExtensionNameForMatch:Ln,parseTelemetryQueue:Nh,probeTelemetryEndpointHealth:Lh,projectHealthResult:zh,resolveActionableUnknownAuthorEventCount:Ys,resolveHealthSkipPolicy:Fh,resolveUnknownAuthorEventCount:Ks,resolveVectorRefreshPolicy:jh,selectStaleItemDetail:qs,summarizeHealthCheckDetails:Ph,summarizeExtensionList:pa,summarizeRecordList:it,summarizeStringList:q,telemetryEnvFlagEnabled:fa,warningCode:Vs};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a07d2f98-7c1d-5d0a-be70-5181ed0f7b4f")}catch{}})();function Gh(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!Kd(e,t).ok)return{reason:"unverified_history"};let r=ed(),i={reason:"no_proven_transition"};for(let[a,o]of e.entries()){let s=n.has(String(r.metadata.status));r=yd(r,o.patch,a+1,o.op),n.has(String(r.metadata.status))?s||(i=["create","close","cancel","update","update_audit"].includes(o.op)&&St(o.ts)?{timestamp:o.ts,source_index:a+1}:{reason:"no_proven_transition"}):i={reason:"no_proven_transition"}}return i}function qh(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function Bh(e,t,n,r,i){let a=qh(n),o=t.filter(l=>a.has(l.status)&&!l.closed_at),s=[],c=[];for(let l of r?o:[]){let d;try{let u=await Ut(Mt(e,l.id),l.id),{body:m,...f}=l;d=Gh(u,{metadata:f,body:m},a)}catch{c.push({id:l.id,reason:"unreadable_history"});continue}if("reason"in d){c.push({id:l.id,reason:d.reason});continue}s.push({item_id:l.id,check:"metadata",field:"closed_at",kind:"set_closed_at",value:d.timestamp,gate:"timestamps",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps"})}return{details:{missing_closed_at_count:o.length,missing_closed_at_item_ids:o.slice(0,i).map(l=>l.id),missing_closed_at_item_ids_truncated:o.length>i,closure_history_inspected:r,closure_timestamp_derivable_count:s.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,i),closure_timestamp_residual_truncated:c.length>i,...o.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:s,warnings:o.length>0?[`validate_metadata_missing_closed_at:${o.length}`]:[]}}async function Vh(e,t){let n=L(process.cwd(),t.path),r=await C(n),i=_e(r.schema);await ct({pmRoot:n,settings:r,id:e.item_id,op:"update",author:G(t.author,r.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(a){if(a.metadata.closed_at)return{changedFields:[]};let o=await Ut(Mt(n,a.metadata.id),a.metadata.id),s=qh(i),c=Gh(o,a,s);if(!("timestamp"in c)||c.timestamp!==e.value)throw new y("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",g.GENERIC_FAILURE);return a.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34d28b31-b098-5ffd-b39b-2e11de150ac1")}catch{}})();function DI(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function Jh(e){return`${e.item_id} ${e.link_kind}`}function Kh(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=DI(i.classification,r.classification),i.owners.set(Jh(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[Jh(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(a=>{let o=t(a.item_id);return{id:a.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:a.link_kind}}).sort((a,o)=>{let s=a.id.localeCompare(o.id);return s!==0?s:a.field.localeCompare(o.field)})}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="00f8052d-480b-5e38-86cf-4574a8ad1e92")}catch{}})();function Yh(e,t,n,r,i=40){let a=i===1/0?1/0:Number.isFinite(i)?Math.max(0,Math.floor(i)):40,o=new Map(t.map(l=>[l.path,l])),s={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=Kh(e,n).map(l=>{let d=[],u=[];for(let f of l.items){let p=ri(f.status,r)??f.status;r.terminal_statuses.has(p)?(u.push(f),p===r.close_status&&(s.legacy_closed_missing_linked_links_count+=1)):d.push(f)}s.missing_linked_links_count+=l.items.length,s.active_missing_linked_links_count+=d.length,s.legacy_terminal_missing_linked_links_count+=u.length,d.length>0&&(s.active_missing_linked_paths_count+=1);let m=o.get(l.path);return{...l,candidates:m?.candidates??[],candidates_truncated:m?.candidates_truncated??!1,link_count:l.items.length,active_link_count:d.length,items:[...d,...u].slice(0,a),items_truncated:l.items.length>a}});return c.sort((l,d)=>+(d.active_link_count>0)-+(l.active_link_count>0)||l.path.localeCompare(d.path)),s.missing_linked_path_rows_count=c.length,s.missing_linked_path_rows=c.slice(0,a),s.missing_linked_path_rows_truncated=c.length>a,s}import Mn from"node:fs/promises";import jn from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7ff2e182-d84c-5e1c-8b63-daea17d55af4")}catch{}})();async function PI(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let a;try{a=await Mn.readdir(jn.join(e,i))}catch{return}for(let o of a)for(let s of Bn)if(o.toLowerCase().endsWith(s)){r.push({relativePath:`${i}/${o}`,id:o.slice(0,-s.length)});break}})),r.sort((i,a)=>i.relativePath.localeCompare(a.relativePath))}function NI(e,t){let{id:n,relativePath:r,liveItemIds:i,out:a}=e,o=Me(t);if(o){a.conflictMarkers.push({id:n,path:r,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let s=LI(e,t);s!==null&&(s.op==="delete"&&i.has(n)&&a.resurrected.push({id:n,deleted_at:typeof s.ts=="string"?s.ts:"",deleted_by:typeof s.author=="string"?s.author:""}),s.op==="history_repair"&&Array.isArray(s.patch)&&s.patch.length>0&&(a.repairReconciliations+=1))}function LI(e,t){let{id:n,relativePath:r,out:i}=e,a=null,o=!1,s=t.split(/\r?\n/).map((c,l)=>({content:c.trim(),number:l+1})).filter(c=>c.content.length>0);for(let c of s){try{let l=JSON.parse(c.content);if(typeof l!="object"||l===null||Array.isArray(l))throw new TypeError("history entry must be an object");a=l}catch{return i.unparseable.push({id:n,path:r,line:c.number,detail:"history line is not a valid JSON object"}),null}if(a.op==="create"){if(o)return i.unparseable.push({id:n,path:r,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;o=!0}}return a}function Xs(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function MI(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await Mn.readdir(jn.join(e,"history"))}catch{return n}for(let i of r.sort((a,o)=>a.localeCompare(o))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let a;try{a=await Mn.readFile(jn.join(e,"history",i),"utf8")}catch(o){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:Xs("history stream",o)});continue}NI({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},a)}return n}function Xh(e){let t=Me(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function jI(e){let t=[],n=0,r=null;try{r=await V(Lt(e))}catch(a){n+=1,t.push({path:"settings.json",detail:Xs("configuration file",a)})}if(r!==null){n+=1;let a=Xh(r);a!==null&&t.push({path:"settings.json",detail:a})}let i;try{i=await Mn.readdir(jn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let a of i.sort((o,s)=>o.localeCompare(s))){if(!a.endsWith(".json"))continue;n+=1;let o;try{o=await Mn.readFile(jn.join(e,"schema",a),"utf8")}catch(c){t.push({path:`schema/${a}`,detail:Xs("configuration file",c)});continue}let s=Xh(o);s!==null&&t.push({path:`schema/${a}`,detail:s})}return{scanned:n,unparseable:t}}async function Zh(e,t,n,r={}){let i=await PI(e,n),a=new Set(i.map(u=>u.id)),o=new Map;for(let u of i){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let s=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,p)=>f.localeCompare(p))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=jn.join(e,u.relativePath);return Et(await Mn.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),l=await MI(e,a),d=await jI(e);return{item_files_on_disk:i.length,item_ids_on_disk:a.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:s,history_streams_scanned:l.scanned,history_conflict_marker_streams:l.conflictMarkers,history_unparseable_streams:l.unparseable,resurrected_items:l.resurrected,history_repair_reconciliations:l.repairReconciliations,config_files_scanned:d.scanned,unparseable_config_files:d.unparseable}}import Sc from"node:fs/promises";import{realpathSync as XA}from"node:fs";import{execFile as ZA}from"node:child_process";import Ee from"node:path";import{promisify as QA}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8c3bbe6d-dcce-5b1a-8352-1472ab1ed6e2")}catch{}})();var FI=["metadata","resolution"],Zs=["metadata","resolution","estimates","timestamps","lifecycle"],UI="completed";function Qs(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Qh(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function e_(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Qh(n.close_reason)??UI;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${Qs(r)}`,gate:"resolution"})}return t}function t_(e){let t=[];for(let n of e){let r=Qh(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${Qs(r)}`,gate:"metadata"})}return t}function n_(e,t){return e.map(n=>{let r=od(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function r_(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function i_(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${Qs(n.path)}`})}return t}function a_(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new y(`--fix-scope values must not be empty. Supported values: ${Zs.join(", ")}.`,g.USAGE);return new Set(FI)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(Zs.includes(i)){n.add(i);continue}throw new y(`Unknown --fix-scope value "${r}". Supported values: ${Zs.join(", ")}.`,g.USAGE)}return n}function o_(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function Rr(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e93db1eb-e524-58bf-af2e-cb5f22f3047b")}catch{}})();var HI=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function zI(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=HI.exec(n);if(!r)return null;let i=r[1],a=i.toUpperCase(),o=i.slice(0,i.lastIndexOf("-")),s=new Set((t.configuredPrefixes??[]).map(u=>u.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(i.length),l=t.evidenceText?.toUpperCase()??"",d=l.includes(`ISSUE CODE: ${a}`)||l.includes(`ISSUE CODE \`${a}\``)||l.includes(`\`${a}\``)||l.includes(`[${a}]`);return o===o.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||s.has(o.toUpperCase())||d?a:null}function s_(e){return typeof e=="string"&&e.trim().length>0}function WI(e){let t=new Set(e.map(o=>o.id.toLowerCase())),n=new Map,r=new Map;for(let o of e){let s=o.id.toLowerCase(),c=new Set([...o.parent===null?[]:[o.parent.toLowerCase()],...o.derivations].filter(l=>l!==s&&t.has(l)));n.set(s,c);for(let l of c){let d=r.get(l)??[];d.push(s),r.set(l,d)}}let i=[...[...n].filter(([,o])=>o.size===0).map(([o])=>o)],a=new Set;for(let o=0;o<i.length;o+=1)for(let s of r.get(i[o])??[]){let c=n.get(s);c.delete(i[o]),c.size===0&&(a.add(s),i.push(s))}return e.filter(o=>!a.has(o.id.toLowerCase()))}function c_(e,t={}){let n=new Map;for(let i of e){if(typeof i.title!="string"||s_(i.duplicate_of))continue;let a=zI(i.title,{...t,evidenceText:i.body});if(a===null)continue;let o=n.get(a);o||(o=[],n.set(a,o)),o.some(s=>s.id===i.id)||o.push({id:i.id,title:i.title,parent:s_(i.parent)?i.parent.trim():null,derivations:(i.dependencies??[]).filter(s=>["discovered_from","supersedes","incident_from"].includes(s.kind)).map(s=>s.id.trim().toLowerCase()).filter(s=>s!==i.id.toLowerCase())})}let r=[];for(let[i,a]of n){if(a.length<2)continue;let o=WI(a);if(o.length<2)continue;let s=[...o].sort((c,l)=>c.id.localeCompare(l.id));r.push({code:i,count:s.length,ids:s.map(c=>c.id),titles:s.map(c=>c.title)})}return r.sort((i,a)=>i.code.localeCompare(a.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c32504d-254c-5156-a41f-8ffd8e49107f")}catch{}})();function l_(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,a)=>i.localeCompare(a))){let i=t.get(r),a={};for(let o of[...i.keys()].sort((s,c)=>s.localeCompare(c)))a[o]=i.get(o);n[r]=a}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c577e41b-6642-554a-bc4d-0c22170c1e24")}catch{}})();function d_(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function u_(e,t,n=3){let r=Number.isFinite(n)&&n>=1?Math.floor(n):3,i=new Map;for(let a of t){let o=d_(a);if(o.length===0)continue;let s=i.get(o);s?s.push(a):i.set(o,[a])}return e.map(a=>{if(a.includes(",")||a.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:a,classification:"malformed",candidates:[],candidates_truncated:!1};let o=(i.get(d_(a))??[]).filter(s=>s!==a).sort((s,c)=>s.localeCompare(c));return o.length===0?{path:a,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:a,classification:"moved",candidates:o.slice(0,r),candidates_truncated:o.length>r}})}function m_(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var GI=/^[a-z][a-z0-9+.-]+:\/\//i;function Cr(e){return GI.test(e.trim())}import qI from"node:fs/promises";import Se from"node:path";import{glob as BI}from"tinyglobby";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="12655e94-6304-56cf-9f5d-387a26572db0")}catch{}})();var VI=["path","scope","note"],JI=["pattern","glob","path","scope","note"],KI=["path"],YI=["from","to"],XI=new Set(["note","scope"]);function f_(e){let t=e??"project";if(!La.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${La.join(", ")} (default: project).`,g.USAGE);return t}function ec(e){if(e.startsWith("```")||e.includes(`
66
+ `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(i=>i>=0&&i<r))?!1:n.includes("=")||ud(e)}function ZI(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function QI(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!ec(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let a=e.slice(t+2,-1).trim();if(a.length>0&&ZI(a))return{path:a,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),i=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(i)))return{path:i,scope:"project",note:r}}function eA(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let a=QI(r);if(a!==void 0)return[a]}md(r,"--add",`${t} path`,ec(r));let i=ec(r)?Jn(n,"--add"):{path:r};if(Kn(i,"--add",VI),!i.path)throw new y(`--add requires path=<value> or a bare ${t} path`,g.USAGE);return[{path:i.path,scope:f_(i.scope),note:i.note?.trim()||void 0}]}):[]}function tA(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--add-glob requires a glob pattern value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=Jn(n,"--add-glob");Kn(r,"--add-glob",JI);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new y("--add-glob key/value form requires pattern=<glob>",g.USAGE);return{pattern:i,scope:f_(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function nA(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--remove requires a path value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=Jn(n,"--remove"),i=Object.keys(r).filter(a=>XI.has(a.toLowerCase()));if(i.length>0)throw new y(`--remove identifies a linked artifact by path only and does not accept ${i.map(a=>`"${a}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,g.USAGE);if(Kn(r,"--remove",KI),!r.path)throw new y("--remove key/value form requires path=<value>",g.USAGE);return r.path}return n}):[]}function rA(e){return e?e.map(t=>{let n=Jn(t,"--migrate");Kn(n,"--migrate",YI);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new y("--migrate requires from=<value> and to=<value>",g.USAGE);return{from:r,to:i}}):[]}function Tr(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function iA(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(a=>Tr(a.path,n))),i=[...new Set(t.map(a=>Tr(a,n)).filter(a=>r.has(a)))].sort((a,o)=>a.localeCompare(o));if(i.length!==0)throw new y(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${i.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,g.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function vt(e){return e.split(Se.sep).join("/")}function tc(e,t,n=process.cwd()){let r=e.trim();if(Cr(r))return r;if(Se.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return vt(r.replaceAll("\\",Se.sep));let i=Se.relative(t,n);return i.startsWith(`..${Se.sep}`)||i===".."||Se.isAbsolute(i)?vt(Se.normalize(r)):vt(Se.relative(t,Se.resolve(n,r)))}async function aA(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){if(Se.resolve(n,i.pattern)===Se.resolve(n))continue;let a=Se.isAbsolute(i.pattern),o=await BI(i.pattern,{cwd:n,absolute:a,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),s=[...new Set(o.map(c=>tc(c,t,n)))].sort((c,l)=>c.localeCompare(l));for(let c of s)r.push({path:c,scope:i.scope,note:i.note})}return r}function oA(e,t,n){if(t===void 0)return e;if(!n)throw new y("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",g.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function sA(e){return`${e.path}::${e.scope}`}function nc(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function rc(e){return[...new Map(e.map(t=>[sA(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function cA(e,t=process.cwd()){let n=[...new Set(e)].sort((s,c)=>s.localeCompare(c)),r=[],i=[],a=[],o=[];for(let s of n){if(Cr(s)){o.push(s.trim());continue}let c=Se.isAbsolute(s)?s:Se.resolve(t,s);try{(await qI.stat(c)).isFile()?r.push(s):a.push(s)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&bt(l)){i.push(s);continue}a.push(s)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:a,remote_references:o}}function lA(e,t,n,r){let i=0;for(let a=0;a<e.length;a+=1){let o=Tr(e[a].path,r);o!==e[a].path&&(e[a]={...e[a],path:o},i+=1)}return{adds:t.map(a=>{let o=Tr(a.path,r);return o!==a.path&&(i+=1),{...a,path:o}}),removes:n.map(a=>Tr(a,r)),count:i}}function dA(e,t,n,r){let i=rc(e);for(let a of t){let o=i.findIndex(s=>s.path===a.path&&s.scope===a.scope);o<0?i.push(a):a.note!==void 0&&(i[o]={...i[o],note:a.note})}if(n.length>0)for(let a=i.length-1;a>=0;a-=1)n.includes(i[a].path)&&i.splice(a,1);return r?i:nc(i)}async function p_(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed?await cA(t,e.workspaceRoot):void 0}}async function _a(e,t,n,r){let{metadataKey:i}=r,a=hd(),o=L(process.cwd(),n.path),s=Ve(o),c=process.cwd();await te(o);let l=await C(o),d=W(l,H()),u=await a.resolveList(t.add,"--add"),m=await a.resolveList(t.addGlob,"--add-glob"),f=await a.resolveList(t.remove,"--remove"),p=await a.resolveList(t.migrate,"--migrate"),h=eA(u,r.bareNoun).map(I=>({...I,path:tc(I.path,s,c)})),_=tA(m),w=await aA(_,s,c),v=oA([...h,...w],t.note,h.length>0||_.length>0),S=nA(f).map(I=>tc(I,s,c)),k=rA(p);if(iA(v,S,k),!(v.length>0||S.length>0||k.length>0)){let I=await we(o,e,l.id_prefix,l.item_format,d.type_to_folder);if(!I)throw new y(`Item ${e} not found`,g.NOT_FOUND);let R=(await ve(I,{schema:l.schema})).document.metadata[i]??[];return p_({id:I.id,artifacts:R,changed:!1,options:t,workspaceRoot:s})}let x=G(t.author,l.author_default),D=await ct({pmRoot:o,settings:l,id:e,op:r.op,author:x,message:t.message,force:t.force,skipNoop:!0,mutate(I){let R=I.metadata,Q=R[i]??[],xe=[...Q],ye=lA(xe,v,S,k),he=dA(xe,ye.adds,ye.removes,r.supportsAppendStable&&t.appendStable===!0);he.length>0?R[i]=he:delete R[i];let He=!il(Q,he);return{changedFields:He?[i]:[],warnings:He&&ye.count>0?[`path_migrations_applied:${ye.count}`]:[]}}}),E=D.item[i]??[],b=D.warnings.find(I=>I.startsWith("path_migrations_applied:")),N=b?Number(b.slice(24)):0;return p_({id:D.item.id,artifacts:E,changed:D.changedFields.includes(i),migrationsApplied:N,options:t,workspaceRoot:s})}function ga(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t:r]=i;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="79f1acaf-8ef7-5725-900a-fbeced1c57e6")}catch{}})();async function h_(e,t,n){let r=await _a(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return ga(r,"docs")}import __ from"node:fs/promises";import Ue from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="06b0bd73-d282-5473-a1da-f11c61a0a086")}catch{}})();var uA=32768;function ic(e){return vt(Ue.normalize(e))}async function ya(e){try{return await __.realpath(e)}catch{return Ue.resolve(e)}}function Fn(e,t){let n=Ue.isAbsolute(e.path)?Ue.resolve(e.path):Ue.resolve(t,e.path);return`${ic(n)}::${e.scope}`}function wa(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>wa(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))wa(i,t?`${t}.${r}`:r,n)}function mA(e){let t=[];return wa(e.metadata,"metadata",t),wa(e.body,"body",t),t}function pA(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function fA(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let i of e){let a=new Set,o=i.value.slice(0,uA);for(let[s,c]of[[n,i.value],[r,o]]){s.lastIndex=0;for(let l of c.matchAll(s)){let d=pA(l[0]);!d||a.has(d)||(a.add(d),t.push({field:i.field,value:d}))}}}return t}async function hA(e,t,n=t){let r=Ue.isAbsolute(e)?Ue.resolve(e):Ue.resolve(n,e),i;try{i=await __.stat(r)}catch{return}if(!i.isFile())return;let[a,o]=await Promise.all([ya(t),ya(r)]);if(fe(a,o)){let s=Ue.relative(a,o);return!s||s.startsWith("..")||Ue.isAbsolute(s)?void 0:{path:ic(s),scope:"project"}}return{path:ic(r),scope:"global"}}async function _A(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>Fn(c,t))),i=new Map,a=fA(mA(e)),o=new Map;await Promise.all([...new Set(a.map(c=>c.value))].map(async c=>{o.set(c,await hA(c,t,n))}));let s=a.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:l}of s){if(!l)continue;let d=Fn(l,t),u=i.get(d)??{path:l.path,scope:l.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(d,u)}return[...i.entries()].map(([c,l])=>({path:l.path,scope:l.scope,status:r.has(c)?"already_linked":"addable",source_count:l.sourceCount,source_fields:[...l.sourceFields].sort((d,u)=>d.localeCompare(u)),original_paths:[...l.originalPaths].sort((d,u)=>d.localeCompare(u))})).sort((c,l)=>{let d=c.status.localeCompare(l.status);if(d!==0)return d;let u=c.path.localeCompare(l.path);return u!==0?u:c.scope.localeCompare(l.scope)})}async function g_(e,t,n){let r=await _a(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return ga(r,"files")}async function gA(e,t){let n=await ya(t),r=await Promise.all(e.map(async a=>{let o=a.trim();if(!o)throw new y("Files lookup paths must not be empty.",g.USAGE);if(!Ue.isAbsolute(o))return vt(o);let s=await ya(o);return fe(n,s)?vt(Ue.relative(n,s)):vt(s)})),i=[...new Set(r)].sort((a,o)=>a.localeCompare(o));if(i.length===0)throw new y("Files lookup requires at least one path.",g.USAGE);return i}function yA(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new y(`Files lookup ${r} must be a non-negative integer.`,g.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function y_(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function w_(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let r=t.item.updated_at.localeCompare(e.item.updated_at);return r===0?e.item.id.localeCompare(t.item.id):r}function wA(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(vt(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,r)=>{let i=n.path.localeCompare(r.path);return i===0?n.scope.localeCompare(r.scope):i})})).filter(t=>t.files.length>0).sort(w_)}async function vA(e){if(e.explain)return Fu({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function bA(e){if([e.strictRead,e.noTruncate,e.explain,Ol()].includes(!0))return null;let t=await hi(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?xd({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function kA(e){let t=[],n=await fn(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),r=wA({metadata:n,paths:e.paths,scope:e.scope}),i=t.filter(s=>/^item_list_(?:item|directory)_read_failed:/u.test(s));if(e.strictRead&&i.length>0)throw new y(`Files lookup could not read every item: ${i.join("; ")}`,g.GENERIC_FAILURE);let a=await vA({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:r,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),o=(a?[...r].sort((s,c)=>{let l=a.explanations.get(c.item.id).score-a.explanations.get(s.item.id).score;return l!==0?l:w_(s,c)}):r).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:o.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+o.length<r.length,truncated:e.offset+o.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:o.map(s=>({item:y_(s.item),files:s.files,...a?{traceability:a.explanations.get(s.item.id)}:{}})),...a?{traceability_receipt:a.receipt}:{}}}async function LH(e,t){let n=L(process.cwd(),t.path),r=Ve(n);await te(n);let i=await gA(e.paths,r);if(e.lineRange&&i.length!==1)throw new y("Files lookup line attribution requires exactly one source path.",g.USAGE);let a=await C(n),o=W(a,H()),{offset:s,limit:c}=yA(e),l=await bA({pmRoot:n,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return l?{paths:i,total:l.total,count:l.matches.length,offset:s,limit:c,has_more:s+l.matches.length<l.total,truncated:s+l.matches.length<l.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:l.matches.map(d=>({item:y_(d.item),files:d.files}))}:kA({pmRoot:n,settings:a,typeToFolder:o.type_to_folder,paths:i,scope:e.scope,limit:c,offset:s,strictRead:e.strictRead===!0,workspaceRoot:r,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function MH(e,t,n){let r=L(process.cwd(),n.path),i=Ve(r);await te(r);let a=await C(r),o=W(a,H()),s=await we(r,e,a.id_prefix,a.item_format,o.type_to_folder);if(!s)throw new y(`Item ${e} not found`,g.NOT_FOUND);let c=await ve(s,{schema:a.schema}),l=await _A(c.document,i,process.cwd()),d=l.filter(b=>b.status==="addable"),u=l.filter(b=>b.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||d.length===0){let b=c.document.metadata.files??[];return{id:s.id,files:b,changed:!1,apply:m,count:b.length,candidate_count:l.length,addable_count:d.length,added_count:0,skipped_existing_count:u.length,candidates:l,added:[],skipped_existing:u}}let p=G(t.author,a.author_default),h=d.map(b=>({path:b.path,scope:b.scope,note:f})),_=[],w=new Set,v=await ct({pmRoot:r,settings:a,id:e,op:"files_discover",author:p,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let N=[...b.metadata.files??[]],I=new Set(N.map(xe=>Fn(xe,i)));_=[],w.clear();for(let[xe,ye]of h.entries()){let he=Fn(ye,i);I.has(he)||(N.push(ye),I.add(he),_.push(ye),w.add(xe))}let R=rc(N),Q=t.appendStable?R:nc(R);return Q.length>0?b.metadata.files=Q:delete b.metadata.files,{changedFields:_.length>0?["files"]:[],warnings:_.length!==h.length?[`files_discover_skipped_existing:${h.length-_.length}`]:[]}}}),S=v.item.files??[],k=new Set(_.map(b=>Fn(b,i))),x=S.filter(b=>k.has(Fn(b,i))),D=d.filter((b,N)=>!w.has(N)),E=[...u,...D];return{id:v.item.id,files:S,changed:x.length>0,apply:!0,count:S.length,candidate_count:l.length,addable_count:d.length,added_count:x.length,skipped_existing_count:E.length,candidates:l,added:x,skipped_existing:E}}import{readFileSync as SA}from"node:fs";import va from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="597a781e-a00d-5083-8d57-3fae870f9ccd")}catch{}})();var EA=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),ac=new Set(["--pm-path","--path","--author"]),xA={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},IA=new Set(["-p","--package"]),AA=new Set(["-c","--call"]),RA=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),CA=new Set(["-C","--prefix","--userconfig","--cache"]),HH=new Set(["--cwd"]),zH=new Set(["--cwd"]),TA=new Set(["exec","x"]),WH=new Set(["run","run-script"]),GH=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function $A(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function OA(e,t=process.cwd()){let n=DA(e.split(" ").filter(o=>o.length>0));if(n.length===0)return null;let[r,...i]=n;if(v_(r)||b_(r,t))return i;if(r==="node"&&i[0]&&b_(i[0],t))return i.slice(1);let a=r==="npx"||r==="bunx"?oc(i):r==="pnpm"?LA(i):r==="npm"?MA(i):null;return a&&(v_(a.command)||NA(a.command))?a.args:null}var k_=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let a=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let s of $A(a)){let c=OA(s),l=c?jA(c):null,d=l&&EA.has(l.subcommand)?FA(l.remaining,xA[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&o.add(d)}return[...o].sort((s,c)=>s.localeCompare(c))};function DA(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function qH(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(ac.has(n)){t+=2;continue}t+=1;continue}return n}}function v_(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function PA(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function NA(e){let t=PA(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function b_(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=va.resolve(t,e);try{return JSON.parse(SA(va.join(va.dirname(va.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function oc(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let a=i[1];return a?{command:a,args:e.slice(t+1)}:null}if(AA.has(r)){t+=1;break}t+=IA.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function S_(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function LA(e){let t=S_(e,RA);return t?.subcommand!=="dlx"?null:oc(t.args)}function MA(e){let t=S_(e,CA);return!t||!TA.has(t.subcommand)?null:oc(t.args)}function jA(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(ac.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function FA(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(ac.has(r)||t.has(r))&&(n+=1)}}import{execFile as UA}from"node:child_process";import{readFile as HA}from"node:fs/promises";import x_ from"node:path";import{promisify as zA}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="574bbc1f-493b-5c51-9c93-97234779a3ce")}catch{}})();var WA=zA(UA),sc=1,GA="linked-test-trust.json";function cc(e){return x_.join(el(e),GA)}function E_(){return{version:sc,acknowledged:{}}}async function lc(e){try{let t=JSON.parse(await HA(cc(e),"utf8"));return t.version!==sc||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?E_():{version:sc,acknowledged:t.acknowledged}}catch{return E_()}}async function dc(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await WA("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function uc(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function qA(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Nl(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function $r(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function BA(e,t,n,r){return e?.map(i=>i.command&&!i.provenance?{...i,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:i)}async function tz(e,t,n){if(!e||e.length===0)return e;let r=uc();return BA(e,t,n,await dc(r))}function I_(e){return Ie(T({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function nz(e,t,n){let r=await lc(e);return A_(t,n,r)}function A_(e,t,n){let r=I_(e),i=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let a=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!qA(e.provenance)?a?{fingerprint:r,trusted:!0,reason:"acknowledged",...$r(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...$r(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...$r(void 0,t)}:e.provenance.source_kind==="local_mutation"&&i!==void 0&&i===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:i,current_source_ref:t}:a?{fingerprint:r,trusted:!0,reason:"acknowledged",...$r(i,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...$r(i,t)}}async function R_(e,t,n){let r=await lc(e);return t.map(i=>A_(i,n,r))}async function rz(e,t,n){let r=await lc(e),i=t.filter(a=>typeof a.command=="string"&&a.command.length>0).map(I_);for(let a of i)r.acknowledged[a]={acknowledged_at:n};return await qn(x_.dirname(cc(e))),await Z(cc(e),`${JSON.stringify(r,null,2)}
67
+ `),{acknowledged:i.length,fingerprints:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8cca9707-86a7-5ab5-8c7b-92be560254d0")}catch{}})();async function ba(e){return e.includeBody?zt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):fn(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6322c4ff-92bd-59e5-aa64-ef8d3ef4b57f")}catch{}})();var VA=5;async function JA(e,t){let n=t.hashMismatches.filter(a=>a!==ce);if(n.length===0)return;let r=await C(e),i=W(r,H());for(let a of n){let o=await re(e,a,r.locks.ttl_seconds,"history-drift-read",!1,!0,r.locks.wait_ms);try{let s=await we(e,a,r.id_prefix,r.item_format,i.type_to_folder);if(s===null)throw new y(`Item ${a} not found`,g.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await ve(s,{schema:r.schema});if(c.metadata.id!==a)throw new y(`Item identity changed while validating ${a}`,g.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let l=await vm(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(m=>m!==a),...l[u].filter(m=>m===a)].sort((m,f)=>m.localeCompare(f));let d=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==a),...(l.identityDiscontinuities??[]).filter(u=>u.item_id===a)];d.length>0?t.identityDiscontinuities=d:delete t.identityDiscontinuities}finally{await o()}}}async function ka(e,t,n){let r=await qt(e,t);await JA(e,r);let i=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,l])=>`${c}:${l}`),a=n?Number.POSITIVE_INFINITY:VA,o=r.driftedItems.slice(0,a),s=r.identityDiscontinuities??[];return{check:{name:"history_drift",status:s.length>0?"error":i.length===0?"ok":"warn",ok:s.length===0&&i.length===0,details:{identity_discontinuities:s.slice(0,a),identity_discontinuities_count:s.length,identity_discontinuities_truncated:s.length>a,checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:o,drifted_items_truncated:o.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,a)}},warnings:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3caaa82b-d8c7-5bc4-94e5-6699da27fa3c")}catch{}})();function Sa(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],a=new Set([n]),o=s=>{for(let c of(t.get(s)??[]).filter(l=>r.has(l))){if(c===n&&i.length>1)return i.push(n),!0;if(!a.has(c)){if(a.add(c),i.push(c),o(c))return!0;i.pop(),a.delete(c)}}return!1};return o(n)?[...i]:[...e,n]}function KA(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function YA(e,t,n,r){for(let i of e.dependencies??[]){if(typeof i!="object"||i===null||typeof i.id!="string")continue;let a=r.resolve(i.kind);if(!a?.hierarchy)continue;let o=n.get(i.id.toLowerCase());o&&(a.hierarchyDirection==="source_parent"?t.get(o).push(e.id):t.get(e.id).push(o))}}function mc(e,t=Xn()){let n=new Map(e.map(i=>[i.id.toLowerCase(),i.id])),r=new Map(e.map(i=>[i.id,[]]));for(let i of[...e].sort((a,o)=>a.id.localeCompare(o.id))){let a=r.get(i.id),o=KA(i.parent,n);o&&a.push(o),YA(i,r,n,t)}for(let[i,a]of r)r.set(i,[...new Set(a)].sort());return r}function pc(e,t,n=Xn()){let r=gi(e,o=>t?wl(o,t):o==="closed"||o==="canceled",n),i=mc(e,n),a=r.cycles.map(o=>o.item_ids);return{cycle_count:a.length,active_cycle_count:r.cycles.filter(o=>!o.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(o=>o.legacy_terminal).length,cycle_item_ids:[...new Set(a.flat())].sort(),cycle_sample_paths:a.map(o=>Sa(o,i).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(o=>!o.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(o=>o.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(o=>`${o.child_id}:${o.parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(o=>!o.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(o=>o.legacy_terminal).length,parent_divergence_rows:r.divergences.map(o=>`${o.child_id}:scalar=${o.scalar_parent_id}:dependencies=${o.dependency_parent_ids.join(",")}:${o.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f2840c80-38f5-5563-b2c0-ef5596cf8f62")}catch{}})();function Pt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function fc(e){return Pt(e).replace(/\/+$/,"")}function qe(e){let t=ee(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function hc(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9b5e620c-ce82-5e2d-9866-2de6882bbb0c")}catch{}})();var eR=["src","tests","docs"],tR=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],nR=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),rR=["resolution","expected_result","actual_result"],iR=["default","tracked-all","tracked-all-strict"],C_=["core","strict","custom"],Ia=["off","warn","error"],yc=["author","acceptance_criteria","estimated_minutes","close_reason"],O_=[...yc,"reviewer","risk","confidence","sprint","release"],wc=Array.from(new Set(O_)),aR={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},oR={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},sR={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},cR={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},lR={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},dR=32*1024*1024,uR=1e4,vc=40,Be=5,mR=4096,pR=255,fR=QA(ZA);function D_(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||r===!1&&n.endsWith("_truncated")||(t[n]=typeof r=="object"&&r!==null?D_(r):r);return t}function hR(e){return{...e,checks:e.checks.map(t=>({...t,details:D_(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function Ra(e,t){return ri(e,t)??e}function Or(e,t){return t.terminal_statuses.has(Ra(e,t))}function Nt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ea(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function _R(e){let t=Nt(Gc),n={blocked_reason:Nt(zr.blocked_reason),resolution:Nt(zr.resolution),actual_result:Nt(zr.actual_result)},r=Nt(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:Nt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:Nt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:Nt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:Ea(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:Ea(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Ea(i.resolution,n.resolution)?"default":"settings",actual_result:Ea(i.actual_result,n.actual_result)?"default":"settings"}}}function P_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(C_.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${C_.join(", ")}.`,g.USAGE)}function N_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Ia.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Ia.join(", ")}.`,g.USAGE)}function L_(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Ia.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Ia.join(", ")}.`,g.USAGE)}function gR(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].map(t=>aR[t]).filter(t=>t!==void 0).sort((t,n)=>t.localeCompare(n))}function yR(e,t,n){let r=gR(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...yc],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...O_],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...yc],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var wR=new Set(["acceptance_criteria","estimated_minutes"]);function M_(e,t,n,r){return!r&&wR.has(t)&&Or(e.status,n)?!1:t==="author"?!ee(e.author):t==="acceptance_criteria"?!ee(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Ra(e.status,n)===n.close_status&&!ee(e.close_reason):t==="reviewer"?!ee(e.reviewer):t==="risk"?!ee(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!ee(e.confidence):t==="sprint"?!ee(e.sprint):!ee(e.release)}function j_(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new y(`Unknown --scan-mode value "${e}". Supported values: ${iR.join(", ")}.`,g.USAGE)}function F_(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return Ee.resolve(t);let n=Ee.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return Ee.dirname(Ee.dirname(n));let r=Ee.resolve(process.cwd()),i=T_(n),a=T_(r),o=Ee.relative(i,a);return o.length===0||!o.startsWith("..")&&!Ee.isAbsolute(o)?n:r}function T_(e){try{return XA.native(e)}catch{return Ee.resolve(e)}}function vR(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Ec(e,t,n){let r=t.length>0?Ee.join(e,t):e,i;try{i=await Sc.readdir(r,{withFileTypes:!0})}catch(a){if(U(a))return;throw a}for(let a of i){if(a.name.startsWith("."))continue;let o=t.length>0?Ee.join(t,a.name):a.name;if(a.isDirectory()){if(nR.has(a.name))continue;await Ec(e,o,n);continue}a.isFile()&&n.push(Pt(o))}}async function bc(e){let t=[];for(let n of eR)await Ec(e,n,t);for(let n of tR){let r=Ee.join(e,n);try{(await Sc.stat(r)).isFile()&&t.push(Pt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function U_(e){try{let{stdout:t}=await fR("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:dR,windowsHide:!0,timeout:uR}),n=t.split("\0").map(r=>Pt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function bR(e,t){let n=new Set,r=fc(Hc);r.length>0&&n.add(r);let i=fc(Ee.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((a,o)=>a.localeCompare(o))}function $_(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function kR(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await U_(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await bc(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await bc(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function ae(e,t=Be){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function en(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ae(e,vc);return{values:n.values,truncated:n.truncated,total:e.length}}var SR={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},ER={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function xR(e){let t=e.missing_fields.map(n=>`${SR[n]} "${ER[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function H_(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(o=>typeof o=="string"):Em(t);if(i.length===0)return;let a=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...a?{fix_hints_truncated:!0}:{}}}function z_(e){let t=new Set;return e.checkCompleteness&&t.add("completeness"),e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("completeness"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var IR="validate_metadata_duplicate_issue_codes";function W_(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:Be,r=e.slice(0,n);return{rows:r.map(i=>({code:i.code,count:i.count,ids:i.ids,titles:i.titles,remediation_hint:`Items ${i.ids.join(", ")} share issue code "${i.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${IR}:${e.length}`]}}function AR(e,t,n){let r=Object.fromEntries(wc.map(i=>[i,[]]));for(let i of e)for(let a of wc)M_(i,a,t,n)&&r[a].push(i.id);return r}function RR(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let a=t[i];a.length>0&&r.push(`${oR[i]}:${a.length}`)}return r.push(...n),r}function G_(e,t){let n={};for(let r of e.required_fields){let i=t[r],a=i?i.length:0,o=sR[r];n[o]=a}return n}function q_(e,t,n){let r=[];for(let i of e.required_fields){let a=t[i];if(a)for(let o of a){let s=n.get(o)?.type,c=typeof s=="string"&&s.length>0?s:"Unknown";r.push({item_type:c,field:i})}}return r}function CR(e,t,n,r){for(let i of t.required_fields){let a=n[i];if(!a||a.length===0)continue;let o=cR[i],s=lR[i];if(!o||!s)continue;let c=ae(a,r?a.length:Be);e[o]=c.values,e[s]=c.truncated}}function B_(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:ee(n.get(i)?.resolution)})):[]}function V_(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:ee(n.get(i)?.type)})):[]}function TR(e,t,n,r,i){let a=new Map(e.map(w=>[w.id,w])),o=t.profile==="strict",s=AR(e,n,o),c=c_(e,{configuredPrefixes:i}),l=W_(c,r),d=RR(t,s,l.warnings),u=G_(t,s),m=q_(t,s,a),f=l_(m),p={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...wc],counts:u,missing_by_type:f,duplicate_issue_codes_count:c.length,duplicate_issue_codes:l.rows,duplicate_issue_codes_truncated:l.truncated};t.configured_custom_fields.length>0&&(p.configured_custom_required_fields=[...t.configured_custom_fields]),CR(p,t,s,r);let h=B_(t,s,a),_=V_(t,s,a);return{check:{name:"metadata",status:d.length===0?"ok":"warn",ok:d.length===0,details:p},warnings:d,closeReasonBackfillRows:h,estimateBackfillRows:_}}function $R(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(Ra(m.status,t))),a=[],o=[];for(let m of i){let f=rR.filter(p=>!ee(m[p]));f.length!==0&&(a.push({id:m.id,missing_fields:f}),o.push({id:m.id,missing_fields:f,close_reason:ee(m.close_reason)}))}let s=a.length>0?[`validate_resolution_missing_fields:${a.length}`]:[],c=n?Number.POSITIVE_INFINITY:Be,l=ae(a.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),d=a.map(m=>xR(m)),u=ae(d,c);return{check:{name:"resolution",status:s.length===0?"ok":"warn",ok:s.length===0,details:{checked_closed_items:i.length,missing_resolution_items:a.length,missing_resolution_rows:l.values,missing_resolution_rows_truncated:l.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:s,resolutionBackfillRows:o}}function J_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function K_(e,t="pm",n=Vc()){let r=new Set(e.map(a=>a.id)),i=[...e].sort((a,o)=>a.id.localeCompare(o.id));return new Map(i.map(a=>{let o=new Set,s=qe(a.blocked_by);s&&r.has(s)&&o.add(s),(a.dependencies??[]).filter(l=>{let d=qe(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>qe(l.id)).filter(l=>l!==void 0&&r.has(l)).forEach(l=>o.add(l));let c=qe(a.definition_of_ready);return X_(c??"",t).filter(l=>r.has(l)).forEach(l=>o.add(l)),[a.id,[...o].sort((l,d)=>l.localeCompare(d))]}))}function Y_(e,t,n){let r=qd(e,n?d=>Or(d,n):void 0),i=r.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),a=r.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),o=t?Number.POSITIVE_INFINITY:Be,s=ae(i,o),c=ae(a,o),l=ae(r.active.map(d=>d.source==="parent"?`pm update ${d.holder_id} --unset parent`:d.source==="blocked_by"?`pm update ${d.holder_id} --unset blocked_by`:`pm update ${d.holder_id} --replace-deps '<correct dependency edges>'`),o);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:e.length,dangling_reference_count:i.length+a.length,active_dangling_reference_count:i.length,dangling_reference_rows:s.values,dangling_reference_rows_truncated:s.truncated,legacy_terminal_dangling_reference_count:a.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(d=>d.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:l.values,remediation_hints_truncated:l.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function X_(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${J_(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,a)=>i.localeCompare(a))}function Z_(e){let t=0,n=new Map,r=new Map,i=[],a=new Set,o=[],s=l=>{n.set(l,t),r.set(l,t),t+=1,i.push(l),a.add(l);for(let u of e.get(l)??[])n.has(u)?a.has(u)&&r.set(l,Math.min(r.get(l),n.get(u))):(s(u),r.set(l,Math.min(r.get(l),r.get(u))));if(r.get(l)!==n.get(l))return;let d=[];for(;i.length>0;){let u=i.pop();if(a.delete(u),d.push(u),u===l)break}d.sort((u,m)=>u.localeCompare(m)),o.push(d)},c=[...e.keys()].sort((l,d)=>l.localeCompare(d));for(let l of c)n.has(l)||s(l);return o.filter(l=>{if(l.length>1)return!0;let d=l[0];return(e.get(d)??[]).includes(d)}).sort((l,d)=>l[0].localeCompare(d[0])||l.length-d.length||l.join(",").localeCompare(d.join(",")))}function Q_(e,t="pm"){let n=K_(e,t),r=Z_(n),i=[...new Set(r.flat())].sort((o,s)=>o.localeCompare(s)),a=r.map(o=>Sa(o,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:a}}function eg(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function Aa(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function tg(e,t){let n=Aa(e).split("/").filter(Boolean),r=Aa(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function OR(e,t){let n=Aa(t),r=Aa(e),i=t.endsWith("/")?t:`${t}/`,a=e.startsWith(i),o=n.length>0&&n===r,s=tg(e,t);return!a&&!o&&s===0?null:a?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:s+500,confidence:"same_directory"}:{score:s,confidence:"shared_directory"}}function DR(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function PR(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(a=>(r==="docs"?a.docs??[]:a.files??[]).map(o=>({item:a,link:o}))).forEach(({item:a,link:o})=>{if(o.scope!=="project")return;let s=Pt(o.path);if(s.length===0||s===e)return;let c=OR(e,s);c!==null&&DR(i,a,c.score)&&(i={item:a,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function ng(e,t){return e.map(n=>{let r=eg(n),i=r==="docs_unowned"?"docs":"files",a=PR(n,r,t),o=a?.id??"<id>";return{path:n,classification:r,owner_candidate:a,remediation_hint:`pm ${i} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function rg(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function NR(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=qe(e[n]);return i?r.some(a=>i.toLowerCase().includes(a)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function LR(e,t,n,r,i){let a=qe(t.parent),o=a?n.get(r.get(a.toLowerCase())??a):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!Or(o.status,i)}}function MR(e,t,n,r){let i=qe(e.blocked_by),a=qe(e.blocked_reason),o=a?.toLowerCase(),s=Ra(e.status,n),c=[];return t.has(s)?(!i&&!a&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&r.stale_blocker_reason_patterns.some(l=>o.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),a&&c.push("non_blocked_status_has_blocked_reason"),c)}function jR(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),a=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),s={activeItems:e.filter(c=>!Or(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of s.activeItems){let l=NR(c,r);l.length>0&&s.closureLikeRows.push({id:c.id,fields:l});let d=qe(c.parent),u=d?i.get(a.get(d.toLowerCase())??d):void 0;if(u&&Or(u.status,n)&&(s.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),s.terminalParentFixRows.push(LR(c,u,i,a,n))),t){let m=MR(c,o,n,r);m.length>0&&s.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,p)=>f.localeCompare(p))})}}return s}function FR(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function xa(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function _c(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function UR(e,t,n,r,i){let a=[];e.closureLikeRows.length>0&&a.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&a.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&a.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let o=xa("validate_lifecycle_dependency_cycles",n,i.dependencyCycles),s=xa("validate_hierarchy_parent_cycle",r,i.activeHierarchyCycles),c=xa("validate_hierarchy_cardinality_violation",r,i.activeHierarchyCardinality),l=xa("validate_hierarchy_parent_divergence",r,i.activeHierarchyDivergence),d=_c("validate_legacy_hierarchy_parent_cycle",r,i.legacyHierarchyCycles),u=_c("validate_legacy_hierarchy_cardinality_violation",r,i.legacyHierarchyCardinality),m=_c("validate_legacy_hierarchy_parent_divergence",r,i.legacyHierarchyDivergence);return[...a,...o?[o]:[],...s?[s]:[],...c?[c]:[],...l?[l]:[],...d?[d]:[],...u?[u]:[],...m?[m]:[]]}function ig(e){let t=Pt(e);return t.length>mR||t.split(/[\\/]/).some(n=>n.length>pR)}async function HR(e,t){let n=Ee.isAbsolute(t)?t:Ee.resolve(e,t);if(ig(n))return!1;try{let r=await Sc.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return vR(r,["ENOENT","ENOTDIR"])}}async function zR(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(a=>({item:i,artifact:a,link_kind:"files"})),...(i.docs??[]).map(a=>({item:i,artifact:a,link_kind:"docs"}))]);for(let{item:i,artifact:a,link_kind:o}of r){if(a.scope!=="project")continue;if(Cr(a.path)){n.remoteLinkedPaths.add(a.path.trim());continue}let s=Pt(a.path);s.length!==0&&(n.linkedProjectPaths.add(s),await HR(t,a.path)&&(n.missingLinkedPaths.push(s),n.staleLinkRows.push({item_id:i.id,path:s,link_kind:o})))}return n}function WR(e,t,n,r,i,a){let o=r==="tracked-all-strict",s=o&&!i,c=i||o,l=c?[]:bR(t,n),d=l.length===0?[]:e.candidateFiles.filter(f=>$_(f,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!$_(f,l)),m={};if(d.length>0){let f=en(d,a);m.pm_internals={count:d.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:s,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:m}}function ag(e,t,n,r,i,a,o,s="pm"){let c=jR(e,t,i,a);FR(c);let l=Q_(c.activeItems,s),d=pc(e,i),u=Oi(i,e,o?Number.POSITIVE_INFINITY:Be),m=[...UR(c,t,n,r,{dependencyCycles:l.cycle_count,activeHierarchyCycles:d.active_cycle_count,activeHierarchyCardinality:d.active_cardinality_violation_count,activeHierarchyDivergence:d.active_parent_divergence_count,legacyHierarchyCycles:d.legacy_cycle_count,legacyHierarchyCardinality:d.legacy_cardinality_violation_count,legacyHierarchyDivergence:d.legacy_parent_divergence_count}),...Di(u)],f=o?Number.POSITIVE_INFINITY:Be,p=ae(c.closureLikeRows.map(b=>`${b.id}:${b.fields.join(",")}`),f),h=ae(c.terminalParentRows.map(b=>`${b.id}:${b.parent_id}:${b.parent_status}`),f),_=ae(c.staleBlockerRows.map(b=>`${b.id}:${b.status}:${b.reasons.join(",")}`),f),w=ae(l.cycle_item_ids,f),v=ae(l.cycle_sample_paths,f),S=ae(d.cycle_item_ids,f),k=ae(d.cycle_sample_paths,f),x=ae(d.cardinality_violation_rows,f),D=ae(d.parent_divergence_rows,f),E=l.cycle_count>0&&n==="error"||(d.active_cycle_count>0||d.active_cardinality_violation_count>0||d.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:E?"error":m.length===0?"ok":"warn",ok:!E&&m.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:p.values,active_closure_like_metadata_rows_truncated:p.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:h.values,active_terminal_parent_rows_truncated:h.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:_.values,stale_blocker_rows_truncated:_.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:l.cycle_count,dependency_cycle_item_count:l.cycle_item_ids.length,dependency_cycle_item_ids:w.values,dependency_cycle_item_ids_truncated:w.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:d.cycle_count,active_parent_cycle_count:d.active_cycle_count,legacy_parent_cycle_count:d.legacy_cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:S.values,parent_cycle_item_ids_truncated:S.truncated,parent_cycle_sample_paths:k.values,parent_cycle_sample_paths_truncated:k.truncated,hierarchy_cardinality_violation_count:d.cardinality_violation_count,active_hierarchy_cardinality_violation_count:d.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:d.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:x.values,hierarchy_cardinality_violation_rows_truncated:x.truncated,hierarchy_parent_divergence_count:d.parent_divergence_count,active_hierarchy_parent_divergence_count:d.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:d.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:D.values,hierarchy_parent_divergence_rows_truncated:D.truncated,stale_blocker_reason_patterns:[...a.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:a.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...a.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:a.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...a.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:a.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...a.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:a.closure_like_metadata_field_pattern_sources.actual_result}},warnings:m,terminalParentFixRows:c.terminalParentFixRows}}async function og(e,t,n,r,i,a,o=_e(qc.schema)){let s=await zR(e,t),c=new Map(e.map(R=>[R.id,R])),l=[...new Set(s.missingLinkedPaths)].sort((R,Q)=>R.localeCompare(Q)),d=await kR(t,r),u=WR(d,n,t,r,i,a),m=u.candidateFiles.filter(R=>!s.linkedProjectPaths.has(R)),f=ng(m,e),p=u_(l,u.candidateFiles),h=new Map(p.map(R=>[R.path,R.classification])),_=p.filter(R=>R.classification==="moved").length,w=s.staleLinkRows.map(R=>({...R,classification:h.get(R.path)??"deleted"})).sort((R,Q)=>R.item_id.localeCompare(Q.item_id)||R.path.localeCompare(Q.path)||R.link_kind.localeCompare(Q.link_kind)),v=[];u.strictModeForcesPmInternals&&v.push("validate_files_tracked_all_strict_forces_pm_internals"),m.length>0&&v.push(`validate_files_orphaned_paths:${m.length}`);let S=[...s.remoteLinkedPaths].sort((R,Q)=>R.localeCompare(Q)),k=en(S,a),x=en(l,a),D=en(m,a),E=en(f.map(R=>`${R.path}:${R.classification}:owner_candidate=${R.owner_candidate?.id??"unowned"}`),a),b=a?f:en(rg(f),!1).values,N=en(m_(p),a),I=Yh(w,p,R=>c.get(R),o,a?1/0:vc);return I.active_missing_linked_paths_count>0&&v.push(`validate_files_missing_linked_paths:${I.active_missing_linked_paths_count}`),{check:{name:"files",status:v.length===0?"ok":"warn",ok:v.length===0,details:{workspace_root:t,scan_mode_requested:d.requestedMode,scan_mode_applied:d.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:a?"full":"summary",file_list_summary_limit:vc,candidate_scan_source:d.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:s.linkedProjectPaths.size,remote_linked_paths_count:S.length,remote_linked_paths_total:k.total,remote_linked_paths:k.values,remote_linked_paths_truncated:k.truncated,candidate_total_raw:d.candidateTotal,candidate_scanned_raw:d.candidateScanned,candidate_total:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:l.length,missing_linked_paths_total:x.total,missing_linked_paths:x.values,missing_linked_paths_truncated:x.truncated,missing_linked_paths_moved_count:_,missing_linked_paths_deleted_count:p.filter(R=>R.classification==="deleted").length,missing_linked_paths_malformed_count:p.filter(R=>R.classification==="malformed").length,missing_linked_path_classifications:N.values,missing_linked_path_classifications_truncated:N.truncated,...I,orphaned_paths_count:m.length,orphaned_paths_total:D.total,orphaned_paths:D.values,orphaned_paths_truncated:D.truncated,orphaned_path_classifications:E.values,orphaned_path_classifications_truncated:E.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:b}},warnings:v,staleLinkPruneRows:w}}function GR(e,t){let n=[];return e.forEach(({item:r,linkedTest:i},a)=>{let o=t[a];if(o.trusted)return;let s=hc(i.command??"");n.push(`${r.id}:${o.source_ref??"unknown"}->${o.current_source_ref??"unknown"}:${s}`)}),n}async function sg(e,t,n,r){let i=new Set(e.map(x=>x.id.toLowerCase())),a=0,o=0,s=new Set,c=[],l=e.flatMap(x=>(x.tests??[]).map(D=>({item:x,linkedTest:D}))),d=await dc(uc()),u=await R_(r,l.map(({linkedTest:x})=>x),d),m=GR(l,u);for(let{item:x,linkedTest:D}of l){if(typeof D.command!="string"||D.command.trim().length===0)continue;a+=1;let E=k_(D.command,t);if(E.length!==0){o+=E.length;for(let b of E)s.add(b),i.has(b.toLowerCase())||c.push(`${x.id}:${b}:${hc(D.command)}`)}}let f=[...new Set(c)].sort((x,D)=>x.localeCompare(D)),p=[...new Set(f.map(x=>x.split(":")[1]??""))].filter(x=>x.length>0).sort((x,D)=>x.localeCompare(D)),h=[];f.length>0&&h.push(`validate_command_references_stale_pm_ids:${f.length}`),m.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${m.length}`);let _=n?Number.POSITIVE_INFINITY:Be,w=ae(f,_),v=ae(p,_),S=ae([...s].sort((x,D)=>x.localeCompare(D)),_),k=ae(m,_);return{check:{name:"command_references",status:h.length===0?"ok":"warn",ok:h.length===0,details:{checked_items:e.length,linked_commands_scanned:a,referenced_pm_ids_count:o,unique_referenced_pm_ids_count:s.size,unique_referenced_pm_ids:S.values,unique_referenced_pm_ids_truncated:S.truncated,linked_test_trust_current_source_ref:d??null,untrusted_linked_tests_count:m.length,untrusted_linked_tests:k.values,untrusted_linked_tests_truncated:k.truncated,stale_pm_id_references_count:f.length,stale_pm_ids_count:p.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:w.values,stale_pm_id_reference_rows_truncated:w.truncated}},warnings:h}}function qR(e,t){let n=ni(e.map(c=>({ref:c.id,version:ti(c)}))),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:Be,a=ae(n.outdated,i),o=ae(n.ahead,i),s=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:s,ok:s==="ok",details:{checked_items:e.length,current_format_version:zl,outdated_items_count:n.outdated.length,outdated_items:a.values,outdated_items_truncated:a.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:r}}var kc="pm validate auto-fix";async function cg(e,t,n){switch(e.kind){case"set_closed_at":await Vh(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:kc};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new y("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",g.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function gc(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function lg(e,t,n){let r=[],i=[],a=new Map;for(let o of e.filter(s=>gc(s)===null))try{await cg(o,t,n),r.push(o)}catch(s){i.push({fix:o,error:s})}for(let o of e.filter(s=>gc(s)!==null)){let s=gc(o),c=a.get(s);c?c.push(o):a.set(s,[o])}for(let o of a.values()){let s=o[0];if(!s)continue;let c=o.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{s.kind==="prune_file_link"?await g_(s.item_id,{remove:c,message:kc},t):await h_(s.item_id,{remove:c,message:kc},t),r.push(...o)}catch(l){i.push(...o.map(d=>({fix:d,error:l})))}}return{applied:r,failed:i}}var fW={applyValidateFix:cg,applyValidateFixes:lg,attachValidateFixHints:H_,buildCommandReferencesCheck:sg,buildDependencyReferencesCheck:Y_,buildCloseReasonBackfillRows:B_,buildFilesCheck:og,buildLifecycleCheck:ag,buildLifecycleDependencyGraph:K_,buildLifecycleParentGraph:mc,buildEstimateBackfillRows:V_,buildMetadataCounts:G_,buildMissingFieldOccurrences:q_,buildOrphanedPathRows:ng,classifyOrphanedPath:eg,collectDefaultProjectFileCandidates:bc,collectTrackedGitFileCandidates:U_,detectLifecycleDependencyCycles:Q_,detectLifecycleParentCycles:pc,escapeRegExp:J_,extractItemIds:X_,findLifecycleDependencyCycleComponents:Z_,isMetadataFieldMissing:M_,linkedArtifactPathExceedsFilesystemLimits:ig,listFilesRecursive:Ec,resolveDependencyCycleSeverity:N_,resolveParentCycleSeverity:L_,resolveFileScanMode:j_,resolveLifecycleDependencyCycleSamplePath:Sa,resolveRequestedChecks:z_,resolveValidateMetadataProfile:P_,resolveWorkspaceRoot:F_,sharedDirectoryPrefixLength:tg,summarizeOrphanedPathRows:rg,summarizeDuplicateIssueCodes:W_,toMeaningfulString:qe};function BR(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function VR(e,t,n,r){let i=await Zh(e,new Set(t.map(_=>_.id)),n,{schema:r.schema,extensionFieldNames:tn(H())}),a=[];i.unreadable_item_files.length>0&&a.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&a.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&a.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&a.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&a.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&a.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let o=a.length,s=await ia(e);s.tracked_path_count>0&&a.push(`validate_storage_tracked_runtime_cache_files:${s.tracked_path_count}`);let c=await In(e,At(r));c.status==="drift"&&a.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await et(e),d=l===null?null:await An(l);d!==null&&d.status!=="ok"&&a.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=await gt(l??e,{includeLossless:!0,pmRoot:e}),m=u.receipts,{pendingDecisions:f,lossless:p}=Pn(m);f.length>0&&a.push(`validate_merge_decisions_unreviewed:${f.length}`),BR(a,u.invalid_evidence_count);let h=o>0?"error":a.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:h,ok:h==="ok",details:{...i,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:f.length,pending_merge_decision_items:[...new Set(f.map(_=>_.item_id))].sort((_,w)=>_.localeCompare(w)),lossless_merge_receipt_count:p.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(p.map(_=>_.item_id))].sort((_,w)=>_.localeCompare(w)),tracked_runtime_cache:{tracker_relative_root:s.tracker_relative_root,tracked_paths:s.tracked_paths,tracked_path_count:s.tracked_path_count,remediation_command:s.remediation_command}}},warnings:a}}function at(e,t,n){n&&H_(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function JR(e){let t={closureTimestampFixes:[],checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let i=await hu(e.pmRoot,e.items,r?1/0:Be,e.sourceIncomplete);at(t,i,n)}if(e.requestedChecks.has("metadata")){let i=TR(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows;let a=await Bh(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,r?1/0:Be);t.closureTimestampFixes=a.fixes,Object.assign(i.check.details,a.details),i.warnings.push(...a.warnings),i.check.ok=i.warnings.length===0,i.check.status=i.check.ok?"ok":"warn",at(t,i,n)}if(e.requestedChecks.has("resolution")){let i=$R(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,at(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=ag(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,at(t,i,n),at(t,Y_(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await og(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=i.staleLinkPruneRows,at(t,i,n)}return e.requestedChecks.has("command_references")&&at(t,await sg(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&at(t,await ka(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&at(t,qR(e.items,r),n),e.requestedChecks.has("storage_integrity")&&at(t,await VR(e.pmRoot,e.items,W(e.settings,H()).type_to_folder,e.settings),n),t}function KR(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...t.closureTimestampFixes),r.push(...t_(t.closeReasonBackfillRows)),r.push(...e_(t.resolutionBackfillRows)),r.push(...n_(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...r_(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...i_(t.staleLinkPruneRows)),r}async function YR(e,t,n,r,i,a){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=KR(e,t,n),{applicable:s,gated:c}=o_(o,r),l=e.dryRun===!0,d=[],u=[];if(!l){let m=await lg(s,i,a);d.push(...m.applied.map(Rr)),u.push(...m.failed.map(({fix:f,error:p})=>({...Rr(f),error:p instanceof Error?p.message:String(p)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,f)=>m.localeCompare(f)),planned_count:o.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(Rr),applied_fixes:d,gated_fixes:c.map(m=>({...Rr(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function dg(e,t,n={}){Pl(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new y("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",g.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new y("--fix-scope requires --auto-fix.",g.USAGE);let i=a_(e.fixScope),a=L(process.cwd(),t.path);await te(a);let o=await C(a),s=_e(o.schema),c=W(o,H()),l=z_(e),d=[],u=await ba({includeBody:["history_drift","metadata","completeness"].some(N=>l.has(N)),pmRoot:a,settings:o,typeToFolder:c.type_to_folder,warnings:d}),m=d.length>0;if(l.has("history_drift")){let N=await ir(a);N.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${N.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",p=P_(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),h=yR(p,f,o.validation.metadata_required_fields),_=_R(o),w=N_(e.dependencyCycleSeverity),v=L_(e.parentCycleSeverity),S=j_(e.scanMode),k=F_(a),x=await JR({requestedChecks:l,options:e,global:t,pmRoot:a,workspaceRoot:k,settings:o,items:u,statusRegistry:s,metadataPolicy:h,lifecyclePatternPolicy:_,dependencyCycleSeverity:w,parentCycleSeverity:v,fileScanMode:S,initialWarnings:[...new Set(d)],sourceIncomplete:m}),D=r?await YR(e,x,o,i,t,n):void 0,E=[...new Set(x.warnings)].sort((N,I)=>N.localeCompare(I)),b={ok:!x.checks.some(N=>N.status==="error"),has_warnings:E.length>0,checks:x.checks,warnings:E,...D!==void 0?{fixes:D}:{},generated_at:$(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?b:{...hR(b),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as XR}from"node:child_process";import{promisify as ZR}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c51ba190-f6ae-5885-806c-d2ae0706c429")}catch{}})();var QR=ZR(XR),eC=16,tC=3e4;function nC(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(r=>typeof r=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function rC(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let r=t.parameters??{},i=n.parameters??{};for(let a of Object.entries(i).filter(([,o])=>o.required===!0).map(([o])=>o))if(!Object.hasOwn(r,a))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${a}`);for(let[a,o]of Object.entries(r)){let s=i[a];if(!s)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${a}`);if(o===null||typeof o!==s.type)throw new TypeError(`assurance provider ${e.id} parameter ${a} must be ${s.type}`)}return{...r}}async function iC(e,t,n,r){let i=rC(e,t),a=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:i,trigger:r,pm_root:n,...$l(n)}));a.catch(()=>{});let o;try{let s=await Promise.race([a,new Promise((c,l)=>{o=setTimeout(()=>l(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??tC),o.unref?.()})]);return nC(e,t.key,s)}finally{clearTimeout(o)}}function mg(e,t,n,r){let i=e;for(let a of t.split(".")){if(typeof i!="object"||i===null||Array.isArray(i))throw new Ze(`assurance field ${t} is not present`,{source_kind:n,field:t,...r?{check:r}:{}});i=i[a]}if(typeof i=="number"&&Number.isFinite(i)||Array.isArray(i)&&i.every(a=>typeof a=="string"))return i;throw new Ze(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...r?{check:r}:{}})}function ug(e,t,n,r){let i=e.checks.find(a=>a.name===t);if(!i)throw new Ze(`assurance check ${t} is not present`,{source_kind:r,field:n,check:t});return{value:n==="status"||n==="ok"?i.ok?0:1:mg(i.details,n,r,t),population_size:1,cost:e.checks.length}}async function aC(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await QR("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function oC(e,t){let n=new Array(t.length),r=0,i=Array.from({length:Math.min(eC,t.length)},async()=>{for(;r<t.length;){let a=r;r+=1;let o=t[a],s=await Ut(Mt(e,o.id),o.id);n[a]=s.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(i),n.flat()}async function Dr(e,t={}){let n=await C(e),r=W(n),i=_e(n.schema),a=(t.strict_read===!0?(await Vd(void 0,{status:"all",full:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await fn(e,n.item_format,r.type_to_folder,void 0,n.schema)).map(m=>({...m,id:m.id,status:m.status,type:m.type})),o={path:e},s=H(),c=Object.fromEntries((s?.assurance_providers??[]).map(m=>[m.definition.id,{cost_class:m.runtime_definition.cost_class,network:m.runtime_definition.network}])),l=new Map,d,u;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await aC(e,t.tree_id),items:a,history:t.include_history===!1?[]:await oC(e,a),terminal_statuses:[...i.terminal_statuses],provider_capabilities:{...c,...t.provider_capabilities},external:async m=>{if(m.kind==="graph"){let h=T({operation:m.operation,parameters:m.parameters??{}}),_=l.get(h);_===void 0&&(_=Yd(m.operation,void 0,void 0,{...m.parameters,full:!0},o),l.set(h,_));let w=await _;return{value:mg(w,m.field,m.kind),population_size:a.length,cost:a.length}}if(m.kind==="validate"){d??=dg({counts:!0},o);let h=await d;return ug(h,m.check,m.field,m.kind)}if(m.kind==="health"){u??=Wh(o,{checkOnly:!0,full:!0});let h=await u;return ug(h,m.check,m.field,m.kind)}let f=t.providers?.[m.provider];if(f)return f(m);let p=cd(s,m.provider);if(!p)throw new TypeError(`assurance provider ${m.provider} is not registered`);return iC(p.runtime_definition,m,e,t.trigger??"sdk")}}}import{createHash as sC}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c72d246d-a7ff-5c9d-8c36-4ebd45b8a69f")}catch{}})();function pg(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:r,limit:i}=Zr({...t,change:{}});return{policy:n,...r===void 0?{}:{cursor:r},...i===void 0?{}:{limit:i},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function cC(e,t){if(e===void 0)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("recurrence coverage cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("recurrence coverage cursor is invalid");let r=n;if(r.fingerprint!==t||typeof r.offset!="number"||!Number.isSafeInteger(r.offset)||r.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return r.offset}function lC(e,t,n,r,i,a){let o=Object.fromEntries(Ja.map(f=>[f,0])),s=0,c=0,l=0,d=0,u=[],m=sC("sha256").update(i);for(let f of r){let p=e.membership.get(f),h=n.has(f),_=p.family_ids.length>0;_&&h&&(s+=1),_||(c+=1),h||(l+=1);let w=t.get(f)?.escape_class;w!==void 0&&Ja.includes(w)&&(o[w]+=1,d+=1),m.update(T([f,h,t.get(f)??null,p.id,p.family_ids])),(!a||!_||!h)&&u.push(f)}return{classCounts:o,coveredCount:s,uncoveredCount:c,missingCount:l,classifiedCount:d,selected:u,fingerprint:m.digest("hex")}}function fg(e,t,n={}){Ul(e);let r=n.limit??25;if(!Number.isSafeInteger(r)||r<1||r>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let i=new Set,a=new Map;for(let k of t){if(i.has(k.id))throw new TypeError(`Duplicate recurrence item ${k.id}`);i.add(k.id);let x=Xr(k);x!==void 0&&a.set(k.id,x)}let o=Ml(e.families,a),s=[...o.membership.keys()].sort(),c=T({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:l,coveredCount:d,uncoveredCount:u,missingCount:m,classifiedCount:f,selected:p,fingerprint:h}=lC(o,a,i,s,c,n.uncoveredOnly===!0),_=cC(n.cursor,h);if(_>p.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let w=p.slice(_,_+r).map(k=>{let x=o.membership.get(k),D=i.has(k);return{item_id:k,lineage_id:x.id,lineage_item_count:x.item_ids.length,family_ids:x.family_ids,present:D,...D?x.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),v=_+w.length,S=s.length===0?null:l.production_defect/s.length;return{ok:u===0&&m===0,fingerprint:h,items:w,total:p.length,has_more:v<p.length,...v<p.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:h,offset:v})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:s.length,lineage_count:o.lineages.length,edge_count:o.edge_count,covered_item_count:d,uncovered_item_count:u,missing_item_count:m,classified_item_count:f,unclassified_item_count:s.length-f,class_counts:l,escape_rate:f===s.length?S:null,escape_rate_lower_bound:S},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:o.edge_count,row_limit:r},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as dC}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0311387c-c7c3-598c-961c-489e8a94ad29")}catch{}})();var xc,hg=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],Ic=["measurement","assertion","gate"];function uC(e){if(hg.includes(e))return e;throw ui({command_path:"assurance",token:e,allowed:hg,display_name:"assurance action"})}function Un(e,t,n){throw new y(t,g.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function mC(e){if(!e)return Un("kind",`Assurance declaration kind is required. Expected: ${Ic.join(", ")}`,"pm assurance list measurement");if(Ic.includes(e))return e;throw new y(`Assurance declaration kind is required. Expected: ${Ic.join(", ")}`,g.USAGE)}function _g(e){if(!e)return Un("preset",`Assurance preset is required. Expected: ${ar.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(ar.includes(e))return e;throw new y(`Assurance preset is required. Expected: ${ar.join(", ")}`,g.USAGE)}function Ac(e){return e.owner?.trim()?e.owner.trim():Un("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function pC(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(r){throw new y("assurance definition must be valid JSON",g.USAGE,{reason:r instanceof Error?r.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new y("assurance put requires a JSON object definition",g.USAGE);return n}async function fC(e){let[t,n,r]=await Promise.all([er(e,"measurement"),er(e,"assertion"),er(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:r.items}}function gg(e,t){return t===!0?{id:e.id}:e}async function hC(e,t){let n=t.authorization_decision;if(!n)return[];let r=await Dr(e,{include_history:!1,resolve_tree:!1}),i=r.items.find(o=>o.id===n),a=new Set(r.terminal_statuses);if(!i||i.type.toLowerCase()!=="decision"||!a.has(i.status))throw new y(`Assurance authorization ${n} must name a terminal Decision item`,g.USAGE);return[i.id]}async function _C(e,t){let n=vo(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>yn))throw new y(`assurance verdict limit must be an integer from 1 through ${yn}`,g.USAGE);let r=await pu(t,{gate_id:e.id??e.gate,limit:n});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function gC(e,t,n){if(e==="presets"){if(t.preset??t.id)return Ti(_g(t.preset??t.id),Ac(t));let i=ar.map(a=>{let o=Ti(a,"pm-owner");return{id:a,title:o.title,description:o.description}});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return gn(()=>Hu(n,_g(t.preset??t.id),Ac(t),{author:t.author,message:t.message}));if(e==="derive"){let i=await zu(await Dr(n,{resolve_tree:!1,trigger:"derive"}),Ac(t)),a=t.apply?await gn(()=>Wu(n,i,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:i,count:i.length,...a?{applied:a}:{}}}if(!t.id)return Un("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new y("assurance promote requires --enforcement warn|block",g.USAGE);let r=await _o(n,"assertion",t.id);return gn(()=>Gu(n,r,t.enforcement,{author:t.author,message:t.message}))}async function yC(e,t,n){if(!e.id)return Un("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let r=e.id;if(!e.trigger)throw new y("assurance run requires a trigger",g.USAGE);if(!Gt.includes(e.trigger))throw new y(`Unknown assurance trigger ${e.trigger}. Expected: ${Gt.join(", ")}`,g.USAGE);let i=e.trigger,[a,o]=await Promise.all([fC(t),Dr(t,{...n.workspace,tree_id:e.tree,trigger:i})]),s=await Xd(()=>lu(r,a,o,{trigger:i,dry_run:e.dry_run===!0}));return s.dry_run||await mu(t,s,{author:e.author,message:e.message}),s}function yg(e){throw e instanceof y?e:new y(e instanceof Error?e.message:"assurance risk request is invalid",g.USAGE)}function wC(e){if(e.limit!==void 0)throw new y(`assurance ${e.action} does not accept --limit; set limit inside the definition`,g.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new y(`assurance ${e.action} definition must be valid JSON`,g.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?pg(t):Zr(t)}catch(n){return yg(n)}}function vC(e,t){let n=new Set;for(let[r,i]of t)e.item_fingerprints.get(r)!==i&&n.add(r);for(let r of e.item_fingerprints.keys())t.has(r)||n.add(r);return n}function bC(e,t,n){let r=T(t.policy),i=xc?.pm_root===e?xc:void 0,a=new Map(n.map(l=>[l.id,dC("sha256").update(T([Ll(l),Xr(l)])).digest("hex")])),o=i?.policy_serialized===r?i:void 0,s=o?vC(o,a):new Set,c=jl(t.policy,o?n.filter(l=>s.has(l.id)):n,o?{previous_index:o.index,changed_item_ids:[...s]}:{});return xc={pm_root:e,policy_serialized:r,item_fingerprints:a,index:c},c}async function kC(e,t){let n=wC(e),r=await Dr(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?Fl(bC(t,n,r.items),n.change,{cursor:n.cursor,limit:n.limit}):fg(n.policy,r.items,n)}catch(i){return yg(i)}}async function SC(e,t={},n={}){let r=uC(e.action),i=L(process.cwd(),t.path);if(r==="presets"||r==="apply"||r==="derive"||r==="promote")return gC(r,e,i);if(r==="verdicts")return _C(e,i);if(r==="run")return yC(e,i,n);if(["risk","lineages"].includes(r))return kC(e,i);let a=mC(e.kind);if(r==="list")return er(i,a);if(!e.id)return Un("id",`assurance ${r} requires an id`,`pm assurance ${r} ${a} <id>`);let o=e.id;if(r==="show")return _o(i,a,o);if(r==="remove"){let d=await gn(()=>uu(i,a,o,{author:e.author,message:e.message}));return gg(d,e.idOnly)}let s=pC(a,e.definition);if(s.id!==o)throw new y(`Assurance definition id ${s.id} does not match requested id ${o}`,g.USAGE);let c={author:e.author,message:e.message,...a==="assertion"?{authorized_decision_ids:await hC(i,s)}:{}},l=await gn(()=>Si(i,a,s,c));return gg(l,e.idOnly)}function KW(e,t,n){let r={...e,...t};return SC({action:P(r,"subcommand")??P(r,"assuranceAction")??P(r,"operation")??"",kind:P(r,"kind"),id:P(r,"id"),definition:r.definition,trigger:P(r,"trigger"),tree:P(r,"treeId")??P(r,"tree"),gate:P(r,"gate"),limit:vo(r.limit,"assurance verdict limit"),dry_run:r.dryRun===!0||r.dry_run===!0,fullChangedFields:r.fullChangedFields===!0,idOnly:r.idOnly===!0,author:P(r,"author"),message:P(r,"message"),preset:P(r,"preset"),owner:P(r,"owner"),apply:r.apply===!0,enforcement:P(r,"enforcement")},n)}import Hn from"node:fs/promises";import Ta from"node:path";import Ca from"node:fs/promises";import Rc from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4fe37a62-2d0f-55f6-bb98-7162e7e8b8fe")}catch{}})();var EC=864e5;function xC(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function IC(e,t){let n;try{n=await Ca.readdir(e,{withFileTypes:!0})}catch(i){if(U(i))return[];throw i}let r=[];for(let i of n)if(i.isDirectory()){let a=Rc.join(e,i.name),o;try{o=await Ca.readdir(a)}catch(s){U(s)||t.push(`checkpoint_subdir_unreadable:${i.name}`);continue}for(let s of o)s.endsWith(".json")&&r.push(`${i.name}/${s}`)}else i.name.endsWith(".json")&&r.push(i.name);return r.sort()}async function wg(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Math.max(0,t.retentionDays)*EC,o=Rc.join(e,"checkpoints"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await IC(o,s.warnings);for(let l of c){let d=Rc.join(o,l),u=`checkpoints/${l}`;s.scanned+=1,r?.onRead&&s.warnings.push(...await r.onRead(d));let m;try{m=await Ca.readFile(d,"utf8")}catch(w){if(U(w)){s.scanned-=1;continue}s.warnings.push(`checkpoint_unreadable:${l}`),s.retained.push(u),s.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let f=xC(m),p=f===null?Number.NaN:Date.parse(f);if(!Number.isFinite(p)){s.warnings.push(`checkpoint_unparseable:${l}`),s.retained.push(u),s.entries.push({file:u,created_at:f,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=i-p,_={file:u,created_at:f,age_seconds:Math.floor(h/1e3),stale:h>a,reason:h>a?"expired":"active"};if(!_.stale){s.retained.push(u),s.entries.push(_);continue}if(!n){try{await Ca.unlink(d)}catch(w){if(!U(w)){s.warnings.push(`checkpoint_remove_failed:${l}`),s.retained.push(u),s.entries.push(_);continue}}r?.onWrite&&s.warnings.push(...await r.onWrite(d))}s.removed.push(u),s.entries.push(_)}return s}import Cc from"node:fs/promises";import vg from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9c0640f0-505c-5f4a-bb7a-daa3cc775239")}catch{}})();var AC=1440*60*1e3,RC=new Set(["committed","compensated"]);function CC(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function TC(e,t,n,r,i){let a=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(a))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let o=r-a;return RC.has(t)?o>i?{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(o/1e3),stale:!1,reason:"active"},remove:!1}}async function $C(e,t,n,r){let i=r.hooks?.onRead?await r.hooks.onRead(e):[],a=CC(await Cc.readFile(e,"utf8")),o=TC(t,a.status,a.updatedAt,r.nowMs,r.retentionMs);return o.entry.reason==="unparseable"&&i.push(`transaction_journal_unparseable:${n}`),o.remove&&!r.dryRun&&(await Cc.rm(e,{force:!0}),r.hooks?.onWrite&&i.push(...await r.hooks.onWrite(e))),{decision:o,warnings:i}}async function bg(e,t){let{dryRun:n,hooks:r}=t,i=t.now??Date.now(),a=Math.max(0,t.retentionDays)*AC,o=vg.join(e,"transactions","sdk"),s={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await Cc.readdir(o)).filter(l=>l.endsWith(".json")).sort((l,d)=>l.localeCompare(d))}catch(l){if(U(l))return s;throw l}for(let l of c){let d=vg.join(o,l),u=`transactions/sdk/${l}`,m=await $C(d,u,l,{dryRun:n,hooks:r,nowMs:i,retentionMs:a});s.warnings.push(...m.warnings),s.scanned+=1;let{decision:f}=m;if(!f.remove){s.retained.push(u),s.entries.push(f.entry);continue}s.removed.push(u),s.entries.push(f.entry)}return s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38736716-2644-5166-bfec-4ed4bca951b9")}catch{}})();var Pr=["index","embeddings","runtime","locks","checkpoints","transactions"],OC=1440*60*1e3,DC=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];async function PC(e,t,n){let r=t.relativePath,i=Ta.join(e,r),a=await ze({path:i,scope:"project"});try{let o=await Hn.stat(i);if(t.kind==="file"&&!o.isFile())return{removed:!1,warnings:[...a,`not_a_file:${r}`]};if(t.kind==="directory"&&!o.isDirectory())return{removed:!1,warnings:[...a,`not_a_directory:${r}`]};if(n)return{removed:!0,warnings:a};t.kind==="file"?await Hn.unlink(i):await Hn.rm(i,{recursive:!0,force:!0});let s=await X({path:i,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...a,...s]}}catch(o){if(U(o))return{removed:!1,warnings:a};throw o}}async function NC(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],r=[],i=[],a=[],o=Date.now()-OC;for(let s of n){let c=Ta.join(e,s.relativePath);if(!await O(c))continue;let l=(await Hn.readdir(c)).filter(d=>d.startsWith(s.prefix)).sort();for(let d of l){let u=Ta.posix.join(s.relativePath,d),m=Ta.join(c,d);a.push(...await ze({path:m,scope:"project"}));let f=await Hn.stat(m).catch(p=>{if(!U(p))throw p});if(f){if(f.mtimeMs>o){i.push(u);continue}r.push(u),!t&&(await Hn.rm(m,{recursive:!0,force:!0}),a.push(...await X({path:m,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:r,retained:i,warnings:a}}function LC(e){if(!e||e.length===0)return[...Pr];let t=e.flatMap(r=>r.split(",")).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);if(t.length===0)throw new y(`--scope requires at least one value (${Pr.join(",")})`,g.USAGE);let n=new Set;for(let r of t){if(!Pr.includes(r))throw new y(`Invalid --scope value "${r}". Expected one or more of: ${Pr.join(", ")}`,g.USAGE);n.add(r)}return Pr.filter(r=>n.has(r))}function MC(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),r=e.removed.some(i=>i==="index/manifest.json"||i==="search/embeddings.jsonl"||i==="search/vectorization-status.json"||i==="search/lancedb"||i==="search/pending-refresh.json"||i==="search/pending-refresh.gate.lock");return n&&r&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(i=>i.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(i=>i.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function yG(e,t={}){let n=L(process.cwd(),e.path);await te(n);let r=await C(n),i=t.dryRun===!0,a=LC(t.scope),o=DC.filter(p=>a.includes(p.scope)),s=[],c=[],l=[];for(let p of o){let h=await PC(n,p,i);h.removed?s.push(p.relativePath):c.push(p.relativePath),l.push(...h.warnings)}if(a.includes("runtime")){let p=await NC(n,i);s.push(...p.removed),c.push(...p.retained),l.push(...p.warnings)}let d;if(a.includes("locks")){let p=await Sm(n,{dryRun:i,hooks:{onRead:h=>ze({path:h,scope:"project"}),onWrite:h=>X({path:h,scope:"project",op:"gc:lock_remove"})}});s.push(...p.removed),c.push(...p.retained),l.push(...p.warnings),d={scanned:p.scanned,removed:p.removed.length,retained:p.retained.length}}let u;if(a.includes("transactions")){let p=r.checkpoints.retention_days,h=await bg(n,{dryRun:i,retentionDays:p,hooks:{onRead:_=>ze({path:_,scope:"project"}),onWrite:_=>X({path:_,scope:"project",op:"gc:transaction_journal_remove"})}});s.push(...h.removed),c.push(...h.retained),l.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:p}}let m;if(a.includes("checkpoints")){let p=r.checkpoints.retention_days,h=await wg(n,{dryRun:i,retentionDays:p,hooks:{onRead:_=>ze({path:_,scope:"project"}),onWrite:_=>X({path:_,scope:"project",op:"gc:checkpoint_remove"})}});s.push(...h.removed),c.push(...h.retained),l.push(...h.warnings),m={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:p}}l.push(...await Yr({mode:i?"gc:dry-run":"gc",total_items:o.length}));let f=MC({dryRun:i,scopes:a,removed:s});return{ok:l.length===0,dry_run:i,scope:a,removed:s,retained:c,warnings:l,...d?{locks:d}:{},...m?{checkpoints:m}:{},...u?{transactions:u}:{},guidance:f,generated_at:$()}}import{execFile as jC}from"node:child_process";import FC from"node:path";import{promisify as UC}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7fe99df0-8454-5667-9205-0b861ba212d1")}catch{}})();var HC=UC(jC),Sg="@unbrained/pm-cli",zC="latest",WC={global:["--global"],project:[]};function kg(e){let t=e.project===!0||e.local===!0||e.scope==="project",n=e.global===!0||e.scope==="global";if(t&&n)throw new y('Options "--project/--local" and "--global" are mutually exclusive.',g.USAGE);return n?"global":"project"}function Oa(e){return e.trim().toLowerCase()}function Eg(e,t){let n=Oa(t);return[e.name,e.directory,e.source.input,e.source.location,e.source.package,e.source.repository,e.source.owner&&e.source.repo?`${e.source.owner}/${e.source.repo}`:void 0].some(r=>typeof r=="string"&&Oa(r)===n)}function GC(e,t){let n=L(process.cwd(),t.path),r=nn(n,process.cwd());return{selected_root:e==="global"?r.global:r.project}}async function qC(e,t,n){try{let r=await HC(e,t,{cwd:n?.cwd,encoding:"utf8"});return{stdout:r.stdout,stderr:r.stderr}}catch(r){let i=typeof r=="object"&&r!==null&&"stderr"in r?String(r.stderr??""):"",a=i.trim().length>0?i.trim():r instanceof Error?r.message:String(r);throw new y(`Command failed: ${e} ${t.join(" ")}
68
+ ${a}`,g.GENERIC_FAILURE)}}function Da(e){return typeof e.tag=="string"&&e.tag.trim().length>0?e.tag.trim():zC}function $a(e){return typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():Sg}async function BC(e,t){let n=e.commandRunner??qC,r=$a(e),i=Da(e),a=`${r}@${i}`,o=["npm","install","-g",a];e.repair===!0&&o.push("--force");let s=Jc(import.meta.url,["../../.."]),c={requested:!0,status:"planned",package:r,target:a,command:o,before_version:s,...r===Sg?{migration_guidance:["Calendar scheduling commands are package-owned. If calendar is absent, run pm package install calendar --project; use pm calendar meet, pm calendar event, or pm calendar remind."]}:{},repair:e.repair===!0};if(t)return c;try{await n(o[0],o.slice(1));let l=await n("pm",["--version"]);return{...c,status:"updated",after_version:l.stdout.trim()||void 0}}catch(l){return{...c,status:"failed",error:l instanceof Error?l.message:String(l)}}}function VC(e){return FC.isAbsolute(e)||e.startsWith(".")||e.startsWith("..")||e.startsWith("file:")}function JC(e,t){if(e.kind==="npm"){let n=e.input.startsWith("npm:")?e.input.slice(4).trim():e.input.trim();return!VC(n)&&e.package&&e.package.trim().length>0?`npm:${e.package.trim()}@${t}`:e.input.startsWith("npm:")?e.input:`npm:${e.input}`}return e.input}async function KC(e,t){let n=JC(e,t);return e.kind!=="local"||await O(n)?n:await O(e.location)?e.location:n}function YC(e,t,n,r){let i=["pm","package","install",t,n==="global"?"--global":"--project"];return e.kind==="github"&&r&&r.trim().length>0&&i.push("--ref",r.trim()),i}async function xg(e,t){let n=GC(e,t);return(await be(n.selected_root)).state.entries.filter(r=>r.scope===e)}async function XC(e,t,n){let r=await xg(e,t);return r.find(i=>Eg(i,n.name))??r.find(i=>Oa(i.directory)===Oa(n.directory))}async function ZC(e,t,n,r,i){let a=Da(t),o=await KC(e.source,a),s=YC(e.source,o,r,e.source.ref),c={name:e.name,directory:e.directory,scope:r,source:e.source,status:"planned",command:s,previous_version:e.manifest_version};if(i)return c;try{await vs(o,{install:!0,project:r==="project",global:r==="global",ref:e.source.kind==="github"?e.source.ref:void 0},n);let l=await XC(r,n,e);return{...c,status:"updated",installed_version:l?.manifest_version}}catch(l){return{...c,status:"failed",error:l instanceof Error?l.message:String(l)}}}function QC(e,t,n,r){let i=[n?e.status:void 0,...t.map(a=>a.status)].filter(a=>typeof a=="string");return{requested_cli:n,requested_packages:r,planned:i.filter(a=>a==="planned").length,updated:i.filter(a=>a==="updated").length,skipped:i.filter(a=>a==="skipped").length,failed:i.filter(a=>a==="failed").length}}async function IG(e,t,n){let r=typeof e=="string"&&e.trim().length>0?e.trim():void 0;if(t.cliOnly===!0&&t.packagesOnly===!0){let m=["package","upgrade",...r?[r]:[],"--packages-only","--dry-run",...WC[kg(t)]];throw new y('Options "--cli-only" and "--packages-only" are mutually exclusive.',g.USAGE,{code:"package_upgrade_modes_mutually_exclusive",recovery:{suggested_retry:Xe(m),suggested_retry_args:m}})}let i=kg(t),a=t.dryRun===!0;if(t.cliOnly===!0&&r)throw new y('A package target cannot be used with "--cli-only".',g.USAGE);let o=!(t.packagesOnly===!0||r),s=t.cliOnly!==!0,c=o?await BC(t,a):{requested:!1,status:"skipped",package:$a(t),target:`${$a(t)}@${Da(t)}`,command:["npm","install","-g",`${$a(t)}@${Da(t)}`],repair:t.repair===!0,reason:"not_requested"},l=s?await xg(i,n):[];if(r&&(l=l.filter(m=>Eg(m,r)),l.length===0))throw new y(`Managed package "${r}" was not found in ${i} scope.`,g.NOT_FOUND);let d=[];for(let m of l)d.push(await ZC(m,t,n,i,a));let u=QC(c,d,o,s);return{ok:u.failed===0,action:"upgrade",dry_run:a,scope:i,target:r,cli:c,packages:d,summary:u}}import{createHash as eT}from"node:crypto";import{isUtf8 as tT}from"node:buffer";import Nr from"node:fs/promises";import Tc from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a049f799-3807-59b5-96de-51e900798779")}catch{}})();async function Ig(e){try{return(await Nr.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(U(t))return[];throw t}}function nT(e,t,n,r){let i=t.at(-1),a;for(let c=t.length-1;c>=0;c-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[c].op)){a=t[c];break}let o=t[0]?.context?.history_compaction,s=typeof o=="object"&&o!==null&&"pruned_stream_digest"in o&&typeof o.pruned_stream_digest=="string"?o.pruned_stream_digest:null;return{id:e,entries:t.length,bytes:n,stream_digest:r,latest_after_hash:i?.after_hash??null,latest_record_hash:i?.record_hash??null,latest_hash_algorithm:i?Re(i.hash_algorithm):null,rewrite_count:t.reduce((c,l)=>c+(l.reanchor_evidence?.length??0),0),checkpoint_digest:s,last_maintenance:a?{op:a.op,ts:a.ts,record_hash:a.record_hash??null}:null}}function rT(e,t,n){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!tT(t))return null;let r=[];for(let i of t.toString("utf8").split(/\r?\n/u)){if(!i.trim())continue;let a=JSON.parse(i);if(typeof a!="object"||a===null||Array.isArray(a))return null;let o=a;if(![o.op,o.author,o.ts,o.before_hash,o.after_hash].every(s=>typeof s=="string")||!Array.isArray(o.patch))return null;r.push(o)}return Vn(r).ok?nT(e,r,t.length,n):null}catch{return null}}async function $c(e,t){if(!(await Nr.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let n=Tc.join(e,"history"),r=await Ig(n),i=new Map,a=[];for(let o of r){let s=o.slice(0,-6),c={id:s,digest:null,stream:null};a.push(c);let l=Tc.join(n,o);try{let d=await Nr.lstat(l);if(i.set(o,T([d.ino,d.size,d.mtimeMs,d.ctimeMs])),!d.isFile())continue;let u=await Nr.readFile(l);c.digest=eT(t).update(u).digest("hex"),c.stream=rT(s,u,c.digest)}catch{}}if(T(r)!==T(await Ig(n)))throw new TypeError("attestation history inventory changed during read; retry");for(let[o,s]of i){let c=await Nr.lstat(Tc.join(n,o));if(s!==T([c.ino,c.size,c.mtimeMs,c.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54d3c0f4-e663-5e31-aa4e-45ea2f6aaf75")}catch{}})();function Oc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dc(e,t){return Object.keys(e).length===t.length&&t.every(n=>Object.hasOwn(e,n))}function zn(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function iT(e){return e.entries===0?[e.latest_hash_algorithm,e.latest_after_hash,e.latest_record_hash,e.checkpoint_digest,e.last_maintenance].every(t=>t===null)&&e.rewrite_count===0:e.latest_hash_algorithm!=="sha256"&&e.latest_hash_algorithm!=="sha512"?!1:zn(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||zn(e.latest_record_hash,e.latest_hash_algorithm))}function aT(e){return e===null?!0:!Oc(e)||!Dc(e,["op","ts","record_hash"])?!1:typeof e.op=="string"&&["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(e.op)&&typeof e.ts=="string"&&St(e.ts)&&(e.record_hash===null||zn(e.record_hash,"sha256")||zn(e.record_hash,"sha512"))}function oT(e,t){return!Oc(e)||!Dc(e,["id","entries","bytes","stream_digest","latest_after_hash","latest_record_hash","latest_hash_algorithm","rewrite_count","checkpoint_digest","last_maintenance"])?!1:typeof e.id=="string"&&/^[A-Za-z0-9_-]+$/u.test(e.id)&&[e.entries,e.bytes,e.rewrite_count].every(n=>typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)&&zn(e.stream_digest,t)&&iT(e)&&(e.checkpoint_digest===null||zn(e.checkpoint_digest,"sha256"))&&aT(e.last_maintenance)}function Ag(e){if(!Oc(e)||!Dc(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==Ya.format||e.version!==1||typeof e.generated_at!="string"||!St(e.generated_at)||!Array.isArray(e.streams)||e.hash_algorithm!=="sha256"&&e.hash_algorithm!=="sha512")throw new TypeError("Invalid history attestation format");let t=e.hash_algorithm,n;for(let a of e.streams){if(!oT(a,t))throw new TypeError("Invalid history attestation stream");let o=a.id;if(n!==void 0&&o<=n)throw new TypeError("Invalid history attestation stream order");n=o}let{workspace_digest:r,...i}=e;if(Xa(T(i),t)!==r)throw new TypeError("History attestation rollup mismatch");return e}async function Rg(e={}){let t=Re(e.hashAlgorithm),n=e.generatedAt??$();if(!St(n))throw new TypeError("Invalid history attestation timestamp");let r=await $c(L(e.cwd??process.cwd(),e.pmRoot),t),i=r.filter(o=>o.stream===null);if(i.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${i.map(o=>o.id).join(", ")}`);let a={format:Ya.format,version:1,hash_algorithm:t,generated_at:n,streams:r.map(o=>o.stream)};return Ag({...a,workspace_digest:Xa(T(a),t)})}async function Cg(e,t={}){let n=Ag(e),r=await $c(L(t.cwd??process.cwd(),t.pmRoot),n.hash_algorithm),i=new Map(r.map(d=>[d.id,d])),a=new Map(n.streams.map(d=>[d.id,d])),o=n.streams.filter(d=>!i.has(d.id)).map(d=>d.id),s=r.filter(d=>!a.has(d.id)).map(d=>d.id),c=r.filter(d=>d.stream===null).map(d=>d.id),l=[];for(let d of n.streams){let u=i.get(d.id);u&&(u.digest!==d.stream_digest||T(u.stream)!==T(d))&&l.push({id:d.id,before_digest:d.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:o.length+s.length+c.length+l.length===0,workspace_digest:n.workspace_digest,streams_checked:r.length,changed_streams:l.map(d=>d.id),missing_streams:o,added_streams:s,invalid_streams:c,transitions:l}}import Tg from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3bca4afb-f1cc-5627-a377-b30e8005a284")}catch{}})();async function YG(e,t){for(let r of["verify","output","hashAlgorithm"]){let i=e[r];if(!(r==="verify"&&typeof i=="object"&&i!==null)&&i!==void 0&&(typeof i!="string"||i.trim().length===0))throw new y(`history attest ${r} requires a nonempty string.`,g.USAGE)}if(e.verify!==void 0){if(e.output!==void 0||e.hashAlgorithm!==void 0)throw new y("history attest --verify cannot be combined with --output or --hash-algorithm",g.USAGE);let r;try{r=typeof e.verify=="string"?JSON.parse(await Tg.readFile(e.verify,"utf8")):e.verify}catch{throw new y("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",g.USAGE)}return Cg(r,{pmRoot:t.path})}let n=await Rg({pmRoot:t.path,hashAlgorithm:Re(e.hashAlgorithm)});if(e.output===void 0)return n;try{await Tg.writeFile(e.output,`${JSON.stringify(n,null,2)}
69
+ `,{flag:"wx",mode:384})}catch{throw new y("Cannot create history attestation proof. Choose --output with a new filename in a writable directory; existing files are never overwritten.",g.USAGE)}return{output:e.output,workspace_digest:n.workspace_digest,streams:n.streams.length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="42dc4379-016c-5b5d-a15b-37fe3a80dab5")}catch{}})();function $g(e){return e.invalidEvidenceCount>0?"merge_evidence_invalid":e.historyEvidenceValid?e.pendingDecisionCount>0||e.losslessCount>0?"merge_reconciliation_required":e.driftedItemCount>0?"history_repair_required":e.fence.status!=="ok"||e.drivers===null||e.drivers.status!=="ok"?"merge_fence_unprepared":"ready":"history_evidence_invalid"}function Og(e,t,n=process.platform){let r=["--pm-path",t];return e==="merge_evidence_invalid"?Xe([...r,"merge","report"],n):e==="history_evidence_invalid"?Xe([...r,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?Xe([...r,"merge","reconcile"],n):e==="history_repair_required"?Xe([...r,"history-repair","--all"],n):e==="merge_fence_unprepared"?Xe([...r,"merge","install"],n):null}function Dg(e){let t=Array.isArray(e.drifted_items)?e.drifted_items.filter(n=>typeof n=="string"):[];return{evidence_valid:Array.isArray(e.drifted_items)&&e.drifted_items.every(n=>typeof n=="string")&&typeof e.drifted_items_count=="number"&&Number.isInteger(e.drifted_items_count)&&e.drifted_items_count>=0&&typeof e.drifted_items_truncated=="boolean"&&typeof e.counts=="object"&&e.counts!==null&&!Array.isArray(e.counts),drifted_item_count:typeof e.drifted_items_count=="number"?e.drifted_items_count:t.length,drifted_item_ids:t,drifted_item_ids_truncated:e.drifted_items_truncated===!0,counts:typeof e.counts=="object"&&e.counts!==null?e.counts:{}}}async function lq(e){let t=L(process.cwd(),e.path);await te(t);let n=await C(t),r=W(n,H()),i=[],a=await ba({includeBody:!0,pmRoot:t,settings:n,typeToFolder:r.type_to_folder,warnings:i}),o=await et(t),[s,c,l,d]=await Promise.all([In(t,At(n)),o===null?Promise.resolve(null):An(o),gt(o??t,{includeLossless:!0,pmRoot:t}),ka(t,a,!1)]),{pendingDecisions:u,lossless:m}=Pn(l.receipts),f=[...new Set(u.map(w=>w.item_id))].sort((w,v)=>w.localeCompare(v)),p=d.check.details,h=Dg(p),_=$g({invalidEvidenceCount:l.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:m.length,historyEvidenceValid:h.evidence_valid,driftedItemCount:h.drifted_item_count,fence:s,drivers:c});return{ok:_==="ready",state:_,merge_fence:{committed:s,clone_local_drivers:c},merge_receipts:{pending_decision_count:u.length,pending_item_ids:f.slice(0,25),pending_item_ids_truncated:f.length>25,lossless_count:m.length,invalid_evidence_count:l.invalid_evidence_count},history_drift:h,next_action:{command:Og(_,t),reason:_},warnings:[...new Set(i)].sort((w,v)=>w.localeCompare(v)),generated_at:$()}}function dq(e){let t=e.next_action.command??"none";return[`workspace_position: ${e.state}`,`merge_fence: ${e.merge_fence.committed.status}`,`clone_local_drivers: ${e.merge_fence.clone_local_drivers?.status??"unavailable"}`,`pending_merge_decisions: ${e.merge_receipts.pending_decision_count}`,`history_drifted_items: ${e.history_drift.drifted_item_count}`,`next_action: ${t}`].join(`
70
+ `)}var uq={commandForWorkspacePositionState:Og,normalizeWorkspaceHistoryDrift:Dg,selectWorkspacePositionState:$g};import sT from"node:fs/promises";import Lr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f02db25d-bedb-5411-b50a-de0fea51a117")}catch{}})();var Pc="index/manifest.json",Nc="search/embeddings.jsonl",cT="Provider or model has changed since last index. Run pm reindex --mode semantic to rebuild.";function lT(e){return e.progress===!0||process.stderr.isTTY===!0}function le(e,t){if(e)try{process.stderr.write(`[pm reindex] ${t}
71
+ `)}catch{}}function dT(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new y("Reindex mode must be one of keyword|semantic|hybrid",g.USAGE)}async function uT(e,t,n,r){let i=[];return{candidates:await Id(e,t,n,i,r),warnings:i}}async function Mc(e,t,n,r,i){let a=tn(H()),o=[];for(let s of t)if(!(i&&!i.has(s.metadata.id))){if(typeof s.body=="string"){o.push({metadata:s.metadata,body:s.body});continue}try{let c=await sT.readFile(s.item_path,"utf8"),l=Et(c,{format:s.item_format,schema:n,extensionFieldNames:a,onWarning:d=>r.push(d)});o.push({metadata:s.metadata,body:l.body})}catch{r.push(`item_list_item_read_failed:${Lr.relative(e,s.item_path)}`),o.push({metadata:s.metadata,body:""})}}return o}function mT(e,t,n){let r=e.metadata;return{id:r.id,mode:t,updated_at:r.updated_at,corpus:Cd(e,{fields:n})}}var Wn=ee;function pT(e){let t=H(),n=Wn(e.search?.provider);if(!n)return null;let r=ld(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,a=Wn(i.name)??Wn(r.definition.name);if(!a)return null;let o=i.embedBatch,s=i.embed_batch,c=i.embed,l=typeof o=="function"?o:typeof s=="function"?s:void 0,d=typeof c=="function"?c:void 0;return!l&&!d?null:{name:a,embedBatch:l,embed:d}}function fT(e){let t=H(),n=Wn(e.vector_store?.adapter);if(!n)return null;let r=dd(t,n);if(!r)return null;let i=r.runtime_definition??r.definition,a=Wn(i.name)??Wn(r.definition.name);if(!a)return null;let o=i.upsert,s=i.delete;return{adapterName:a,...typeof o=="function"?{upsert:o}:{},...typeof s=="function"?{delete:s}:{}}}function Lc(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new y(`Invalid vector returned by ${t}`,g.GENERIC_FAILURE);return e}async function hT(e,t,n){let r=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let a=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:r}));if(!Array.isArray(a))throw new y(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,g.GENERIC_FAILURE);return a.map((o,s)=>Lc(o,`extension search provider "${e.name}" embedBatch output at index ${s}`))}if(!e.embed)throw new y(`Extension search provider "${e.name}" does not implement embed/embedBatch`,g.GENERIC_FAILURE);let i=[];for(let[a,o]of n.entries()){let s=await Promise.resolve(e.embed({input:o,settings:t,model:r}));i.push(Lc(s,`extension search provider "${e.name}" embed output at index ${a}`))}return i}function Pg(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function Ng(e,t,n){let r=n?Wt(n.name,Pg(e)):t?Wt(t.name,t.model):null;if(!r)throw new y("No embedding identity available for semantic reindex mode",g.USAGE);return r}function _T(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,r)=>n.localeCompare(r))}async function Lg(e,t,n,r,i,a,o,s){let c=r?.name??n?.name,l=Td(c,e.search.embedding_corpus_max_characters).maxCharacters,d=ro(e),u=i.map(p=>$d(p,{providerName:c,maxCharacters:l,fields:d})),m=[],f=null;if(r)try{m=await hT(r,e,u),f=Wt(r.name,Pg(e))}catch(p){if(!n)throw new y(`Extension search provider "${r.name}" failed to generate embeddings: ${p instanceof Error?p.message:String(p)}`,g.GENERIC_FAILURE);a.push(`Extension search provider "${r.name}" failed; falling back to built-in provider (${p instanceof Error?p.message:String(p)})`)}if(m.length===0){if(!n)throw new y(`No embedding executor available for reindex mode '${t}'`,g.USAGE);let p=await Od(n,e,u,{onProgress:h=>{h.phase==="complete"&&(o.batches_completed=h.batch_index),le(s,`embedding_batch_${h.phase} batch=${h.batch_index}/${h.batch_total} size=${h.batch_size} completed_inputs=${h.completed_inputs}/${h.total_inputs}`)}});a.push(...p.warnings),o.batching=p.receipt,m=p.vectors,f=Wt(n.name,n.model)}if(le(s,`embedding_complete vectors=${m.length}`),m.length!==i.length)throw new y(`Embedding output size mismatch (expected ${i.length}, received ${m.length})`,g.GENERIC_FAILURE);if(!f)throw new y(`No embedding identity available for reindex mode '${t}'`,g.USAGE);return{vectors:m,embeddingIdentity:f}}async function gT(e,t,n,r,i,a){let o=Object.keys(n);if(t){if(o.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:o.sort((s,c)=>s.localeCompare(c)),settings:r}))}catch(s){throw new y(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${s instanceof Error?s.message:String(s)}`,g.GENERIC_FAILURE)}else o.length>0&&i.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${o.length}`);if(!e)return}e&&await Nd(e,o,{},a)}async function Mg(e,t,n,r,i){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:r}))}catch(a){throw new y(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${a instanceof Error?a.message:String(a)}`,g.GENERIC_FAILURE)}else i.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await Pd(e,n)}}function yT(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function wT(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(r=>({id:r.metadata.id,type:r.metadata.type,status:r.metadata.status,priority:r.metadata.priority,updated_at:r.metadata.updated_at}))}}function vT(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=Yn(e.settings);if(!t.active&&!e.extensionEmbedding)throw new y(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,g.USAGE);let n=_i(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new y(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,g.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function bT(e){let t=W(e.settings,H()),n=await uT(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(r=>({metadata:r.metadata,body:typeof r.body=="string"?r.body:""}))}}async function kT(e){let t=await _n(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return Ng(e.settings,Yn(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&hn(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(cT))}async function ST(e){let t=await _n(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=Ng(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),r=new Set(e.metadataDocuments.map(l=>l.metadata.id)),i=_T(t.entries,r),a=hn(t.embedding,n);e.forceFullSemantic&&!a&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let o=e.forceFullSemantic||a?e.metadataDocuments:e.metadataDocuments.filter(l=>t.entries[l.metadata.id]!==l.metadata.updated_at),s=new Set(o.map(l=>l.metadata.id)),c=s.size>0?await Mc(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,s):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:i,resetRequired:a,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function ET(e){let t=new Set(e.metadataDocuments.map(i=>i.metadata.id)),n=await Mc(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,le(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let r=await Lg(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...r,staleDocuments:n,vectorDimension:io(r.vectors,"Reindex embeddings")}}async function xT(e){let t=await Lg(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,r=t.embeddingIdentity,i=io(n,"Reindex embeddings");if(!(!e.resetRequired&&(hn(e.ledgerEmbedding,r)||Md(e.ledgerEmbedding,i))))return{vectors:n,embeddingIdentity:r,staleDocuments:e.staleDocuments,vectorDimension:i,resetRequired:e.resetRequired};let a=await ET(e);return n=a.vectors,r=a.embeddingIdentity,i=a.vectorDimension,{vectors:n,embeddingIdentity:r,staleDocuments:a.staleDocuments,vectorDimension:i,resetRequired:!0}}async function IT(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(le(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new y(`Extension vector adapter "${t}" does not support upserting vectors.`,g.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,le(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof y)throw t;if(!e.activeVectorStore)throw new y(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,g.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),le(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){le(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await Dd(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,le(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new y(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,g.USAGE)}function AT(e,t){return e.map((n,r)=>({id:n.metadata.id,vector:Lc(t[r],`reindex embeddings output at index ${r}`),payload:{id:n.metadata.id,type:n.metadata.type,status:n.metadata.status,priority:n.metadata.priority,updated_at:n.metadata.updated_at}}))}async function RT(e){le(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await xT({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(le(e.progressEnabled,"vector_reset_start"),await gT(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),le(e.progressEnabled,"vector_reset_complete")):await Mg(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=AT(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await IT({requestedMode:e.requestedMode,activeVectorStore:e.activeVectorStore,extensionVectorAdapter:e.extensionVectorAdapter,settings:e.settings,points:n,semanticWarnings:e.semanticWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled}),{staleDocuments:t.staleDocuments,embeddingMetadata:Ld(t.embeddingIdentity,t.vectorDimension)}}async function CT(e){let t=await ST(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(a=>[a.metadata.id,a.metadata.updated_at]));if(le(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return le(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await Mg(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let r=await RT({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let i=new Map(r.staleDocuments.map(a=>[a.metadata.id,a]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(a=>i.get(a.metadata.id)??a),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:r.embeddingMetadata}}async function TT(e){let t=Lr.join(e.pmRoot,Pc),n=Lr.join(e.pmRoot,Nc),r=ro(e.settings),i=e.documentsForKeywordArtifacts.map(o=>JSON.stringify(mT(o,e.mode,r))).join(`
72
+ `);le(e.progressEnabled,"writing keyword artifacts"),await Z(t,`${JSON.stringify(e.manifest,null,2)}
73
+ `),await Z(n,`${i}
74
+ `);let a=[];if(e.mode!=="keyword")try{le(e.progressEnabled,"writing vectorization status ledger"),await jd(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(o){a.push(`search_vectorization_status_ledger_write_failed:${o instanceof Error?o.message:String(o)}`)}return a}async function gq(e,t){let n=dT(e.mode),r=lT(e),i=e.full===!0;le(r,`start mode=${n}`);let a=L(process.cwd(),t.path);await te(a);let o=fi(await C(a)).settings,s=null;try{s=await re(a,gd,o.locks.ttl_seconds,G(void 0,"pm-reindex"),!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms)}catch(c){throw c instanceof y&&c.exitCode===g.CONFLICT?new y("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",g.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=pT(o),l=fT(o),d=vT({requestedMode:n,pmRoot:a,settings:o,extensionEmbedding:c,extensionVectorAdapter:l}),u=n;le(r,"loading item corpus");let m=await bT({pmRoot:a,settings:o}),f=m.warnings,{documentCandidates:p,metadataDocuments:h}=m;le(r,`loaded_items=${h.length}`);let _=$(),w=wT(u,_,h),v=Lr.join(a,Pc),S=Lr.join(a,Nc),k=u==="keyword"?await Mc(a,p,o.schema,f):h,x=[],D={},E=null,b=yT(u);if(u==="keyword"&&await kT({pmRoot:a,settings:o,forceFullSemantic:i,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let R=await CT({pmRoot:a,settings:o,requestedMode:n,activeEmbeddingProvider:d.activeEmbeddingProvider,activeVectorStore:d.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:l,documentCandidates:p,metadataDocuments:h,documentsForKeywordArtifacts:k,forceFullSemantic:i,reindexWarnings:f,semanticWarnings:x,semanticSummary:b,progressEnabled:r});k=R.documentsForKeywordArtifacts,D=R.vectorizationLedgerEntries,E=R.vectorizationEmbeddingMetadata}let N=await TT({pmRoot:a,mode:u,manifest:w,documentsForKeywordArtifacts:k,settings:o,vectorizationLedgerEntries:D,vectorizationEmbeddingMetadata:E,progressEnabled:r}),I=[...await X({path:v,scope:"project",op:"reindex:manifest"}),...await X({path:S,scope:"project",op:"reindex:embeddings"}),...await Yr({mode:u,total_items:h.length})];return le(r,"done"),{ok:!0,mode:u,total_items:h.length,semantic:b,artifacts:{manifest:Pc,embeddings:Nc},warnings:[...f,...x,...N,...I],generated_at:_}}finally{await s?.()}}export{M as a,Te as b,Ze as c,gn as d,Xd as e,Qd as f,Gt as g,co as h,Jg as i,mo as j,po as k,ru as l,wn as m,Qn as n,ho as o,py as p,lu as q,er as r,_o as s,Si as t,go as u,uu as v,mu as w,pu as x,Qm as y,TD as z,rv as A,iv as B,et as C,lP as D,xv as E,_y as F,qT as G,_u as H,wy as I,u$ as J,pb as K,pN as L,_N as M,gN as N,mr as O,yN as P,wN as Q,vN as R,bN as S,kN as T,SN as U,EN as V,xN as W,IN as X,AN as Y,RN as Z,gf as _,vs as $,aD as aa,um as ba,Ai as ca,W$ as da,P as ea,oe as fa,G$ as ga,vo as ha,q$ as ia,B$ as ja,Au as ka,V$ as la,J$ as ma,K$ as na,Ly as oa,Y$ as pa,X$ as qa,bo as ra,Z$ as sa,Q$ as ta,wo as ua,eO as va,tO as wa,Cu as xa,nO as ya,jy as za,Ou as Aa,mO as Ba,ir as Ca,pO as Da,qy as Ea,By as Fa,fO as Ga,Vy as Ha,h_ as Ia,wO as Ja,Fu as Ka,g_ as La,LH as Ma,MH as Na,ar as Oa,Ti as Pa,Hu as Qa,zu as Ra,Wu as Sa,Gu as Ta,Ju as Ua,Yu as Va,Xu as Wa,em as Xa,Dt as Ya,Jj as Za,Kj as _a,Yj as $a,Xj as ab,cF as bb,ih as cb,Ls as db,RF as eb,gt as fb,CF as gb,TF as hb,tx as ib,ax as jb,yh as kb,pw as lb,nm as mb,Us as nb,S1 as ob,E1 as pb,Oi as qb,Di as rb,Wh as sb,kU as tb,Gh as ub,Bh as vb,Vh as wb,Yh as xb,Zh as yb,RA as zb,CA as Ab,HH as Bb,zH as Cb,WH as Db,GH as Eb,$A as Fb,OA as Gb,DA as Hb,qH as Ib,v_ as Jb,NA as Kb,b_ as Lb,oc as Mb,S_ as Nb,LA as Ob,MA as Pb,jA as Qb,dc as Rb,uc as Sb,tz as Tb,nz as Ub,rz as Vb,hR as Wb,fW as Xb,dg as Yb,Dr as Zb,pg as _b,fg as $b,hg as ac,Ic as bc,SC as cc,KW as dc,yG as ec,IG as fc,Ag as gc,Rg as hc,Cg as ic,YG as jc,lq as kc,dq as lc,uq as mc,gq as nc};
75
+ //# sourceMappingURL=chunk-ECBOPEJE.js.map