@unbrained/pm-cli 2026.10.21 → 2026.10.23

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 (186) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +134 -77
  3. package/dist/cli/error-guidance.d.ts +12 -0
  4. package/dist/cli/error-guidance.js +2 -2
  5. package/dist/cli/register-setup.js +1 -1
  6. package/dist/cli-bundle/bundle-manifest.json +1 -1
  7. package/dist/cli-bundle/chunks/{chunk-DIR3YEFD.js → chunk-2LTGJ5DL.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-EMGMLKRV.js → chunk-2UX2TAN2.js} +15 -15
  9. package/dist/cli-bundle/chunks/{chunk-2B5HAZFK.js → chunk-3S5FLCG7.js} +2 -2
  10. package/dist/cli-bundle/chunks/chunk-5DKCD4KV.js +126 -0
  11. package/dist/cli-bundle/chunks/{chunk-V3XONSVC.js → chunk-5V4HU6GK.js} +48 -48
  12. package/dist/cli-bundle/chunks/{chunk-QPV6UD55.js → chunk-AAX7CNL7.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-TMXWWOPJ.js → chunk-AXGFNNI3.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-F76ZUP73.js +113 -0
  15. package/dist/cli-bundle/chunks/chunk-HDKY2YX3.js +3 -0
  16. package/dist/cli-bundle/chunks/{chunk-DR6DUBTU.js → chunk-KY34HTT2.js} +29 -29
  17. package/dist/cli-bundle/chunks/chunk-MMVX5L32.js +20 -0
  18. package/dist/cli-bundle/chunks/{chunk-C6SAXKBO.js → chunk-MTRYEVZR.js} +2 -2
  19. package/dist/cli-bundle/chunks/chunk-QSY55FTA.js +2 -0
  20. package/dist/cli-bundle/chunks/{chunk-GWIGZDRS.js → chunk-R7KWBFM2.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-5PZ7JNMI.js → chunk-REXCO5AG.js} +2 -2
  22. package/dist/cli-bundle/chunks/chunk-ZDVTXLA6.js +9 -0
  23. package/dist/cli-bundle/chunks/{chunk-DJQVNDXO.js → chunk-ZEI3DC5E.js} +6 -6
  24. package/dist/cli-bundle/chunks/{chunk-MOC5BJHW.js → chunk-ZMJF5HQW.js} +2 -2
  25. package/dist/cli-bundle/chunks/chunk-ZNDYAZZ6.js +6 -0
  26. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-65XXSPPR.js → indexed-receipt-blobs-XANVELIV.js} +2 -2
  27. package/dist/cli-bundle/chunks/{mutation-admission-FNWOVJLN.js → mutation-admission-P6LOBNLO.js} +2 -2
  28. package/dist/cli-bundle/chunks/{register-list-query-6PT5Y2EZ.js → register-list-query-JOB65KDN.js} +2 -2
  29. package/dist/cli-bundle/chunks/{register-mutation-TAIQV46L.js → register-mutation-QMNIN3RJ.js} +2 -2
  30. package/dist/cli-bundle/chunks/{register-operations-ONIRO22G.js → register-operations-Z4VET3I7.js} +2 -2
  31. package/dist/cli-bundle/chunks/register-setup-GNKWL3VL.js +2 -0
  32. package/dist/cli-bundle/chunks/{settlement-hook-UVFYSBMU.js → settlement-hook-YUVCO65H.js} +2 -2
  33. package/dist/cli-bundle/chunks/{stage-FCPVFO3B.js → stage-FW5OXCCR.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-VD64TPXI.js → chunk-4MNUQCGR.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/chunk-6GTZ24YV.js +3 -0
  36. package/dist/cli-bundle/focused-chunks/{chunk-XE7P7N5X.js → chunk-BM652VCB.js} +6 -6
  37. package/dist/cli-bundle/focused-chunks/{chunk-3LWH2RJC.js → chunk-BUZ2Z4P3.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/chunk-CGL36F6I.js +2 -0
  39. package/dist/cli-bundle/focused-chunks/{chunk-KVYUQS6Y.js → chunk-DWQMYLFM.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-4HJVAUFX.js → chunk-EDXTOAXP.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/chunk-FO4U3FIP.js +91 -0
  42. package/dist/cli-bundle/focused-chunks/chunk-GXKP56W7.js +2 -0
  43. package/dist/cli-bundle/focused-chunks/chunk-I2USTQNQ.js +2 -0
  44. package/dist/cli-bundle/focused-chunks/{chunk-44353U27.js → chunk-JDN34LEZ.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-CUWNNU4N.js → chunk-KI5YFKNN.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-7UD7XTOE.js → chunk-LEHGCPZ6.js} +11 -11
  47. package/dist/cli-bundle/focused-chunks/{chunk-HNCMYF2W.js → chunk-MLET6I3I.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-PDOWLRHC.js → chunk-NSMZY6IK.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/chunk-OMXMYTEX.js +26 -0
  50. package/dist/cli-bundle/focused-chunks/{chunk-JI3RXXRN.js → chunk-P7DPS5M4.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/chunk-R536272H.js +9 -0
  52. package/dist/cli-bundle/focused-chunks/{chunk-5IMM7GOF.js → chunk-UNTCCJPL.js} +3 -3
  53. package/dist/cli-bundle/focused-chunks/{chunk-32ZKLRWM.js → chunk-XIZYJDYW.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/chunk-Z5LDTMZ3.js +2 -0
  55. package/dist/cli-bundle/focused-chunks/chunk-ZHMF34DT.js +65 -0
  56. package/dist/cli-bundle/focused-chunks/{chunk-P5D7MHDS.js → chunk-ZR6ZKQUK.js} +15 -15
  57. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-CRP6HAZY.js → indexed-receipt-blobs-FVOA3XMI.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{mutation-admission-KM57KDDF.js → mutation-admission-HTFAIHJL.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{settlement-hook-MNCHFCAX.js → settlement-hook-2VXEB6PP.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{stage-UJYGWNZ7.js → stage-X3BUGEJT.js} +2 -2
  61. package/dist/cli-bundle/main.js +21 -21
  62. package/dist/cli-bundle/sdk-authoring.js +1 -1
  63. package/dist/cli-bundle/sdk-contracts.js +5 -2
  64. package/dist/cli-bundle/sdk-core.js +33 -33
  65. package/dist/cli-bundle/sdk-governance.js +1 -1
  66. package/dist/cli-bundle/sdk-graph.js +1 -1
  67. package/dist/cli-bundle/sdk-merge.js +58 -58
  68. package/dist/cli-bundle/sdk-query.js +1 -1
  69. package/dist/cli-bundle/sdk-runtime.js +1 -1
  70. package/dist/cli-bundle/sdk-testing.js +1 -1
  71. package/dist/cli-bundle/sdk.js +12 -9
  72. package/dist/core/config/nested-settings.js +1 -1
  73. package/dist/core/extensions/loader.js +1 -1
  74. package/dist/core/extensions/version-diagnostics.d.ts +2 -0
  75. package/dist/core/extensions/version-diagnostics.js +2 -0
  76. package/dist/core/lock/lock.d.ts +40 -6
  77. package/dist/core/lock/lock.js +3 -3
  78. package/dist/core/shared/errors.d.ts +28 -0
  79. package/dist/core/shared/errors.js +1 -1
  80. package/dist/core/store/item-store.js +1 -1
  81. package/dist/mcp/http-server.js +2 -2
  82. package/dist/mcp/server.d.ts +2 -2
  83. package/dist/mcp/server.js +2 -2
  84. package/dist/sdk/agent/command-recovery.d.ts +2 -0
  85. package/dist/sdk/agent/command-recovery.js +1 -1
  86. package/dist/sdk/cli-contracts/agent-output-contracts.js +1 -1
  87. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +6 -0
  88. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  89. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  90. package/dist/sdk/context-intent-contracts.d.ts +13 -0
  91. package/dist/sdk/context-intent-contracts.js +1 -1
  92. package/dist/sdk/contracts.d.ts +2 -1
  93. package/dist/sdk/contracts.js +1 -1
  94. package/dist/sdk/core.d.ts +2 -2
  95. package/dist/sdk/core.js +1 -1
  96. package/dist/sdk/define.d.ts +15 -16
  97. package/dist/sdk/define.js +1 -1
  98. package/dist/sdk/dependencies.js +1 -1
  99. package/dist/sdk/extension/doctor.js +1 -1
  100. package/dist/sdk/extension/install-receipts.js +1 -1
  101. package/dist/sdk/extension/install-snapshot.d.ts +11 -0
  102. package/dist/sdk/extension/install-snapshot.js +1 -1
  103. package/dist/sdk/extension.d.ts +12 -0
  104. package/dist/sdk/extension.js +1 -1
  105. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  106. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  107. package/dist/sdk/governance/health.d.ts +1 -0
  108. package/dist/sdk/governance/health.js +2 -2
  109. package/dist/sdk/index.d.ts +3 -2
  110. package/dist/sdk/index.js +1 -1
  111. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  112. package/dist/sdk/lifecycle/restore.js +1 -1
  113. package/dist/sdk/mcp/executable.d.ts +13 -0
  114. package/dist/sdk/mcp/executable.js +5 -0
  115. package/dist/sdk/merge/install.js +2 -2
  116. package/dist/sdk/public-surface.json +1 -1
  117. package/dist/sdk/query/context.d.ts +5 -0
  118. package/dist/sdk/query/context.js +2 -2
  119. package/dist/sdk/read-output/session-result.d.ts +39 -0
  120. package/dist/sdk/read-output/session-result.js +2 -0
  121. package/dist/sdk/read-output-contracts.d.ts +18 -5
  122. package/dist/sdk/read-output-contracts.js +1 -1
  123. package/dist/sdk/read-output-session.d.ts +2 -0
  124. package/dist/sdk/read-output-session.js +1 -1
  125. package/dist/sdk/relationship-context.js +1 -1
  126. package/dist/sdk/runtime-input.js +1 -1
  127. package/dist/sdk/runtime-primitives.d.ts +7 -1
  128. package/dist/sdk/runtime-primitives.js +1 -1
  129. package/dist/sdk/runtime.d.ts +11 -9
  130. package/dist/sdk/runtime.js +1 -1
  131. package/dist/sdk/workspace-snapshot.d.ts +5 -1
  132. package/dist/sdk/workspace-snapshot.js +3 -3
  133. package/dist/sdk/workspace.d.ts +3 -1
  134. package/dist/sdk/workspace.js +8 -5
  135. package/docs/CONFIGURATION.md +28 -3
  136. package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +30 -0
  137. package/docs/EXTENSION_AUTHOR_CONTRACTS.md +2 -1
  138. package/docs/EXTENSION_LIFECYCLE.md +47 -0
  139. package/docs/MCP_OPTION_CONFORMANCE.md +27 -1
  140. package/docs/MCP_REMOTE_TRANSPORT_SECURITY.md +16 -1
  141. package/docs/MERGE_SAFETY.md +8 -0
  142. package/docs/READ_OUTPUT_CONTRACTS.md +79 -0
  143. package/docs/RELATIONSHIP_GRAPH.md +15 -0
  144. package/docs/RELEASING.md +17 -0
  145. package/docs/SDK.md +76 -12
  146. package/docs/SDK_STORAGE_LIFECYCLE.md +2 -1
  147. package/docs/TESTING.md +16 -7
  148. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
  149. package/marketplace.json +1 -1
  150. package/package.json +1 -1
  151. package/packages/pm-beads/package.json +1 -1
  152. package/packages/pm-calendar/package.json +1 -1
  153. package/packages/pm-command-kit/package.json +1 -1
  154. package/packages/pm-digital-twin/package.json +1 -1
  155. package/packages/pm-governance-audit/package.json +1 -1
  156. package/packages/pm-guide-shell/package.json +1 -1
  157. package/packages/pm-kanban/package.json +1 -1
  158. package/packages/pm-lifecycle-hooks/package.json +1 -1
  159. package/packages/pm-linked-test-adapters/package.json +1 -1
  160. package/packages/pm-search-advanced/package.json +1 -1
  161. package/packages/pm-templates/package.json +1 -1
  162. package/packages/pm-todos/package.json +1 -1
  163. package/packages/pm-vcs/package.json +1 -1
  164. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  165. package/plugins/pm-claude/package.json +1 -1
  166. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  167. package/plugins/pm-codex/package.json +1 -1
  168. package/plugins/pm-codex/plugin.json +1 -1
  169. package/runtime-dependencies.json +1 -1
  170. package/dist/cli-bundle/chunks/chunk-4OYU5OXQ.js +0 -6
  171. package/dist/cli-bundle/chunks/chunk-DIKQ2AL5.js +0 -2
  172. package/dist/cli-bundle/chunks/chunk-KBSVPUFD.js +0 -113
  173. package/dist/cli-bundle/chunks/chunk-MZZIAC6S.js +0 -20
  174. package/dist/cli-bundle/chunks/chunk-NNB65OOO.js +0 -3
  175. package/dist/cli-bundle/chunks/chunk-V5GJTXYW.js +0 -126
  176. package/dist/cli-bundle/chunks/chunk-ZNKFMIVA.js +0 -6
  177. package/dist/cli-bundle/chunks/register-setup-OQMUZBJV.js +0 -2
  178. package/dist/cli-bundle/focused-chunks/chunk-6QSZHRM7.js +0 -6
  179. package/dist/cli-bundle/focused-chunks/chunk-E2S42XCT.js +0 -2
  180. package/dist/cli-bundle/focused-chunks/chunk-GRSQGMRR.js +0 -2
  181. package/dist/cli-bundle/focused-chunks/chunk-IAGFXKMZ.js +0 -3
  182. package/dist/cli-bundle/focused-chunks/chunk-JMZPZQHR.js +0 -26
  183. package/dist/cli-bundle/focused-chunks/chunk-O3M6YWVL.js +0 -2
  184. package/dist/cli-bundle/focused-chunks/chunk-T27TLSEU.js +0 -65
  185. package/dist/cli-bundle/focused-chunks/chunk-VE6MTRH5.js +0 -2
  186. package/dist/cli-bundle/focused-chunks/chunk-YIWDX6KO.js +0 -91
@@ -1,113 +0,0 @@
1
- import{A as h,C as g,E as mt,F as Se,G as ue,H as ge,I as Jc,J as Mi,K as pt,L as Zc,a as xe,b as Pi,c as Bc,e as Pn,f as Mn,g as $n,h as Wc,i as jn,j as Vt,k as Gc,m as we,n as Kc,o as Yc,p as Ln,q as Fn,u as Rr,v as Xc,y as S,z as xr}from"./chunk-GWIGZDRS.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]="451b262c-a9b6-5f1c-b397-2686a5fd953a")}catch{}})();var F_=[["history-redact","history redact"],["history-repair","history repair"],["history-compact","history compact"],["activity","history activity"],["restore","history restore"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"commander",owner:"pm-tqel"})),z_=[...["next","focus"].map(e=>({alias:e,canonical:`context ${e}`,owner:"pm-kcs4"})),...["stats","health","validate","gc","telemetry","eval","test-all"].map(e=>({alias:e,canonical:`ops ${e}`,owner:"pm-6apl"})),...["normalize","reindex"].map(e=>({alias:e,canonical:`ops ${e}`,owner:"pm-3i9q8g"})),{alias:"events",canonical:"history events",owner:"pm-3i9q8g"}].map(e=>({...e,canonical_argv:e.canonical.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap"})),U_=[["update-many","update many"],["close-many","close many"],["delete","close delete"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:"pm-ik19"})),H_=[...z_,...U_,...["init","config","schema","profile"].map(e=>({alias:e,canonical:`workspace ${e}`,canonical_argv:["workspace",e],lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:"pm-npr3"})),...[...["comments","notes","learnings","files","docs","deps","append","test"].map(e=>[e,`item ${e}`,"pm-yql1"]),["test-runs-worker","item test worker","pm-lp4j"],...["statuses","tags","types"].map(e=>[`completion-${e}`,`completion ${e}`,"pm-szdc"]),["history-author-acknowledge","history acknowledge","pm-djyvbk"],["copy","item copy","pm-m6g87m"],["merge","workspace merge","pm-m6g87m"],["duplicates","item duplicates","pm-fmy9ih"],["dedupe-audit","item duplicates audit","pm-fmy9ih"],["dedupe-merge","item duplicates merge","pm-fmy9ih"],["comments-audit","item audit-comments","pm-fmy9ih"],["search-advanced","search advanced","pm-wfskfn"],...["meet","event","remind"].map(e=>[e,`calendar ${e}`,"pm-o3fh"])].map(([e,t,r])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:r}))],$i=[{alias:"history-attest",canonical:"history attest",canonical_argv:["history","attest"],lifecycle:"permanent",hidden:!0,registration:"commander",owner:"pm-3z0k"},...F_,...H_,...["discover","lookup"].map(e=>({alias:`files ${e}`,canonical:`item files ${e}`,canonical_argv:["item","files",e],lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:"pm-yql1"}))];function YI(e){let t;for(let r of $i)r.canonical_argv.length<=(t?.canonical_argv.length??0)||r.canonical_argv.every((n,o)=>n===(o===0&&e[o]==="ctx"?"context":e[o]))&&(t=r);return t}function q_(e){let t=e.trim().replace(/\s+/gu," ");return $i.find(r=>r.canonical===t.replace(/^ctx /u,"context "))?.alias??t}function Nr(e){return q_(e)}var zn=[...$i,...[["ctx","context"],["packages","package"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:[t],lifecycle:"permanent",hidden:!1,registration:"commander",owner:"pm-pbyu"})),...[["start-task","claim","--start"],["pause-task","release","--pause"],["close-task","close","--release-assignment"]].map(([e,t,r])=>({alias:e,canonical:t,canonical_argv:[t,r],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-eq4x"})),{alias:"tests",canonical:"item test",canonical_argv:["item","test"],lifecycle:"permanent",hidden:!1,registration:"bootstrap",owner:"pm-u4t9gp"},...[["fetch","get"],["read","get"],["show","get"],["view","get"],["comment","comments"],["note","notes"],["learning","learnings"]].map(([e,t])=>({alias:e,canonical:["comments","notes","learnings"].includes(t)?`item ${t}`:t,canonical_argv:["comments","notes","learnings"].includes(t)?["item",t]:[t],lifecycle:"permanent",hidden:!1,registration:"bootstrap",owner:"pm-pbyu"})),...[["extension list","extension catalog"],["extension scaffold","extension init"],["package list","package catalog"],["package scaffold","package init"],["packages list","package catalog"],["packages scaffold","package init"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!1,registration:"commander",owner:"pm-ya7x55"})),{alias:"list-all",canonical:"list",canonical_argv:["list","--all"],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"},...[["list-draft","draft"],["list-open","open"],["list-in-progress","in_progress"],["list-blocked","blocked"],["list-closed","closed"],["list-canceled","canceled"]].map(([e,t])=>({alias:e,canonical:"list",canonical_argv:["list","--status",t],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"})),...[["extension","package"],["install","package install"],["upgrade","package upgrade"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-tnud"}))],XI=Object.fromEntries(zn.filter(e=>e.registration==="bootstrap").map(e=>[e.alias,e.canonical]));function JI(e){let t=e.trim().toLowerCase();return zn.find(r=>r.alias===t)}function ZI(e){return`Deprecated command \`${e.alias}\`; use \`pm ${e.canonical_argv.join(" ")}\`.`}(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]="2ea7934f-4751-5245-a5ba-492681aa3794")}catch{}})();var ji=[{kind:"blocked_by",direction:"directed",traversal:"ordering",inverse:"blocks",ordering:!0,precedence:"target_before_source",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["depends_on"],compatibilityVersion:1,allowSelf:!1},{kind:"blocks",direction:"directed",traversal:"ordering",inverse:"blocked_by",ordering:!0,precedence:"source_before_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"parent",direction:"directed",traversal:"hierarchy",outcomeTraversal:"source_to_target",inverse:"child",ordering:!1,hierarchy:!0,hierarchyDirection:"target_parent",outgoing:"one",incoming:"many",lifecycle:"supersedable",aliases:["child_of","epic"],compatibilityVersion:1,allowSelf:!1},{kind:"child",direction:"directed",traversal:"hierarchy",outcomeTraversal:"target_to_source",inverse:"parent",ordering:!1,hierarchy:!0,hierarchyDirection:"source_parent",outgoing:"many",incoming:"one",lifecycle:"supersedable",aliases:["parent_child","task"],compatibilityVersion:1,allowSelf:!1},{kind:"related",direction:"undirected",traversal:"association",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["related_to"],compatibilityVersion:1,allowSelf:!1},{kind:"discovered_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"incident_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"implements",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"recurs_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,temporalOrder:"source_after_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"verifies",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"supersedes",direction:"directed",traversal:"semantic",outcomeTraversal:"both",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"supersedable",compatibilityVersion:1,allowSelf:!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]="418b3f7f-6350-5878-a362-3948de287baf")}catch{}})();function qn(e){return e.trim().toLowerCase().replaceAll("-","_")}function V_(e){if(e===void 0)return;let t=qn(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function Fi(e,t=new Set){if(e===null||typeof e!="object"||t.has(e))return e;if(t.add(e),Array.isArray(e)){for(let r of e)Fi(r,t);return Object.freeze(e)}for(let r of Object.values(e))Fi(r,t);return Object.freeze(e)}function B_(e,t){if(e.precedence!==void 0&&e.precedence!=="source_before_target"&&e.precedence!=="target_before_source")throw new TypeError(`Invalid relationship precedence for ${t}`);if(!e.ordering&&e.precedence!==void 0)throw new TypeError(`Non-ordering relationship kind cannot declare precedence: ${t}`)}function W_(e,t){if(e.temporalOrder!==void 0&&e.temporalOrder!=="source_after_target")throw new TypeError(`Invalid relationship temporal order for ${t}`);if(e.direction!=="directed"&&e.temporalOrder!==void 0)throw new TypeError(`Undirected relationship kind cannot declare temporal order: ${t}`)}function G_(e,t){if(e.hierarchyDirection!==void 0&&e.hierarchyDirection!=="source_parent"&&e.hierarchyDirection!=="target_parent")throw new TypeError(`Invalid relationship hierarchy direction for ${t}`);if(!e.hierarchy&&e.hierarchyDirection!==void 0)throw new TypeError(`Non-hierarchy relationship kind cannot declare hierarchy direction: ${t}`)}function K_(e){if(typeof e!="object"||e===null)throw new TypeError("Relationship kind definition requires an object");if(typeof e.kind!="string")throw new TypeError("Relationship kind requires a string identifier");let t=qn(e.kind);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid relationship kind: ${e.kind}`);if(!Number.isInteger(e.compatibilityVersion)||e.compatibilityVersion<1)throw new TypeError(`Invalid compatibility version for ${t}`);return t}function Y_(e,t){if(!["directed","undirected"].includes(e.direction))throw new TypeError(`Invalid relationship direction for ${t}`);if(typeof e.ordering!="boolean")throw new TypeError(`Invalid relationship ordering flag for ${t}`);if(![void 0,!0,!1].includes(e.hierarchy))throw new TypeError(`Invalid relationship hierarchy flag for ${t}`);if(!["one","many"].includes(e.outgoing))throw new TypeError(`Invalid outgoing relationship cardinality for ${t}`);if(!["one","many"].includes(e.incoming))throw new TypeError(`Invalid incoming relationship cardinality for ${t}`);if(!["persistent","supersedable","ephemeral"].includes(e.lifecycle))throw new TypeError(`Invalid relationship lifecycle for ${t}`);if(typeof e.allowSelf!="boolean")throw new TypeError(`Invalid relationship self-edge flag for ${t}`);if(e.traversal!==void 0&&!["hierarchy","ordering","semantic","association"].includes(e.traversal))throw new TypeError(`Invalid relationship traversal family for ${t}`);if(e.outcomeTraversal!==void 0&&!["source_to_target","target_to_source","both"].includes(e.outcomeTraversal))throw new TypeError(`Invalid outcome traversal for ${t}`);if(e.direction==="undirected"&&e.outcomeTraversal!==void 0&&e.outcomeTraversal!=="both")throw new TypeError(`Undirected relationship kind cannot declare directional outcome traversal: ${t}`)}function X_(e,t){if(e.payloadSchema!==void 0&&(typeof e.payloadSchema!="object"||e.payloadSchema===null||Array.isArray(e.payloadSchema)))throw new TypeError(`Invalid relationship payload schema for ${t}`);if(e.aliases!==void 0&&(!Array.isArray(e.aliases)||e.aliases.some(r=>typeof r!="string")))throw new TypeError(`Invalid relationship aliases for ${t}`)}function J_(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var zi=class{#e=new Map;#r=new Map;constructor(t=ji){for(let r of t)this.register(r)}register(t){let r=K_(t);if(Y_(t,r),X_(t,r),B_(t,r),W_(t,r),G_(t,r),this.#e.has(r)||this.#r.has(r))throw new TypeError(`Relationship kind already registered: ${r}`);let n=V_(t.inverse),o=[...new Set((t.aliases??[]).map(qn))].sort();for(let s of o){if(!/^[a-z][a-z0-9_]*$/.test(s))throw new TypeError(`Invalid relationship alias: ${s}`);if(s===r||this.#e.has(s)||this.#r.has(s))throw new TypeError(`Relationship alias already registered: ${s}`)}let i=Object.freeze({...t,kind:r,traversal:J_(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:n,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?Fi(structuredClone(t.payloadSchema)):void 0});this.#e.set(r,i);for(let s of o)this.#r.set(s,r);return this}resolve(t){if(typeof t!="string")return;let r=qn(t);return this.#e.get(this.#r.get(r)??r)}require(t){let r=this.resolve(t);if(!r)throw new TypeError(`Unknown relationship kind: ${t}`);return r}list(){return Object.freeze([...this.#e.values()].sort((t,r)=>t.kind.localeCompare(r.kind)))}};function Ui(){return new zi}var _t=Ui();function nT(e){return _t.require(e).kind}function oT(e){return _t.resolve(e)?.kind}function iT(e,t=_t){return t.resolve(e)?.ordering===!0}function Z_(e,t,r,n=_t){let o=Dr(e),i=Dr(t);if(!o||!i)throw new TypeError("Relationship endpoint must not be empty");let s=n.require(r);if(o===i&&!s.allowSelf)throw new TypeError(`Self relationship is not allowed for ${s.kind}`);return s}function Un(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.kind.localeCompare(t.kind)}function Q_(e,t,r){let n=typeof e.source=="string"?e.source.trim():"",o=typeof e.target=="string"?e.target.trim():"";if(!t.has(n)||!t.has(o))throw new TypeError(`Relationship endpoint not found: ${n} -> ${o}`);let i=Z_(n,o,e.kind,r),s=Object.freeze({...e,source:n,target:o,kind:i.kind}),a=i.direction==="undirected"?[n,o].sort().join("\0"):`${n}\0${o}`;return{edge:s,identity:`${i.kind}\0${a}`}}function Hn(e,t,r){let n=e.get(t);n?n.push(r):e.set(t,[r])}function Dr(e){return typeof e=="string"?e.trim():""}function Li(e,t){let r=Dr(e);return r&&t.has(r)?r:void 0}function ey(e,t,r){let n=[t],o=t;for(;o!==e;)o=r.get(o),n.push(o);return n.reverse()}var Qc=class e{#e;#r;#o;#n;#s=new Map;#a=new Map;constructor(t,r,n=_t){this.#e=n,this.#r=new Set([...t].filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean)),this.#o=Object.freeze([...this.#r].sort());let o=new Map;for(let i of r){let{edge:s,identity:a}=Q_(i,this.#r,n);o.set(a,s)}this.#n=Object.freeze([...o.values()].sort(Un));for(let i of this.#n)Hn(this.#s,i.source,i),Hn(this.#a,i.target,i),n.require(i.kind).direction==="undirected"&&(Hn(this.#s,i.target,i),Hn(this.#a,i.source,i))}static fromItems(t,r=_t){let n=new Set(t.map(i=>Dr(i.id)).filter(Boolean)),o=[];for(let i of t){let s=Dr(i.id);if(!s)continue;let a=Li(i.parent,n);a&&o.push({source:s,target:a,kind:"parent"});let c=Li(i.blocked_by,n);c&&o.push({source:s,target:c,kind:"blocked_by"});for(let d of i.dependencies??[]){let l=Li(d.id,n);l&&r.resolve(d.kind)&&o.push({source:s,target:l,kind:d.kind,createdAt:d.created_at,author:d.author})}}return new e(n,o,r)}edges(){return this.#n}incidentEdges(t){this.#i(t);let r=this.#s.get(t)??[],n=this.#a.get(t)??[];if(r.length===0)return Object.freeze([...n]);if(n.length===0)return Object.freeze([...r]);let o=[],i=0,s=0;for(;i<r.length||s<n.length;){let a=r[i],c=n[s],d=a===void 0?c:c===void 0||Un(a,c)<=0?a:c;o.at(-1)!==d&&o.push(d),a===d&&(i+=1),c===d&&(s+=1)}return Object.freeze(o)}nodes(){return this.#o}hasNode(t){return this.#r.has(t)}registry(){return this.#e}#i(t){if(!this.#r.has(t))throw new TypeError(`Relationship node not found: ${t}`)}#c(t,r){if(!r)return!0;let n=this.#e.require(t.kind);return r.has(t.kind)||n.inverse!==void 0&&r.has(n.inverse)}#t(t,r,n){let o=[...r==="incoming"?[]:this.#s.get(t)??[],...r==="outgoing"?[]:this.#a.get(t)??[]];return[...new Set(o)].filter(i=>this.#c(i,n)).map(i=>({id:i.source===t?i.target:i.source,edge:i})).sort((i,s)=>i.id.localeCompare(s.id)||Un(i.edge,s.edge))}adjacency(t,r={}){this.#i(t),r.signal?.throwIfAborted();let n=r.kinds?new Set(r.kinds.map(c=>this.#e.require(c).kind)):void 0,o=this.#t(t,r.direction??"outgoing",n),i=r.limit??Number.POSITIVE_INFINITY,s=[...new Set(o.map(c=>c.id))],a=s.slice(0,i);return{value:a,meta:{visitedNodes:1,inspectedEdges:o.length,truncated:a.length<s.length,nextCursor:a.at(-1)}}}neighborEdges(t,r={}){this.#i(t),r.signal?.throwIfAborted();let n=r.kinds?new Set(r.kinds.map(a=>this.#e.require(a).kind)):void 0,o=this.#t(t,r.direction??"outgoing",n),i=r.limit??Number.POSITIVE_INFINITY,s=o.slice(0,i);return{value:s,meta:{visitedNodes:1,inspectedEdges:o.length,truncated:s.length<o.length,nextCursor:s.at(-1)?.id}}}closure(t,r={}){this.#i(t);let n=r.kinds?new Set(r.kinds.map(m=>this.#e.require(m).kind)):void 0,o=r.direction??"outgoing",i=r.limit??Number.POSITIVE_INFINITY,s=r.maxDepth??Number.POSITIVE_INFINITY,a=new Set([t]),c=[],d=[{id:t,depth:0}],l=0,u=0,f=!1;e:for(let m=0;m<d.length;m+=1){r.signal?.throwIfAborted();let _=d[m];l+=1;let y=this.#t(_.id,o,n);if(u+=y.length,_.depth>=s){y.some(w=>!a.has(w.id))&&(f=!0);continue}for(let w of y)if(!a.has(w.id)){if(c.length>=i){f=!0;break e}a.add(w.id),c.push(w.id),d.push({id:w.id,depth:_.depth+1})}}return{value:c,meta:{visitedNodes:l,inspectedEdges:u,truncated:f,nextCursor:c.at(-1)}}}shortestPath(t,r,n={}){if(this.#i(t),this.#i(r),t===r)return{value:[t],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}};let o=n.kinds?new Set(n.kinds.map(m=>this.#e.require(m).kind)):void 0,i=n.direction??"outgoing",s=n.maxDepth??Number.POSITIVE_INFINITY,a=[{id:t,depth:0}],c=new Map,d=new Set([t]),l=0,u=0,f=!1;for(let m=0;m<a.length;m+=1){n.signal?.throwIfAborted();let _=a[m];l+=1;let y=this.#t(_.id,i,o);if(u+=y.length,_.depth>=s){y.some(w=>!d.has(w.id))&&(f=!0);continue}for(let w of y)if(!d.has(w.id)){if(c.set(w.id,_.id),w.id===r)return{value:ey(t,r,c),meta:{visitedNodes:l,inspectedEdges:u,truncated:!1}};d.add(w.id),a.push({id:w.id,depth:_.depth+1})}}return{value:[],meta:{visitedNodes:l,inspectedEdges:u,truncated:f}}}subgraph(t,r={}){let n=this.closure(t,r),o=[t,...n.value].sort(),i=new Set(o),s=r.kinds?new Set(r.kinds.map(c=>this.#e.require(c).kind)):void 0,a=new Set;for(let c of o)for(let d of this.#s.get(c)??[])i.has(d.source)&&i.has(d.target)&&this.#c(d,s)&&a.add(d);return{value:{nodes:o,edges:[...a].sort(Un)},meta:n.meta}}};function sT(e,t,r=_t){return{source:e,target:t.id,kind:r.require(t.kind).kind,createdAt:t.created_at,author:t.author}}(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]="32aa20df-edf7-543d-b733-841130466f00")}catch{}})();var ty="__pm_suppress_host_output",Hi="@unbrained/pm-cli:suppress-host-output:v1";function ed(e){return e===void 0?{__pm_suppress_host_output:Hi}:{__pm_suppress_host_output:Hi,result:e}}function Vn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[ty]===Hi}import Bt from"node:fs";import Ne from"node:path";import{fileURLToPath as ry}from"node:url";(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]="efea1aa1-1ad1-5f53-a3a5-b83803d9deb1")}catch{}})();var ny="@unbrained/pm-cli";function oy(e){try{return JSON.parse(Bt.readFileSync(e,"utf8")).name===ny}catch{return!1}}function iy(e){let t=Bt.existsSync(e)&&Bt.statSync(e).isDirectory()?Ne.resolve(e):Ne.dirname(Ne.resolve(e));for(;;){let r=Ne.join(t,"package.json");if(Bt.existsSync(r)&&oy(r))return t;let n=Ne.dirname(t);if(n===t)return;t=n}}function Bn(e,t=[]){let r=ry(e);return iy(r)||Ne.resolve(Ne.dirname(r),...t)}function fT(e,t=[]){try{let r=Ne.join(Bn(e,t),"package.json");if(!Bt.existsSync(r))return;let n=JSON.parse(Bt.readFileSync(r,"utf8"));return typeof n.version=="string"&&n.version.trim().length>0?n.version:void 0}catch{return}}function mT(e=process.env,t="PM_CLI_PACKAGE_ROOT",r,n=[]){let o=e[t];return typeof o=="string"&&o.trim().length>0?Ne.resolve(o.trim()):r?Bn(r,n):process.cwd()}(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]="a797572f-fbc6-5e62-a9b5-5a0bd6ef22b4")}catch{}})();function sy(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function _T(e){return sy(e)??void 0}function yT(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)}function hT(e){return Array.isArray(e)&&e.every(t=>typeof t=="number"&&Number.isFinite(t))}function rd(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function Wn(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;return Number.isFinite(t)?t:null}function gT(e){let t=Wn(e);return t===null||t<=0||!Number.isInteger(t)?null:t}function bT(e,t,r){let n=Wn(e);return n===null||n<t||n>r?null:n}function wT(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}function ze(e){return typeof e!="object"||e===null?null:e}function td(e){return typeof e!="object"&&typeof e!="function"||e===null?null:e}function nd(e){let t=td(e);if(!t)return null;if(typeof t.activate=="function")return t;let r=td(t.default);return typeof r?.activate=="function"?r:null}function vT(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...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]="c05a5a9e-282c-5ca7-97dc-e48c8df7977e")}catch{}})();var ay=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],od=ay,Wt=["draft","open","in_progress","blocked","closed","canceled"],Gn=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],Gt=["string","number","boolean","string_array","array","object"],Kn=["create","update","update_many","list","search","calendar","context"],Yn=["allow","warn","reject"],kT=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"],ST=["project","global"],OT=["low","medium","high","critical"],Xn=["low","medium","high","critical"],Jn=["low","medium","high"];var id=["minimal","default","strict","custom"],AT=["none","warn","strict"],IT=["progressive","strict"],TT=["off","warn","strict"],CT=["off","warn","strict"];var Zn=["daily","weekly","monthly","yearly"],Pr=["mon","tue","wed","thu","fri","sat","sun"];function qi(e){return Pr.indexOf(e)}var RT=["draft","research","review","approved","executing","paused","completed","superseded"],sd=["pending","in_progress","completed","blocked","skipped","superseded"],xT=["codex","claude-code","cursor","generic"],NT=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"],DT=["brief","standard","deep","full"],PT=["hierarchy","activity","progress","recently_created","unparented","blockers","files","workload","staleness","tests"];(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]="0ca7f52c-fb31-5cd9-b689-a918f4e61816")}catch{}})();import fy 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]="75f74db3-9547-5c78-8561-f371c016b90d")}catch{}})();function Ue(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function cy(e){let t=e.key.trim();if(t.length===0)return null;let r=Ue(e.aliases),n=e.description?.trim();return{key:t,values:Ue(e.values),required:e.required===!0?!0:void 0,aliases:r.length>0?r:void 0,description:n&&n.length>0?n:void 0}}var dy=e=>e,cd=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function ly(e,t){let r=t(e.command);if(r===null)return null;let n=e.option.trim();return n.length===0?null:{command:r,option:n,required:e.required,visible:e.visible,enabled:e.enabled}}function uy(e,t){let r=new Map;for(let n of e??[]){let o=ly(n,t);o&&r.set(`${o.command}:${o.option.toLowerCase()}`,o)}return[...r.values()].sort((n,o)=>n.command===o.command?n.option.localeCompare(o.option):n.command.localeCompare(o.command))}function ad(e,t){return t?Ue(e):void 0}function Vi(e){let t=e?.trim();return t&&t.length>0?t:void 0}function Bi(e){if(e===void 0||e==="agent"||e==="human"||e==="gate")return e;throw new Error("Item type execution_role must be agent, human, or gate.")}function Qn(e,t={}){let r=t.resolvePolicyCommand??dy,n=e.name.trim();if(n.length===0)return null;let o=e.required_create_fields!==void 0,i=e.required_create_repeatables!==void 0,s=e.options!==void 0,a=e.command_option_policies!==void 0,c=Ue(e.aliases),d=(e.options??[]).map(u=>cy(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),l=uy(e.command_option_policies,r);return{name:n,description:Vi(e.description),default_status:Vi(e.default_status),...e.execution_role===void 0?{}:{execution_role:Bi(e.execution_role)},folder:Vi(e.folder),aliases:c.length>0?c:void 0,required_create_fields:ad(e.required_create_fields,o),required_create_repeatables:ad(e.required_create_repeatables,i),options:s?d:void 0,command_option_policies:a?l: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]="f40ddc8e-1dd5-5f26-b2ba-fbbac30a1781")}catch{}})();var my=Object.freeze({decision:"human",milestone:"gate"}),py=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],_y=["dep","comment","note","learning","file","test","doc"],ld=["deadline","estimatedMinutes","acceptanceCriteria","definitionOfReady","order","goal","objective","value","impact","outcome","whyNow","assignee","parent","reviewer","risk","confidence","sprint","release","blockedBy","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact"],yy=["title","description","type","status","priority","tags","body",...ld,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],hy=["title","description","body","status","closeReason","priority","type","tags",...ld,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],ud={"close-reason":"closeReason",close_reason:"closeReason","estimated-minutes":"estimatedMinutes",estimated_minutes:"estimatedMinutes",estimate:"estimatedMinutes","acceptance-criteria":"acceptanceCriteria",acceptance_criteria:"acceptanceCriteria",ac:"acceptanceCriteria","definition-of-ready":"definitionOfReady",definition_of_ready:"definitionOfReady",rank:"order","why-now":"whyNow",why_now:"whyNow","blocked-by":"blockedBy",blocked_by:"blockedBy","blocked-reason":"blockedReason",blocked_reason:"blockedReason","unblock-note":"unblockNote",unblock_note:"unblockNote","repro-steps":"reproSteps",repro_steps:"reproSteps","expected-result":"expectedResult",expected_result:"expectedResult","actual-result":"actualResult",actual_result:"actualResult","affected-version":"affectedVersion",affected_version:"affectedVersion","fixed-version":"fixedVersion",fixed_version:"fixedVersion","customer-impact":"customerImpact",customer_impact:"customerImpact","type-option":"typeOption",type_option:"typeOption",type_options:"typeOption"},gy={...ud},by={...ud},fd=[["deadline","--deadline"],["estimatedMinutes","--estimate/--estimated-minutes"],["acceptanceCriteria","--acceptance-criteria/--ac"],["definitionOfReady","--definition-of-ready"],["order","--order/--rank"],["goal","--goal"],["objective","--objective"],["value","--value"],["impact","--impact"],["outcome","--outcome"],["whyNow","--why-now"],["assignee","--assignee"],["parent","--parent"],["reviewer","--reviewer"],["risk","--risk"],["confidence","--confidence"],["sprint","--sprint"],["release","--release"],["blockedBy","--blocked-by"],["blockedReason","--blocked-reason"],["unblockNote","--unblock-note"],["reporter","--reporter"],["severity","--severity"],["environment","--environment"],["reproSteps","--repro-steps"],["resolution","--resolution"],["expectedResult","--expected-result"],["actualResult","--actual-result"],["affectedVersion","--affected-version"],["fixedVersion","--fixed-version"],["component","--component"],["regression","--regression"],["customerImpact","--customer-impact"]],md=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function pd(e){return Object.fromEntries(e)}var wy=pd([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...fd,["author","--author"],["message","--message"],["dep","--dep"],...md]),vy=pd([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...fd,...md,["author","--author"],["message","--message"],["force","--force"]]);function Ey(e){return e.trim().replace(/^--+/,"").toLowerCase()}function ky(e){return e==="create"?yy:hy}function Sy(e){return e==="create"?gy:by}function _d(e,t){let r=Ey(t);return r.length===0?void 0:Sy(e)[r]||ky(e).find(n=>n.toLowerCase()===r)}function qT(e,t){return(e==="create"?wy:vy)[t]??`--${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function Gi(e){let t=Ay(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function Oy(e){let t=e.trim(),r=t.replaceAll("\\","/").replace(/^\/+/,""),n=fy.posix.normalize(r);if(t.includes("\0")||/^[A-Za-z]:/.test(n)||n==="."||n===".."||n.startsWith("../"))throw new Error(`Item type folder "${e}" must stay inside the pm tracker root.`);return n}function Ay(e){let t=e.trim().toLowerCase(),r="",n=!1;for(let o of t){let i=o.charCodeAt(0),s=i>=97&&i<=122,a=i>=48&&i<=57;if(s||a){n&&r.length>0&&(r+="-"),r+=o,n=!1;continue}r.length>0&&(n=!0)}return r}function Iy(e){return Qn(e,{resolvePolicyCommand:cd})}function Mr(e,t){let r=e[t];return Array.isArray(r)?r.filter(n=>typeof n=="string"):void 0}function Ty(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;return typeof t.key!="string"?null:{key:t.key,values:Mr(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:Mr(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function Cy(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;if(typeof t.command!="string"||typeof t.option!="string")return null;let r=t.command.trim().toLowerCase();return r!=="create"&&r!=="update"?null:{command:r,option:t.option,required:t.required===void 0?void 0:!!t.required,visible:t.visible===void 0?void 0:!!t.visible,enabled:t.enabled===void 0?void 0:!!t.enabled}}function Ry(e){if(Array.isArray(e.options))return e.options.map(t=>Ty(t)).filter(t=>t!==null)}function xy(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>Cy(t)).filter(t=>t!==null)}function Ny(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e,r=typeof t.name=="string"?t.name:"";if(r.trim().length===0)return null;let n=typeof t.folder=="string"?t.folder:void 0,o=typeof t.description=="string"?t.description:void 0,i=typeof t.default_status=="string"?t.default_status:void 0;return{name:r,description:o,default_status:i,execution_role:Bi(t.execution_role),folder:n,aliases:Mr(t,"aliases"),required_create_fields:Mr(t,"required_create_fields"),required_create_repeatables:Mr(t,"required_create_repeatables"),options:Ry(t),command_option_policies:xy(t)}}function Dy(e,t){return e.required_create_fields?Ue(e.required_create_fields):t?.required_create_fields??[]}function Py(e,t){return e.required_create_repeatables?Ue(e.required_create_repeatables):t?.required_create_repeatables??[]}function My(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function $y(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function jy(e,t){let r=t?.name??e.name,n=e.description??t?.description,o=e.default_status??t?.default_status,i=Oy(e.folder??t?.folder??Gi(r)),s={name:r,execution_role:e.execution_role,folder:i,aliases:Ue([...t?.aliases??[],...e.aliases??[]]),required_create_fields:Dy(e,t),required_create_repeatables:Py(e,t),options:My(e,t),command_option_policies:$y(e,t)};return n&&(s.description=n),o&&(s.default_status=o),s}function dd(e,t){for(let r of e){let n=Iy(r);if(!n)continue;let o=n.name.toLowerCase(),i=t.get(o);t.set(o,jy({...n,execution_role:n.execution_role??i?.execution_role},i))}}function Ly(e){if(!e)return[];let t=[];for(let r of e.item_types??[]){let n=r.types;if(Array.isArray(n))for(let o of n){let i=Ny(o);i&&t.push(i)}}return t}function VT(e,t=null){let r=new Map;for(let c of od)r.set(c.toLowerCase(),{name:c,execution_role:my[c.toLowerCase()]??"agent",folder:Rr[c],aliases:[],required_create_fields:[...py],required_create_repeatables:[..._y],options:[],command_option_policies:[]});dd(e.item_types?.definitions??[],r),dd(Ly(t),r);let n=[...r.values()].sort((c,d)=>c.name.localeCompare(d.name)),o={},i={},s={};for(let c of n){o[c.name]=c,s[c.name]=c.folder,i[c.name.toLowerCase()]=c.name;for(let d of c.aliases)i[d.toLowerCase()]=c.name}let a=[...new Set(n.map(c=>c.folder))].sort((c,d)=>c.localeCompare(d));return{types:n.map(c=>c.name),folders:a,type_to_folder:s,by_type:o,alias_to_type:i}}function Fy(e,t){if(e!==void 0)return t.alias_to_type[e.trim().toLowerCase()]}function zy(e,t){let r=Fy(e,t);if(r)return t.by_type[r]}function Uy(e,t,r,n){for(let o of n){let i=_d(r,o);if(i){e.required.add(i);continue}e.errors.push(`Unsupported base required option "${o}" for command "${r}" on type "${t.name}"`)}}function Wi(e,t,r){if(r){e.add(t);return}e.delete(t)}function Hy(e,t,r,n){let o=_d(r,n.option);if(!o){e.errors.push(`Unsupported command_option_policies option "${n.option}" for command "${r}" on type "${t.name}"`);return}n.required!==void 0&&Wi(e.required,o,n.required),n.visible!==void 0&&Wi(e.hidden,o,!n.visible),n.enabled!==void 0&&Wi(e.disabled,o,!n.enabled)}function qy(e,t,r){for(let n of t.command_option_policies)n.command===r&&Hy(e,t,r,n)}function Vy(e,t,r){for(let n of e.required)e.disabled.has(n)&&e.errors.push(`Option "${n}" cannot be both required and disabled for command "${r}" on type "${t.name}"`)}function BT(e,t,r){let n=[],o=new Set,i=new Set,s=new Set,a={required:o,hidden:i,disabled:s,errors:n};return Uy(a,e,t,r),qy(a,e,t),Vy(a,e,t),{required:[...o],hidden:[...i].sort((c,d)=>c.localeCompare(d)),disabled:[...s].sort((c,d)=>c.localeCompare(d)),errors:n}}function By(e){let t=new Map;for(let r of e.options){t.set(r.key.toLowerCase(),r);for(let n of r.aliases??[])t.set(n.toLowerCase(),r)}return t}function Wy(e,t,r){let n=e.values;if(n.length===0)return t;let o=new Map(n.map(i=>[i.toLowerCase(),i])).get(t.toLowerCase());if(!o){r.push(`Invalid value "${t}" for type option "${e.key}". Allowed: ${n.join(", ")}`);return}return o}function WT(e,t,r){let n=zy(e,r);if(!n)return{normalized:void 0,errors:[`Unknown type "${e}"`]};let o=[],i=By(n),s={};for(let[c,d]of Object.entries(t??{})){let l=c.trim(),u=d.trim();if(l.length===0){o.push("type option keys must not be empty");continue}if(u.length===0){o.push(`type option "${l}" must not be empty`);continue}let f=i.get(l.toLowerCase());if(!f){let _=n.options.map(y=>y.key).join(", ");o.push(n.options.length>0?`Unknown type option "${l}" for type "${n.name}". Allowed: ${_}`:`Type "${n.name}" does not define any configurable type options`);continue}let m=Wy(f,u,o);m!==void 0&&(s[f.key]=m)}for(let c of n.options)c.required&&!(c.key in s)&&o.push(`Missing required type option "${c.key}" for type "${n.name}"`);let a=Object.keys(s).sort((c,d)=>c.localeCompare(d));return a.length===0?{normalized:void 0,errors:o}:{normalized:Object.fromEntries(a.map(c=>[c,s[c]])),errors:o}}import{readFileSync as Gy,readdirSync as Ky,realpathSync as yd,statSync as hd}from"node:fs";import Yy from"node:os";import T 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]="7f4b8abe-997c-549c-9791-87c78506c8b5")}catch{}})();var Xy={json_markdown:".md",toon:".toon"},Jy={".md":"json_markdown",".toon":"toon"},Zy=new Set([".git","coverage","dist","node_modules"]),tC=[".md",".toon"];function $r(e){try{return hd(e),!0}catch{return!1}}function Qy(e){let t=T.resolve(e),r=[];for(;T.dirname(t)!==t;)try{return T.join(yd(t),...r)}catch(n){if(!Se(n))throw n;r.unshift(T.basename(t)),t=T.dirname(t)}return T.join(yd(t),...r)}function eh(e){try{return hd(e),!0}catch(t){if(Se(t))return!1;throw t}}function gd(e){try{let t=JSON.parse(Gy(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function th(e){let t=Qy(e);for(;;){let r=T.join(t,Ln),n=T.join(r,Fn);if($r(n))return r;let o=T.join(t,Fn);if($r(o)&&gd(o))return t;if(eh(T.join(t,".git")))return r;let i=T.dirname(t);if(i===t)return;t=i}}function rh(e){return th(e)??T.resolve(e,Ln)}function rC(e,t){let r=t?T.resolve(t):void 0;try{return Ky(T.resolve(e),{withFileTypes:!0}).filter(n=>n.isDirectory()&&!Zy.has(n.name)).map(n=>T.join(T.resolve(e),n.name)).filter(n=>n!==r).filter(n=>$r(Oe(n))).filter(n=>gd(Oe(n))).sort((n,o)=>n.localeCompare(o))[0]}catch{return}}function nC(e,t){let r=process.env.PM_PATH,n=t?.trim()||r?.trim();if(n){let o=T.resolve(e,n);if(!$r(Oe(o))){let i=T.join(o,Ln);if($r(Oe(i)))return i}return o}return rh(e)}function oC(e){let t=T.resolve(e),r=T.dirname(t);return T.basename(t)==="pm"&&T.basename(r)===".agents"?T.dirname(r):t}function bd(e){let t=process.env.PM_GLOBAL_PATH?.trim(),r=t&&t.length>0?t:T.join(Yy.homedir(),".pm-cli");return T.resolve(e,r)}function Oe(e){return T.join(e,Fn)}function nh(e,t,r=Rr){let n=r[t]??Gi(t);return T.join(e,n)}function iC(e,t,r,n="toon",o=Rr){return T.join(nh(e,t,o),`${r}${Xy[n]}`)}function sC(e){let t=e.replaceAll("\\","/"),r=T.posix.extname(t).toLowerCase();return Jy[r]??null}function aC(e,t){if(!/^(?!\.{1,2}$)[^/\\:\0]+$/.test(t))throw new g("Invalid history item id: expected a single filename.",h.USAGE);return T.join(e,"history",`${t}.jsonl`)}function Ki(e,t){return T.join(e,"locks",`${t}.lock`)}function Yi(e){return T.join(e,"runtime")}function eo(e){return T.join(Yi(e),"test-runs")}function oh(e){return T.join(eo(e),"runs")}function cC(e,t){return T.join(oh(e),`${t}.json`)}function ih(e){return T.join(eo(e),"stdout")}function sh(e){return T.join(eo(e),"stderr")}function dC(e,t){return T.join(ih(e),`${t}.log`)}function lC(e,t){return T.join(sh(e),`${t}.log`)}function ah(e){return T.join(eo(e),"results")}function uC(e,t){return T.join(ah(e),`${t}.json`)}import ch 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]="77f9d61e-e78b-5b6a-a769-1ad6e5b91777")}catch{}})();function dh(e){if(e===null)return null;if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint")return e.toString();if(e===void 0)return"undefined";if(typeof e=="symbol")return e.toString();if(typeof e=="function")return`[function:${e.name||"anonymous"}]`}function lh(e){let t=Object.keys(e).sort(),r={};for(let n of t){let o=e[n];o!==void 0&&(r[n]=to(o))}return r}function to(e){let t=dh(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(n=>to(n));if(e instanceof Date)return e.toISOString();let r=e;if(typeof r.toJSON=="function"){let n=r.toJSON();if(n!==e)return to(n)}return lh(e)}function R(e){return JSON.stringify(to(e))}function wd(e,t,r,n){for(let o=0;o<t.length;o+=1)if(!r.has(o)&&n(e,t[o]))return r.add(o),!0;return!1}function uh(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function fh(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function mh(e,t){if(!(e instanceof Set||t instanceof Set))return;if(!(e instanceof Set&&t instanceof Set)||e.size!==t.size)return!1;let r=[...t],n=new Set;for(let o of e)if(!wd(o,r,n,B))return!1;return!0}function ph(e,t){if(!(e instanceof Map||t instanceof Map))return;if(!(e instanceof Map&&t instanceof Map)||e.size!==t.size)return!1;let r=[...t.entries()],n=new Set;for(let[o,i]of e.entries())if(!wd([o,i],r,n,([s,a],[c,d])=>B(s,c)&&B(a,d)))return!1;return!0}function _h(e,t){if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((r,n)=>B(r,t[n]))}function yh(e,t){let r=Object.keys(e).sort((o,i)=>o.localeCompare(i)),n=Object.keys(t).sort((o,i)=>o.localeCompare(i));if(r.length!==n.length)return!1;for(let o=0;o<r.length;o+=1){let i=r[o];if(i!==n[o]||!B(e[i],t[i]))return!1}return!0}var hh=[uh,fh,mh,ph,_h];function B(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;for(let r of hh){let n=r(e,t);if(n!==void 0)return n}return yh(e,t)}function ro(e){return ch.createHash("sha256").update(e,"utf8").digest("hex")}function A(e,t){let r={};for(let o of t){let i=e[o];i!==void 0&&(r[o]=i)}let n=Object.keys(e).filter(o=>!t.includes(o)).sort((o,i)=>o.localeCompare(i));for(let o of n){let i=e[o];i!==void 0&&(r[o]=i)}return r}import{createHash as Ed}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]="f675993f-c483-5751-baed-d968b4fd24c0")}catch{}})();var gh=["policies","policy-put","policy-remove","policy-mode","policy-check","policy-approve","policy-presets"],vd=256,Xi=64;function se(e){throw new g(`Invalid workflow policy: ${e}`,h.USAGE,{code:"workflow_policy_invalid",nextSteps:["Inspect pm schema policies and correct the declaration using pm schema policy-put."]})}function De(e,t,r){if(typeof e!="object"||e===null||Array.isArray(e))return se(`${r} must be an object`);let n=e;return Object.keys(n).some(o=>!t.includes(o))?se(`${r} contains an unknown key`):n}function yt(e,t,r=128){return typeof e!="string"||!e.trim()||e.length>r?se(`${t} must be nonempty text of at most ${r} characters`):e.trim()}function jr(e,t){if(!Array.isArray(e)||e.length===0||e.length>Xi)return se(`${t} requires 1-${Xi} terms`);let r=e.map(n=>yt(n,t));return t==="fields"&&r.some(n=>!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$/.test(n)||n.split(".").some(o=>["__proto__","constructor","prototype"].includes(o)))?se("fields must be safe metadata paths of at most eight segments"):[...new Set(r)]}function bh(e){let t=De(e,["kind","fields","authors","allowed"],"rule");return t.kind==="transition"?(De(t,["kind","allowed"],"transition rule"),!Array.isArray(t.allowed)||t.allowed.length>Xi?se("transition.allowed must be a bounded array"):{kind:"transition",allowed:t.allowed.map(r=>!Array.isArray(r)||r.length!==2?se("transition pairs need two statuses"):[yt(r[0],"from"),yt(r[1],"to")])}):t.kind==="authors"?(De(t,["kind","authors"],"authors rule"),{kind:"authors",authors:jr(t.authors,"authors")}):t.kind==="require_fields"?(De(t,["kind","fields"],"require_fields rule"),{kind:"require_fields",fields:jr(t.fields,"fields")}):t.kind==="field_writers"||t.kind==="approval"?(De(t,["kind","fields","authors"],"field rule"),{kind:t.kind,fields:jr(t.fields,"fields"),authors:jr(t.authors,"authors")}):se("unknown rule kind")}function wh(e){let t={},r=De(e,["types","tags","statuses","operations","parents","dependency"],"subject");for(let n of["types","tags","statuses","operations","parents"])r[n]!==void 0&&(t[n]=jr(r[n],n));if(r.dependency!==void 0){let n=De(r.dependency,["kind","id"],"dependency");t.dependency={kind:yt(n.kind,"dependency kind"),...n.id===void 0?{}:{id:yt(n.id,"dependency id")}}}return t}function vh(e){let t=De(e,["id","description","subject","effect","rule"],"policy"),r=yt(t.id,"id");return/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(r)?t.effect!==void 0&&(typeof t.effect!="string"||!["advise","warn","refuse"].includes(t.effect))?se("effect must be advise, warn, or refuse"):{id:r,rule:bh(t.rule),...t.subject===void 0?{}:{subject:wh(t.subject)},...t.description===void 0?{}:{description:yt(t.description,"description",500)},...t.effect===void 0?{}:{effect:t.effect}}:se("id must be a stable token")}function Eh(e){let t=De(e,["version","enforcement","policies"],"document");if(t.version!==1)return se("unsupported version");if(t.enforcement!==void 0&&t.enforcement!=="advise"&&t.enforcement!=="refuse")return se("enforcement must be advise or refuse");if(!Array.isArray(t.policies)||t.policies.length>vd)return se(`policies must contain at most ${vd} declarations`);let r=t.policies.map(vh);return new Set(r.map(n=>n.id)).size!==r.length?se("duplicate policy id"):{version:1,enforcement:t.enforcement??"advise",policies:r}}function no(e,t){let r=e;for(let n of t.split(".")){if(typeof r!="object"||r===null||!Object.hasOwn(r,n))return;r=r[n]}return r}function kh(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function kd(e){return Ed("sha256").update(R(e)).digest("hex")}function Sh(e,t){let r=e.rule.kind==="approval"?e.rule.fields:[];return Ed("sha256").update(R({id:t.id,fields:r.map(n=>[n,no(t,n)])})).digest("hex")}function Oh(e,t){return Array.isArray(t)&&t.some(r=>typeof r=="object"&&r!==null&&"kind"in r&&r.kind===e.kind&&(e.id===void 0||"id"in r&&r.id===e.id))}function Ah(e,t,r){return!(e.types&&!e.types.some(n=>n.toLowerCase()===String(t.type).toLowerCase())||e.statuses&&!e.statuses.includes(String(t.status))||e.operations&&!e.operations.includes(r)||e.parents&&!e.parents.includes(String(t.parent))||e.tags&&(!Array.isArray(t.tags)||!e.tags.some(n=>t.tags.includes(n)))||e.dependency&&!Oh(e.dependency,t.dependencies))}function Ih(e,t){if(t.completeness_only&&(e.rule.kind!=="require_fields"||e.subject?.operations!==void 0)||e.rule.kind==="approval"&&t.before===null)return!1;let r=e.subject??{},n=t.after?.status??t.before?.status;return[t.before,t.after].some(o=>o!==null&&Ah(r,{...o,status:n},t.operation))}function Th(e,t,r,n){let o=["type","tags","parent","dependencies"].some(i=>!B(t.before?.[i],t.after?.[i]));return t.after&&(t.completeness_only||r||n||o)?e.filter(i=>!kh(no(t.after,i))):[]}function Ch(e,t,r,n){let o=t.after??t.before,i=Sh(e,o);return t.approvals?.some(s=>s.policy_fingerprint===n&&s.content_fingerprint===i&&s.author!==t.author&&r.includes(s.author))??!1}function Rh(e,t,r){let n=e.rule,o=t.before?.status!==t.after?.status,i="fields"in n&&n.fields.some(s=>!B(no(t.before,s),no(t.after,s)));switch(n.kind){case"require_fields":{let s=Th(n.fields,t,o,i);return{satisfied:s.length===0,missing_fields:s,remediation:"Supply the declared required fields before this lifecycle transition."}}case"transition":return{satisfied:!o||n.allowed.some(([s,a])=>s===String(t.before?.status??"$create")&&a===String(t.after?.status??"$delete")),missing_fields:[],remediation:"Choose a declared allowed transition; inspect pm schema policies."};case"authors":return{satisfied:n.authors.includes(t.author),missing_fields:[],remediation:"Have a declared workflow actor perform this operation."};case"field_writers":return{satisfied:!i||n.authors.includes(t.author),missing_fields:[],remediation:"Have a declared field writer change the protected fields."};case"approval":return{satisfied:!o||Ch(e,t,n.authors,r),missing_fields:[],remediation:`Record an independent approval with pm schema policy-approve <item-id> --policy ${e.id} after preparing the reviewed fields.`}}}function Sd(e,t,r){let n=e.policies.filter(o=>Ih(o,t)).map(o=>{let i=o.effect??"advise",s=r(o);return{policy_id:o.id,policy_fingerprint:s,rule:o.rule.kind,effect:i==="refuse"&&e.enforcement!=="refuse"?"warn":i,...Rh(o,t,s)}});return{allowed:!n.some(o=>!o.satisfied&&o.effect==="refuse"),decisions:n,warnings:n.filter(o=>!o.satisfied).map(o=>`workflow_policy:${o.effect}:${o.policy_id}:${o.rule}`)}}function bC(e,t){return Sd(e,t,kd)}function wC(e){let t=Eh(e),r=new Map(t.policies.map(n=>[n,kd(n)]));return n=>Sd(t,n,o=>r.get(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]="432226a6-9df4-5de6-b9af-5c06ec2eed66")}catch{}})();var xh=[...xe],Nh=[...Vt],Dh=[...Pn],OC=[...Mn],AC=[...$n],Ph=[...jn],oo=["init","config","extension","package","packages","install","upgrade","create","item","copy","focus","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","aggregate","context","ctx","get","graph","search","duplicates","eval","next","history","events","history-redact","history-repair","history-compact","history-attest","history-author-acknowledge","merge","schema","profile","activity","restore","update","update-many","close","close-many","delete","append","comments","notes","learnings","files","docs","deps","plan","test","test-all","telemetry","stats","health","validate","assurance","gc","workspace","contracts","claim","release","start-task","pause-task","close-task","meet","event","remind","help"],IC=["ancestors","descendants","predecessors","successors","paths","impact","analyze","audit","communities","redundancy","dominators","slack","centrality","articulation","plan","index"],TC=["install","reconcile","report","driver"],Mh=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],$h=["upgrade"],jh=["reopen"],Od={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},Kt=Object.freeze(oo.flatMap(e=>e in Od?[]:e==="extension"||e==="package"?[...Mh.map(t=>`${e}-${t}`),...e==="package"?$h.map(t=>`package-${t}`):[],e]:e==="item"?jh.map(t=>`item-${t}`):[e])),Lh=Object.freeze(zn.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&&Kt.includes(e.alias)).map(e=>e.alias)),CC=Object.freeze(Kt.filter(e=>!Lh.includes(e)));function RC(e=oo,t=Kt,r=Od){let n=new Set(t),o=new Set(e);return{missing_cli_actions:e.filter(i=>!n.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&r[i]===void 0),waived_cli_actions:e.filter(i=>!n.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&r[i]!==void 0),stale_waivers:Object.keys(r).filter(i=>!o.has(i)||n.has(i)||t.some(s=>s.startsWith(`${i}-`)))}}function xC(e){return Kt.includes(e)}function NC(e){return xh.includes(e)}function DC(e){return Nh.includes(e)}function PC(e){return Dh.includes(e)}function MC(e){return Ph.includes(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]="53865a81-4c96-51e2-a378-ae0e2781a50f")}catch{}})();var io={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"},so=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),Yt=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate","duplicates","package-catalog","package-manage","comments-audit","assurance"];(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]="f8657910-1392-5fae-afda-614b96dc8320")}catch{}})();function F(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Fh(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function fe(e){return e?D(e):{}}function me(e){return e?D(e):Fh()}function D(e){return structuredClone(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]="615b4955-a30d-5d45-a86d-4bcf7bd9bd7a")}catch{}})();var zh=new Set(["commands","command_overrides","command_handlers","flag_commands","parser_overrides"]),Uh=["commands","command_overrides","command_handlers","hooks","flag_commands","item_types","item_fields","relationship_kinds","migrations","profiles","importers","exporters","search_providers","vector_store_adapters","assurance_providers","parser_overrides","service_overrides","renderer_overrides"];function Hh(e,t){for(let r of Uh){let n=e[r];if(n===void 0)continue;if(!Array.isArray(n)||n.some(i=>typeof i!="string"))return!1;let o=n.map(i=>zh.has(r)?F(i):i.trim()).filter(i=>i.length>0);t[r]=[...new Set(o)].sort((i,s)=>i.localeCompare(s))}return!0}function qh(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="object"||r===null)return null;let n=r;if(n.format!=="json"&&n.format!=="toon"||!Array.isArray(n.commands)||n.commands.some(o=>typeof o!="string")||typeof n.result_discriminator!="boolean")return null;t.push({format:n.format,commands:[...new Set(n.commands.map(o=>F(o)))].sort((o,i)=>o.localeCompare(i)),result_discriminator:n.result_discriminator})}return t.sort((r,n)=>r.format.localeCompare(n.format))}function Vh(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="object"||r===null)return null;let n=r.commands;if(!Array.isArray(n)||n.some(o=>typeof o!="string"))return null;t.push({commands:[...new Set(n.map(o=>F(o)))].filter(o=>o.length>0).sort((o,i)=>o.localeCompare(i))})}return t}function ao(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.schema_version!==1)return null;let r={schema_version:1};if(!Hh(t,r))return null;let n=t.preflight_overrides;if(n!==void 0&&(!Number.isInteger(n)||n<0))return null;typeof n=="number"&&(r.preflight_overrides=n);let o=t.renderer_ownership;if(o!==void 0){let s=qh(o);if(s===null)return null;r.renderer_ownership=s}let i=t.preflight_ownership;if(i!==void 0){let s=Vh(i);if(s===null)return null;r.preflight_ownership=s}return r}function zC(e){return{schema_version:1,commands:e.commands,command_overrides:e.command_overrides,command_handlers:e.command_handlers,hooks:e.hooks,flag_commands:e.flag_commands,item_types:e.item_types,item_fields:e.item_fields,...e.relationship_kinds?{relationship_kinds:e.relationship_kinds}:{},migrations:e.migrations,profiles:e.profiles,importers:e.importers,exporters:e.exporters,search_providers:e.search_providers,vector_store_adapters:e.vector_store_adapters,...e.assurance_providers?{assurance_providers:e.assurance_providers}:{},parser_overrides:e.parser_overrides,service_overrides:e.service_overrides,renderer_overrides:e.renderer_overrides,...e.renderer_ownership?{renderer_ownership:e.renderer_ownership}:{},preflight_overrides:e.preflight_overrides,...e.preflight_ownership?{preflight_ownership:e.preflight_ownership}:{}}}(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]="628615ea-5be3-5753-a6c5-3eba8400a8da")}catch{}})();function co(e,t,r){if(e===t)return 0;if(Math.abs(e.length-t.length)>r)return null;let n=t.length+1,o=new Array(n),i=new Array(n),s=new Array(n);for(let c=0;c<n;c+=1)o[c]=0,i[c]=c;for(let c=1;c<=e.length;c+=1){s[0]=c;let d=s[0];for(let l=1;l<=t.length;l+=1){let u=e[c-1]===t[l-1]?0:1,f=i[l-1]+u,m=s[l-1]+1,_=i[l]+1,y=Math.min(f,m,_);c>1&&l>1&&e[c-1]===t[l-2]&&e[c-2]===t[l-1]&&(y=Math.min(y,o[l-2]+1)),s[l]=y,y<d&&(d=y)}if(d>r)return null;for(let l=0;l<n;l+=1)o[l]=i[l],i[l]=s[l]}let a=i[t.length];return a<=r?a: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]="7359c10a-4c56-57ea-8254-fc26b19e5c84")}catch{}})();function Lr(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function He(e){return xe.includes(e)}function Ad(e){let t=e.trim().toLowerCase();return He(t)?t:null}function Id(e){return e.filter(t=>!He(t))}function Ji(e){let t=e.trim().toLowerCase();return t.length===0?null:Bc[t]??null}function Td(e){let t=Lr([...e].map(i=>i.toLowerCase())),r=[],n=[];for(let i of t){let s=Ji(i);if(s){r.push(s),n.push({alias:i,target:s});continue}r.push(i)}let o=[...new Map(n.map(i=>[`${i.alias}>${i.target}`,i])).values()].sort((i,s)=>i.alias.localeCompare(s.alias));return{capabilities:Lr(r),legacy_aliases:o}}function Bh(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let r=Ji(t);if(r)return r;let n=Math.max(1,Math.floor(t.length*.34)),o=null,i=Number.POSITIVE_INFINITY;for(let s of xe){let a=co(t,s,n);a!==null&&a<i&&(i=a,o=s)}return o}function Cd(e,t,r){let n=xe.join(","),o=Bh(r)??"none";return`extension_capability_unknown:${e}:${t}:${r}:allowed=${n}:suggested=${o}`}function Rd(e,t,r){let n=r.map(o=>`${o.alias}>${o.target}`).join(",");return`extension_capability_legacy_alias:${e}:${t}:aliases=${n}`}function Wh(e){let t=/^extension_capability_unknown:(global|project):([^:]+):([^:]+):allowed=([^:]+):suggested=([^:]+)$/.exec(e.trim());if(!t)return null;let[,r,n,o,i,s]=t,a=r,c=i.split(",").map(u=>u.trim()).filter(u=>u.length>0),d=Ji(o),l=(s==="none"?void 0:s)??d??void 0;return{layer:a,name:n,capability:o,allowed_capabilities:c,capability_contract_version:Pi,suggested_capability:l,suggestion_source:l?d===l?"legacy_alias":"nearest_match":void 0,legacy_alias_target:d??void 0}}function Gh(e){let t=/^extension_capability_legacy_alias:(global|project):([^:]+):aliases=(.+)$/.exec(e.trim());if(!t)return[];let[,r,n,o]=t,i=r,s=[...xe],a=[];for(let c of o.split(",")){let[d,l]=c.split(">"),u=d?.trim(),f=l?.trim().toLowerCase();!u||!f||!He(f)||a.push({layer:i,name:n,capability:u,allowed_capabilities:s,capability_contract_version:Pi,suggested_capability:f,suggestion_source:"legacy_alias",legacy_alias_target:f})}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]="01116a5e-62d1-591b-9fd0-84ac6e99f8d0")}catch{}})();function Fr(){return{beforeCommand:[],beforeMutation:[],afterCommand:[],onWrite:[],onRead:[],onIndex:[]}}function Zi(){return{overrides:[],handlers:[]}}function Qi(){return{overrides:[]}}function es(){return{overrides:[]}}function ts(){return{overrides:[]}}function rs(){return{overrides:[]}}function ns(){return{commands:[],flags:[],item_fields:[],item_types:[],relationship_kinds:[],migrations:[],profiles:[],importers:[],exporters:[],search_providers:[],vector_store_adapters:[],assurance_providers:[]}}(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]="67511565-01f8-58a6-ad06-45b5d0ce831b")}catch{}})();var Kh=new Set(["name","version","entry","priority","description","author","capabilities","manifest_version","pm_min_version","pm_max_version","engines","trusted","provenance","sandbox_profile","permissions","activation","contributions","legacy_capability_aliases"]);function Yh(e){return{unknownKeys:Object.keys(e).filter(t=>!Kh.has(t)).sort((t,r)=>t>r?1:-1),missingVersionBounds:e.pm_min_version===void 0&&e.pm_max_version===void 0}}function Xh(e){let t=Yh(e),r=t.unknownKeys.map(n=>({code:"manifest_unknown_key",path:n,...n==="compatibility"?{suggested_key:"pm_min_version"}:{},message:n==="compatibility"?'Manifest key "compatibility" is ignored; declare the canonical pm_min_version and optional pm_max_version fields instead.':`Manifest key "${n}" is not part of the extension manifest contract and will be ignored.`}));return t.missingVersionBounds&&r.push({code:"no_version_bounds_declared",path:"$",suggested_key:"pm_min_version",message:"No canonical pm version bounds are declared; add pm_min_version so compatibility intent is explicit."}),{ok:r.length===0,findings:r}}function xd(e,t,r){return Xh(r).findings.map(n=>n.code==="manifest_unknown_key"?`extension_manifest_unknown_key:${e}:${t.name}:key=${n.path}${n.suggested_key?`:suggested=${n.suggested_key}`:""}`:`extension_manifest_no_version_bounds:${e}:${t.name}:suggested=pm_min_version`)}import{constants as qe}from"node:os";(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]="151124a3-cefa-55d3-bf4f-bd8f2553ad72")}catch{}})();var Nd=new Map([["EACCES",{summary:"was denied filesystem permission",recovery:"Grant the required filesystem access, then retry.",category:"permission"}],["EDQUOT",{summary:"exceeded the filesystem quota",recovery:"Raise or reclaim the filesystem quota, then retry.",category:"capacity"}],["EMFILE",{summary:"exhausted the process file-descriptor limit",recovery:"Close unused file handles or raise the process limit, then retry.",category:"resource"}],["ENFILE",{summary:"exhausted the host file-descriptor limit",recovery:"Free host file descriptors or raise the host limit, then retry.",category:"resource"}],["ENOMEM",{summary:"ran out of available memory",recovery:"Free memory or reduce concurrent work, then retry.",category:"resource"}],["ENOSPC",{summary:"ran out of storage space",recovery:"Free storage on the filesystem holding the project, then retry.",category:"capacity"}],["EPERM",{summary:"was denied by the host permission policy",recovery:"Grant the required filesystem permission, then retry.",category:"permission"}],["EROFS",{summary:"targeted a read-only filesystem",recovery:"Use a writable project filesystem or remount it read-write, then retry.",category:"permission"}]]),Jh=/^[a-z][a-z0-9_]{0,63}$/u,Zh=new Map([[qe.errno.EACCES,"EACCES"],[qe.errno.EDQUOT,"EDQUOT"],[qe.errno.EMFILE,"EMFILE"],[qe.errno.ENFILE,"ENFILE"],[qe.errno.ENOMEM,"ENOMEM"],[qe.errno.ENOSPC,"ENOSPC"],[qe.errno.EPERM,"EPERM"],[qe.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),Qh={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function eg(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&Nd.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:Zh.get(Math.abs(t.errno))??null}function tg(e,t,r={}){let n=eg(e);if(n===null)return null;if(!Jh.test(t))throw new g("Host environment operation labels must be bounded identifiers.",h.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let o=Nd.get(n);return new g(`Host filesystem operation ${t} ${o.summary}.`,h.GENERIC_FAILURE,{code:r.codes?.[o.category]??Qh[o.category].code,reason:n,required:o.recovery,why:r.why??"The operating system refused a required project filesystem operation.",nextSteps:[o.recovery,...r.nextSteps??[]],...r.suggestedRetry?{recovery:{suggested_retry:r.suggestedRetry}}:{}})}async function Dd(e,t,r={}){try{return await t()}catch(n){throw tg(n,e,r)??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]="c24357cc-5dad-5cd7-aa89-cddd2945aab7")}catch{}})();var rg=Object.freeze([{flag:"--json"},{flag:"--lean"},{flag:"--token-accounting"},{flag:"--output-include",value_name:"fields"},{flag:"--output-limit",value_name:"count"},{flag:"--output-budget",value_name:"tokens"},{flag:"--output-format",value_name:"toon|json"},{flag:"--output-session",value_name:"state"},{flag:"--output-cursor",value_name:"cursor"},{flag:"--output-row-contract"},{flag:"--quiet"},{flag:"--no-changed-fields"},{flag:"--full-changed-fields"},{flag:"--id-only"},{flag:"--pm-path",aliases:["--path"]},{flag:"--no-extensions"},{flag:"--no-pager"},{flag:"--profile"},{flag:"--help"},{flag:"--author",value_name:"id"}]),os=new Set(rg.flatMap(e=>[e.flag,...e.aliases??[]]));(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]="896ebde0-4ca1-50ed-bb8e-2a8c2d978d94")}catch{}})();var Pd=/^(--[a-z0-9][a-z0-9_-]*)(?:[ =](<[^<>]+>|\[[^[\]]+\]))?$/;function is(e){if(typeof e!="string")return null;let t=Pd.exec(e.trim());if(!t)return null;let r=t[2];return{name:t[1],valueName:r?r.slice(1,-1):null,optional:r?.startsWith("[")??!1}}function eR(e){let t=is(e);return t?t.name:typeof e=="string"&&e.trim()||null}function ng(e){if(typeof e!="string")return null;let t=e.trim(),r=t.split(/[ =]/,1)[0];return os.has(r)?"host_owned_flag_collision":Pd.test(t)?null:"malformed_long_flag"}function Md(e,t){let r=[e,t].find(i=>typeof i=="string"&&os.has(i.trim().split(/[ =]/,1)[0]));if(typeof r=="string")return{token:r.trim().split(/[ =]/,1)[0],failure:"host_owned_flag_collision"};if(typeof e!="string")return null;let n=e.trim(),o=ng(n);return o===null?null:{token:n,failure:o}}function $d(e,t){return t==="host_owned_flag_collision"?`cannot shadow host-owned global flag "${e}"; read it from context.global instead`:`long flag "${e}" must start with a double-dash name such as "--my-flag" or "--my-flag <value>"`}(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]="5c3049c3-1d5a-5e7e-a070-35340737a6ab")}catch{}})();var jd=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"boolean"});function lo(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.hasOwn(jd,t)?jd[t]:null}function og(e,t,r){return!!(e.value_name?.trim()||t||r||e.required===!0||e.list===!0||e.repeatable===!0)}function ig(e){return(e.value_type?.trim()||e.type?.trim())?.toLowerCase()}function nR(e){let t=ig(e),r=lo(t),n=is(e.long),o=e.value_name?.trim()||null,i=!(r==="boolean"&&t!=="bool")&&og(e,n?.valueName,t),s=n?.valueName?n.optional:t==="bool";return{value_type:r,value_arity:i?s?"optional":"required":"none",value_name:i?o??n?.valueName??"value":null}}function Ld(e){let t=[],r=n=>{if(Array.isArray(n)){for(let o of n)r(o);return}if(typeof n=="string"){for(let o of n.split(",")){let i=o.trim();i.length>0&&t.push(i)}return}n!=null&&t.push(n)};return r(e),t}function Fd(e,t){return t==="string"?!0:t==="number"?typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.trim().length>0&&Number.isFinite(Number(e)):typeof e=="boolean"?!0:typeof e=="string"&&["true","false","1","0"].includes(e.trim().toLowerCase())}function oR(e,t){return t==="number"?typeof e=="number"&&Number.isFinite(e)?null:{kind:t,received:e,expected:"a finite number"}:typeof e=="boolean"?null:{kind:t,received:e,expected:"true, false, 1, or 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]="1dcf5e56-cb0c-5e4c-b0e8-e4dbd06187dd")}catch{}})();var sg=5e3;async function zr(e,t,r){let n=[];for(let o of e)try{await o.run(D(r))}catch{n.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return n}async function ag(e,t){return zr(e.beforeCommand,"beforeCommand",t)}function cg(e,t,r){if(e===void 0)return;if(typeof e!="object"||e===null||!("allow"in e)||e.allow!==!0&&e.allow!==!1)throw new g(`Extension mutation guard ${t.name} returned an invalid decision.`,h.CONFLICT,{code:"extension_mutation_guard_invalid_decision",reason:`${t.layer}:${t.name}`,nextSteps:["Return { allow: true } or a structured denial from the guard."]});if(e.allow)return;let n=e,o=typeof n.code=="string"?n.code.trim():"",i=typeof n.remediation=="string"?n.remediation.trim():"";if(o.length===0||i.length===0)throw new g(`Extension mutation guard ${t.name} returned an invalid denial.`,h.CONFLICT,{code:"extension_mutation_guard_invalid_denial",reason:`${t.layer}:${t.name}`,nextSteps:["Return non-empty code and remediation fields from the guard."]});let s=typeof n.message=="string"?n.message.trim():"";throw new g(s||`Extension mutation guard ${t.name} denied ${r}.`,h.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function ss(e,t){for(let r of e.beforeMutation??[]){let n,o;try{let i=Promise.resolve().then(()=>r.run({pm_root:t.pm_root,operation:t.operation,before:t.before===null?null:D(t.before),after:t.after===null?null:D(t.after),changed_fields:[...t.changed_fields],sdk:t.sdk}));i.catch(()=>{}),n=await Promise.race([i,new Promise((s,a)=>{o=setTimeout(()=>{a(new g(`Extension mutation guard ${r.name} timed out before ${t.operation}.`,h.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${r.layer}:${r.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},sg),o.unref?.()})])}catch(i){throw i instanceof g?i:new g(`Extension mutation guard ${r.name} failed before ${t.operation}.`,h.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${r.layer}:${r.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(o)}cg(n,r,t.operation)}}async function dg(e,t){return zr(e.afterCommand,"afterCommand",t)}async function as(e,t){return zr(e.onWrite,"onWrite",t)}async function cs(e,t){return zr(e.onRead,"onRead",t)}async function ds(e,t){return zr(e.onIndex,"onIndex",t)}function lg(e){let t="";e instanceof Error&&typeof e.message=="string"?t=e.message:typeof e=="string"?t=e:typeof e=="object"&&e!==null&&typeof e.message=="string"&&(t=e.message);let r=t.replace(/\s+/gu," ").trim();if(r.length===0)return"";let n=300;return r.length>n?`${r.slice(0,n-1)}\u2026`:r}function uo(e,t){if(typeof e!="object"||e===null||typeof e[t]!="string")return;let r=String(e[t]).replace(/\s+/gu," ").trim();return r.length>0?r.slice(0,300):void 0}function ug(e){if(typeof e!="object"||e===null||!Object.hasOwn(e,"exit_code"))return;let t=e.exit_code;if(typeof t!="number"||!Number.isInteger(t)||t<1||t>255)throw new TypeError("Extension command result exit_code must be an integer from 1 to 255.");return t}async function ls(e,t){let r=F(t.command);if(r.length===0)return{handled:!1,result:null,warnings:[]};let n=[...e.handlers].reverse().find(o=>o.command===r);if(!n)return{handled:!1,result:null,warnings:[]};try{let o=await n.run({command:r,args:D(t.args),options:D(t.options),global:D(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel,...t.sdk===void 0?{}:{sdk:t.sdk}});return{handled:!0,result:o,warnings:[],...Object.fromEntries([["exitCode",ug(o)],["errorCode",uo(o,"code")],["remediation",uo(o,"remediation")]].filter(i=>i[1]!==void 0))}}catch(o){let i=typeof o=="object"&&o!==null&&"exitCode"in o?o.exitCode:void 0;if(typeof i=="number"&&Number.isFinite(i))throw o;return{handled:!1,result:null,warnings:[`extension_command_handler_failed:${n.layer}:${n.name}:${n.command}`],errorMessage:lg(o),...Object.fromEntries([["errorCode",uo(o,"code")],["remediation",uo(o,"remediation")]].filter(s=>s[1]!==void 0))}}}async function us(e,t){let r=F(t.command);if(r.length===0)return{overridden:!1,context:{command:r,args:D(t.args),options:fe(t.options),global:me(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[]};let n=[...e.overrides].reverse().find(o=>o.command===r);if(!n)return{overridden:!1,context:{command:r,args:D(t.args),options:fe(t.options),global:me(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[]};try{let o=await Promise.resolve(n.run({command:r,args:D(t.args),options:fe(t.options),global:me(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel}))??{},i=Array.isArray(o.args)?D(o.args):D(t.args),s=o.options?fe(o.options):fe(t.options),a=o.global?me(o.global):me(t.global);return{overridden:!0,context:{command:r,args:i,options:s,global:a,pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[]}}catch{return{overridden:!1,context:{command:r,args:D(t.args),options:fe(t.options),global:me(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[`extension_parser_override_failed:${n.layer}:${n.name}:${n.command}`]}}}async function fs(e,t){let r={command:F(t.command),args:D(t.args),options:fe(t.options),global:me(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},n=D(t.decision),o=[...e.overrides].reverse().find(i=>!i.commands?.length||i.commands.includes(r.command));if(!o)return{overridden:!1,context:r,decision:n,warnings:[]};try{let i=await Promise.resolve(o.run({command:r.command,args:D(r.args),options:fe(r.options),global:me(r.global),pm_root:r.pm_root,source_workspace_root:r.source_workspace_root,repo_root:r.repo_root,pm_root_rel:r.pm_root_rel,decision:D(n)}))??{},s={command:r.command,args:Array.isArray(i.args)?D(i.args):r.args,options:i.options?fe(i.options):r.options,global:i.global?me(i.global):r.global,pm_root:r.pm_root,source_workspace_root:r.source_workspace_root,repo_root:r.repo_root,pm_root_rel:r.pm_root_rel},a={enforce_item_format_gate:typeof i.enforce_item_format_gate=="boolean"?i.enforce_item_format_gate:n.enforce_item_format_gate,run_preflight_item_format_sync:typeof i.run_preflight_item_format_sync=="boolean"?i.run_preflight_item_format_sync:n.run_preflight_item_format_sync,run_extension_migrations:typeof i.run_extension_migrations=="boolean"?i.run_extension_migrations:n.run_extension_migrations,enforce_mandatory_migration_gate:typeof i.enforce_mandatory_migration_gate=="boolean"?i.enforce_mandatory_migration_gate:n.enforce_mandatory_migration_gate};return{overridden:!0,context:s,decision:a,warnings:[]}}catch{return{overridden:!1,context:r,decision:n,warnings:[`extension_preflight_override_failed:${o.layer}:${o.name}`]}}}function zd(e){return{handled:!1,result:e.payload,warnings:[]}}function Ud(e,t){return[...e.overrides].reverse().filter(r=>r.service===t)}function Hd(e){return{service:e.service,command:e.command?F(e.command):void 0,args:e.args?D(e.args):void 0,options:e.options?fe(e.options):void 0,global:e.global?me(e.global):void 0,pm_root:e.pm_root,source_workspace_root:e.source_workspace_root,repo_root:e.repo_root,pm_root_rel:e.pm_root_rel,payload:D(e.payload)}}function fg(e){if(typeof e!="object"||e===null||!Object.hasOwn(e,"handled"))return!1;let t=e.handled;return t===!0?Object.hasOwn(e,"result"):t===!1&&Reflect.ownKeys(e).length===1}function qd(e,t){return fg(e)?e.handled?{handled:!0,result:e.result}:{handled:!1,result:t.payload}:t.service==="output_format"&&e==null?{handled:!1,result:t.payload}:{handled:!0,result:e}}function Vd(e,t,r){return t.service==="output_format"&&typeof e=="object"&&e!==null&&B(e,r.payload)}function Bd(e,t,r){if(t.handled){if(e.passThrough===!0){r.push(`extension_service_pass_through_contract_violated:${e.layer}:${e.name}:${e.service}`);return}return{handled:!0,result:t.result,warnings:r}}}function ms(e,t){let r=Ud(e,t.service);if(r.length===0)return zd(t);let n=[];for(let o of r)try{let i=Hd(t),s=o.run(i);if(s instanceof Promise){n.push(`extension_service_override_async_unsupported:${o.layer}:${o.name}:${o.service}`);continue}if(Vd(s,t,i)){n.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=Bd(o,qd(s,t),n);if(a)return a}catch{n.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:n}}async function ps(e,t){let r=Ud(e,t.service);if(r.length===0)return zd(t);let n=[];for(let o of r)try{let i=Hd(t),s=await Promise.resolve(o.run(i));if(Vd(s,t,i)){n.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=Bd(o,qd(s,t),n);if(a)return a}catch{n.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:n}}function _s(e,t){let r=F(t.command);if(r.length===0)return{overridden:!1,result:t.result,warnings:[]};let n=[...e.overrides].reverse().find(o=>o.command===r);if(!n)return{overridden:!1,result:t.result,warnings:[]};try{let o=fe(t.options),i=me(t.global),s=n.run({command:r,args:D(t.args),options:o,global:i,pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel,result:D(t.result)});return s instanceof Promise?{overridden:!1,result:t.result,warnings:[`extension_command_override_async_unsupported:${n.layer}:${n.name}:${n.command}`]}:{overridden:!0,result:s,warnings:[]}}catch{return{overridden:!1,result:t.result,warnings:[`extension_command_override_failed:${n.layer}:${n.name}:${n.command}`]}}}function mg(e,t,r){if((e.commands?.length??0)>0&&!e.commands?.includes(t))return!1;if(e.resultDiscriminator===void 0)return!0;try{return e.resultDiscriminator(D(r))}catch{return!1}}function ys(e,t){let r=typeof t.command=="string"?F(t.command):"",n=[...e.overrides].reverse().find(o=>o.format===t.format&&mg(o,r,t.result));if(!n)return{overridden:!1,rendered:null,warnings:[]};try{let o=Array.isArray(t.args)?D(t.args):[],i=fe(t.options),s=me(t.global),a=typeof t.pm_root=="string"?t.pm_root:"",c=n.run({format:t.format,command:r,args:o,options:i,global:s,pm_root:a,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel,result:D(t.result)});return c==null?{overridden:!1,rendered:null,warnings:[]}:typeof c!="string"?{overridden:!1,rendered:null,warnings:[`extension_renderer_invalid_result:${n.layer}:${n.name}:${n.format}`]}:{overridden:!0,rendered:c,warnings:[]}}catch{return{overridden:!1,rendered:null,warnings:[`extension_renderer_failed:${n.layer}:${n.name}:${n.format}`]}}}import vt from"node:fs/promises";import wt from"node:path";import{pathToFileURL as Yg}from"node:url";import Wd from"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]="01422574-583a-5fd1-bc00-f61f430073cd")}catch{}})();function hs(e,t){let r=Wd.relative(e,t);return r.length===0?!0:!r.startsWith("..")&&!Wd.isAbsolute(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]="559b05dc-0290-5a7c-97b9-ef1e5e8670ba")}catch{}})();function Gd(e){let t={beforeCommand:e.hooks.beforeCommand.length,beforeMutation:e.hooks.beforeMutation.length,afterCommand:e.hooks.afterCommand.length,onWrite:e.hooks.onWrite.length,onRead:e.hooks.onRead.length,onIndex:e.hooks.onIndex.length,commandOverrides:e.commands.overrides.length,commandHandlers:e.commands.handlers.length,parserOverrides:e.parsers.overrides.length,preflightOverrides:e.preflight.overrides.length,serviceOverrides:e.services.overrides.length,rendererOverrides:e.renderers.overrides.length,registrations:Object.fromEntries(Object.entries(e.registrations).map(([r,n])=>[r,n.length]))};return()=>{e.hooks.beforeCommand.length=t.beforeCommand,e.hooks.beforeMutation.length=t.beforeMutation,e.hooks.afterCommand.length=t.afterCommand,e.hooks.onWrite.length=t.onWrite,e.hooks.onRead.length=t.onRead,e.hooks.onIndex.length=t.onIndex,e.commands.overrides.length=t.commandOverrides,e.commands.handlers.length=t.commandHandlers,e.parsers.overrides.length=t.parserOverrides,e.preflight.overrides.length=t.preflightOverrides,e.services.overrides.length=t.serviceOverrides,e.renderers.overrides.length=t.rendererOverrides;for(let[r,n]of Object.entries(t.registrations))e.registrations[r].length=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]="17ae377d-20c2-5e45-825a-48a79c6c7601")}catch{}})();function G(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return t}function Z(e,t){if(t!==void 0&&typeof t!="boolean")throw new TypeError(`${e} must be a boolean when provided`)}function q(e,t){if(t!==void 0&&(typeof t!="string"||t.trim().length===0))throw new TypeError(`${e} must be a non-empty string when provided`)}function Kd(e,t){if(t===void 0)return;let r=n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean";if(Array.isArray(t)){for(let[n,o]of t.entries())if(!r(o))throw new TypeError(`${e}[${n}] must be a string, number, or boolean`);return}if(!r(t))throw new TypeError(`${e} must be a string, number, or boolean, or an array of these when provided`)}function ht(e,t){if(t!==void 0){if(!Array.isArray(t))throw new TypeError(`${e} must be an array of non-empty strings when provided`);for(let[r,n]of t.entries())if(typeof n!="string"||n.trim().length===0)throw new TypeError(`${e}[${r}] must be a non-empty string`)}}function Ur(e,t){if(ht(e,t),!Array.isArray(t))return[];let r=[],n=new Set;for(let o of t){let i=o.trim();i.length===0||n.has(i)||(n.add(i),r.push(i))}return 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]="34536eba-0f92-5599-a807-5b39b000e733")}catch{}})();var gs=Object.freeze(["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"]);(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]="60fd882d-7c92-5be5-bf46-7e3c128bfb58")}catch{}})();var pg=new Set(gs);function _g(e){if(e!==void 0&&!pg.has(String(e)))throw new Error(`registerCommand definition.family must be one of: ${gs.join(", ")}`)}function Yd(e){q("registerCommand definition.action",e.action),q("registerCommand definition.family",e.family),q("registerCommand definition.description",e.description),q("registerCommand definition.intent",e.intent),q("registerCommand definition.tier",e.tier);let t=e.tier;if(t!==void 0&&t!=="core"&&t!=="standard"&&t!=="full"&&t!=="internal")throw new Error("registerCommand definition.tier must be core, standard, full, or internal");_g(e.family)}(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]="095ea29d-eda3-5287-b54d-8a961658f7bc")}catch{}})();function Xd(e,t="",r=""){if(e===void 0)return;if(Xt(t)||Xt(r))throw new TypeError("Native pm commands and actions cannot declare read_output");let n=G("registerCommand definition.read_output",e);if(Object.keys(n).some(s=>s!=="row_keys")||!Array.isArray(n.row_keys))throw new TypeError("registerCommand definition.read_output requires only row_keys: string[]");let o=Array.from(n.row_keys),i=new Set(["__proto__","constructor","prototype","row_contract","read_output","read_session","omission_receipt","output_budget_truncation"]);if(o.some(s=>typeof s!="string"||!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*$/u.test(s)||s.split(".").some(a=>i.has(a))))throw new TypeError("registerCommand definition.read_output row_keys must be safe dot-delimited property paths");if(new Set(o).size!==o.length||o.some(s=>o.some(a=>a.startsWith(`${s}.`))))throw new TypeError("registerCommand definition.read_output row_keys must be unique and non-overlapping");return Object.freeze({row_keys:Object.freeze([...o])})}function Xt(e){let t=e.trim().toLowerCase().replace(/\s+/gu,"-");return Kt.includes(t)||Yt.includes(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]="07cb237c-3956-5997-85f8-972d2ee490d0")}catch{}})();function yg(e){let t=G("registerExporter options.output",e),r=new Set(["channel","receipt","media_type"]);for(let n of Object.keys(t))if(!r.has(n))throw new TypeError(`registerExporter options.output contains unsupported field ${n}`);if(t.channel!=="stdout"&&t.channel!=="file")throw new TypeError("registerExporter options.output.channel must be stdout|file");if(t.receipt!==void 0&&t.receipt!=="suppress"&&t.receipt!=="render")throw new TypeError("registerExporter options.output.receipt must be suppress|render");if(t.channel==="stdout"&&t.receipt==="render")throw new TypeError("registerExporter stdout artifacts cannot render a host receipt");return q("registerExporter options.output.media_type",t.media_type),{channel:t.channel,receipt:t.receipt??(t.channel==="stdout"?"suppress":"render"),...typeof t.media_type=="string"?{media_type:t.media_type}:{}}}function Jd(e,t,r){if(e==="registerImporter"&&t.output!==void 0)throw new TypeError("registerImporter options.output is exporter-only");if(e!=="registerExporter"||t.output===void 0)return;let n=yg(t.output);return!r&&n.channel==="stdout"&&(t.description="Export items with the registered extension adapter. Artifact bytes are written exclusively to stdout and the host receipt is suppressed by default."),n}function bs(e,t,r){return{registration:t,action:r,command:e.command,args:D(e.args),options:D(e.options),global:D(e.global),pm_root:e.pm_root,source_workspace_root:e.source_workspace_root,repo_root:e.repo_root,pm_root_rel:e.pm_root_rel,...e.sdk===void 0?{}:{sdk:e.sdk}}}(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]="fc2e7eac-cd1c-5885-aa27-e98455008a4f")}catch{}})();function Zd(e){return!e.extensionReady||!e.enabledForLoad?null:{layer:e.layer,directory:e.directory,manifest_path:e.manifestPath,entry_path:e.entryPath,manifest:e.manifest,source_package:e.sourceIdentity?.package_name,source_aliases:e.sourceIdentity?.aliases,contributions:e.sourceIdentity?.contributions}}(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]="bb1b4879-079c-50d4-afa5-e8a36ead2e5c")}catch{}})();function be(e){return typeof e!="string"?"":e.trim().toLowerCase()}function P(e){return new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))}function hg(e){let t=e.trim().toLowerCase();if(t.length===0)return"";let r=t.split(/[.:/]/).map(n=>n.replace(/[\s_-]+/g,"")).filter(n=>n.length>0);return r.length===0?"":r.length===1?r[0]:`${r[0]}.${r.slice(1).join("")}`}function Jt(e){return new Set((e??[]).map(t=>hg(t)).filter(t=>t.length>0))}function Qd(e){let t=be(e);return Pn.includes(t)?t:"off"}function el(e){let t=be(e);return Mn.includes(t)?t:"off"}function Hr(e){let t=be(e);return $n.includes(t)?t:"none"}function ws(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return Wc.includes(t)?t:void 0}function tl(e){if(typeof e=="string"){let t=ws(e)??"block";return{global:t,project:t}}return typeof e=="object"&&e!==null&&!Array.isArray(e)?{global:ws(e.global)??"block",project:ws(e.project)??"block"}:{global:"block",project:"block"}}function gg(e){return e.global===e.project?e.global:{global:e.global,project:e.project}}function $(e){return[...new Set(e)].sort((t,r)=>t.localeCompare(r))}function bg(e){let t=be(e.name);return t.length===0?null:{name:t,normalized:{name:t,disabled:e.disabled===!0,requireTrusted:e.require_trusted===!0,requireProvenance:e.require_provenance===!0,sandboxProfile:e.sandbox_profile!==void 0?Hr(e.sandbox_profile):void 0,allowedCapabilities:P(e.allowed_capabilities),blockedCapabilities:P(e.blocked_capabilities),allowedSurfaces:Jt(e.allowed_surfaces),blockedSurfaces:Jt(e.blocked_surfaces),allowedCommands:P(e.allowed_commands),blockedCommands:P(e.blocked_commands),allowedActions:P(e.allowed_actions),blockedActions:P(e.blocked_actions),allowedServices:P(e.allowed_services),blockedServices:P(e.blocked_services)}}}function rl(e){let t=new Map;for(let r of e??[]){let n=bg(r);n&&t.set(n.name,n.normalized)}return t}function wg(e){let t=[],r=[...e.overridesByName.values()].sort((o,i)=>o.name.localeCompare(i.name));for(let o of $([...e.allowedCapabilities,...e.blockedCapabilities]))He(o)||t.push(`extension_policy_unknown_capability:${o}`);for(let o of r)for(let i of $([...o.allowedCapabilities,...o.blockedCapabilities]))He(i)||t.push(`extension_policy_unknown_capability:${o.name}:${i}`);let n=new Set(jn);for(let o of $([...e.allowedSurfaces,...e.blockedSurfaces]))n.has(o)||t.push(`extension_policy_unknown_surface:${o}`);for(let o of r)for(let i of $([...o.allowedSurfaces,...o.blockedSurfaces]))n.has(i)||t.push(`extension_policy_unknown_surface:${o.name}:${i}`);return[...new Set(t)].sort((o,i)=>o.localeCompare(i))}function nl(e){let t=e.extensions?.policy??{},r=P(t.allowed_capabilities),n=P(t.blocked_capabilities),o=Jt(t.allowed_surfaces),i=Jt(t.blocked_surfaces),s=rl(t.extension_overrides);return{mode:Qd(t.mode),trustMode:el(t.trust_mode),pmMaxVersionExceededMode:tl(t.pm_max_version_exceeded_mode),requireProvenance:t.require_provenance===!0,trustedExtensions:P(t.trusted_extensions),defaultSandboxProfile:Hr(t.default_sandbox_profile),allowedExtensions:P(t.allowed_extensions),blockedExtensions:P(t.blocked_extensions),allowedCapabilities:r,blockedCapabilities:n,allowedSurfaces:o,blockedSurfaces:i,allowedCommands:P(t.allowed_commands),blockedCommands:P(t.blocked_commands),allowedActions:P(t.allowed_actions),blockedActions:P(t.blocked_actions),allowedServices:P(t.allowed_services),blockedServices:P(t.blocked_services),overridesByName:s,warnings:wg({allowedCapabilities:r,blockedCapabilities:n,allowedSurfaces:o,blockedSurfaces:i,overridesByName:s})}}function ol(e){let t=[...e.overridesByName.values()].sort((r,n)=>r.name.localeCompare(n.name)).map(r=>({name:r.name,...r.disabled?{disabled:!0}:{},...r.requireTrusted?{require_trusted:!0}:{},...r.requireProvenance?{require_provenance:!0}:{},...r.sandboxProfile?{sandbox_profile:r.sandboxProfile}:{},...r.allowedCapabilities.size>0?{allowed_capabilities:$(r.allowedCapabilities)}:{},...r.blockedCapabilities.size>0?{blocked_capabilities:$(r.blockedCapabilities)}:{},...r.allowedSurfaces.size>0?{allowed_surfaces:$(r.allowedSurfaces)}:{},...r.blockedSurfaces.size>0?{blocked_surfaces:$(r.blockedSurfaces)}:{},...r.allowedCommands.size>0?{allowed_commands:$(r.allowedCommands)}:{},...r.blockedCommands.size>0?{blocked_commands:$(r.blockedCommands)}:{},...r.allowedActions.size>0?{allowed_actions:$(r.allowedActions)}:{},...r.blockedActions.size>0?{blocked_actions:$(r.blockedActions)}:{},...r.allowedServices.size>0?{allowed_services:$(r.allowedServices)}:{},...r.blockedServices.size>0?{blocked_services:$(r.blockedServices)}:{}}));return{mode:e.mode,trust_mode:e.trustMode,pm_max_version_exceeded_mode:gg(e.pmMaxVersionExceededMode),require_provenance:e.requireProvenance,trusted_extensions:$(e.trustedExtensions),default_sandbox_profile:e.defaultSandboxProfile,allowed_extensions:$(e.allowedExtensions),blocked_extensions:$(e.blockedExtensions),allowed_capabilities:$(e.allowedCapabilities),blocked_capabilities:$(e.blockedCapabilities),allowed_surfaces:$(e.allowedSurfaces),blocked_surfaces:$(e.blockedSurfaces),allowed_commands:$(e.allowedCommands),blocked_commands:$(e.blockedCommands),allowed_actions:$(e.allowedActions),blocked_actions:$(e.blockedActions),allowed_services:$(e.allowedServices),blocked_services:$(e.blockedServices),extension_overrides:t}}function il(e){let t=rl(e.extension_overrides);return{mode:Qd(e.mode),trustMode:el(e.trust_mode),pmMaxVersionExceededMode:tl(e.pm_max_version_exceeded_mode),requireProvenance:e.require_provenance===!0,trustedExtensions:P(e.trusted_extensions),defaultSandboxProfile:Hr(e.default_sandbox_profile),allowedExtensions:P(e.allowed_extensions),blockedExtensions:P(e.blocked_extensions),allowedCapabilities:P(e.allowed_capabilities),blockedCapabilities:P(e.blocked_capabilities),allowedSurfaces:Jt(e.allowed_surfaces),blockedSurfaces:Jt(e.blocked_surfaces),allowedCommands:P(e.allowed_commands),blockedCommands:P(e.blocked_commands),allowedActions:P(e.allowed_actions),blockedActions:P(e.blocked_actions),allowedServices:P(e.allowed_services),blockedServices:P(e.blocked_services),overridesByName:t,warnings:[]}}function Ve(e,t){return e.overridesByName.get(be(t))??null}function Zt(e,t,r,n,o){return t.has(r)?o:e.size>0&&!e.has(r)?n:null}function sl(e,t,r){let n=r.trim().toLowerCase(),o=Ve(e,t.name),i=o&&o.allowedCapabilities.size>0?o.allowedCapabilities:e.allowedCapabilities,s=new Set([...e.blockedCapabilities,...o?o.blockedCapabilities:[]]);return Zt(i,s,n,"capability_not_allowlisted","capability_blocked")}function vg(e,t,r){let n=Ve(e,t.name),o=n&&n.allowedSurfaces.size>0?n.allowedSurfaces:e.allowedSurfaces,i=new Set([...e.blockedSurfaces,...n?n.blockedSurfaces:[]]);return Zt(o,i,r,"surface_not_allowlisted","surface_blocked")}function Eg(e,t,r){let n=F(r);if(n.length===0)return null;let o=Ve(e,t.name),i=o&&o.allowedCommands.size>0?o.allowedCommands:e.allowedCommands,s=new Set([...e.blockedCommands,...o?o.blockedCommands:[]]);return Zt(i,s,n,"command_not_allowlisted","command_blocked")}function kg(e,t,r){let n=be(r).replace(/\s+/g,"-");if(n.length===0)return null;let o=Ve(e,t.name),i=o&&o.allowedActions.size>0?o.allowedActions:e.allowedActions,s=new Set([...e.blockedActions,...o?o.blockedActions:[]]);return Zt(i,s,n,"action_not_allowlisted","action_blocked")}function Sg(e,t,r){let n=be(r);if(n.length===0)return null;let o=Ve(e,t.name),i=o&&o.allowedServices.size>0?o.allowedServices:e.allowedServices,s=new Set([...e.blockedServices,...o?o.blockedServices:[]]);return Zt(i,s,n,"service_not_allowlisted","service_blocked")}function Og(e,t){let r=be(t.name);return Ve(e,t.name)?.disabled===!0?"extension_override_disabled":Zt(e.allowedExtensions,e.blockedExtensions,r,"extension_not_allowlisted","extension_blocked")}function Ag(e,t){if(e.trustMode==="off")return null;let r=Ve(e,t.name),n=be(t.name),o=t.trusted===!0,i=t.provenanceVerified===!0;return e.trustedExtensions.size>0&&!e.trustedExtensions.has(n)?"extension_not_trusted":(r?.requireTrusted===!0||e.trustMode==="warn"||e.trustMode==="enforce")&&!o?"extension_untrusted":(e.requireProvenance||r?.requireProvenance===!0)&&!i?"provenance_missing_or_unverified":null}function Ig(e,t){if(e.mode==="off")return null;let r=Ve(e,t.name)?.sandboxProfile??t.sandboxProfile??e.defaultSandboxProfile;if(r==="none")return null;let n=t.permissions;if(!n)return"sandbox_permissions_missing";let o=i=>n[i]===!0;return r==="restricted"?o("process_spawn")?"sandbox_restricted_disallows_process_spawn":o("env_write")?"sandbox_restricted_disallows_env_write":null:o("process_spawn")?"sandbox_strict_disallows_process_spawn":o("network")?"sandbox_strict_disallows_network":o("fs_write")?"sandbox_strict_disallows_fs_write":o("env_write")?"sandbox_strict_disallows_env_write":null}function fo(e,t,r,n,o={}){let i=Object.entries(o).sort((a,c)=>a[0].localeCompare(c[0])).map(([a,c])=>`${a}=${c}`).join(":"),s=i.length>0?`:${i}`:"";return`extension_policy_${e}_${t}:${r.layer}:${r.name}:reason=${n}${s}`}function al(e,t){if(e.mode==="off"&&e.trustMode==="off")return{allowed:!0,warning:null};let r=[],n=Og(e,t);n&&r.push({reason:n,scope:"extension",mode:e.mode});let o=Ag(e,t);o&&r.push({reason:o,scope:"trust",mode:e.trustMode});let i=Ig(e,t);i&&r.push({reason:i,scope:"extension",mode:e.mode});let s=r.find(c=>c.mode==="enforce");if(s)return{allowed:!1,warning:fo("blocked",s.scope,t,s.reason)};let a=r.find(c=>c.mode==="warn");return a?{allowed:!0,warning:fo("violation",a.scope,t,a.reason)}:{allowed:!0,warning:null}}function cl(e,t,r){if(e.mode==="off")return{allowed:!0,warning:null};let n=sl(e,t,r);return n?{allowed:e.mode==="warn",warning:fo(e.mode==="warn"?"violation":"blocked","capability",t,n,{capability:r.trim().toLowerCase()})}:{allowed:!0,warning:null}}function Tg(e,t,r,n,o){let i=typeof n=="string"?sl(e,t,n):null,s=vg(e,t,r),a=o.command?Eg(e,t,o.command):null,c=o.action?kg(e,t,o.action):null,d=o.service?Sg(e,t,o.service):null;return i??s??a??c??d}function Cg(e,t,r,n){let o={method:be(e).replace(/\s+/g,"_"),surface:t};return r&&(o.capability=r),n.command&&(o.command=F(n.command)),n.action&&(o.action=be(n.action).replace(/\s+/g,"-")),n.service&&(o.service=be(n.service)),o}function dl(e,t,r,n,o,i){if(e.mode==="off")return{allowed:!0,warning:null};let s=i??{},a=Tg(e,t,r,o,s);if(!a)return{allowed:!0,warning:null};let c=fo(e.mode==="warn"?"violation":"blocked","registration",t,a,Cg(n,r,o,s));return{allowed:e.mode==="warn",warning:c}}(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]="cd1de600-27e4-522b-842e-1993c12e9f0e")}catch{}})();var ul=100;function ll(e,t){let r=e[t];if(r!=null)return typeof r!="string"||r.trim().length===0?null:r.trim()}function Rg(e){if(e==null)return;let t=ze(e);if(!t)return null;let r={};for(let n of Object.keys(t).sort((o,i)=>o.localeCompare(i))){if(n.trim().length===0)return null;let o=t[n];if(typeof o!="string"||o.trim().length===0)return null;r[n.trim()]=o.trim()}return Object.keys(r).length>0?r:void 0}function vs(e,t){let r=e[t];return typeof r!="string"||r.trim().length===0?null:r.trim()}function fl(e){if(e!=null)return typeof e!="number"||!Number.isInteger(e)?null:e}function gt(e){if(e!=null)return typeof e!="boolean"?null:e}function xg(e){let t=fl(e.priority);return t===void 0?ul:t}function Ng(e){let t=e.sandbox_profile;if(t==null)return;if(typeof t!="string")return null;let r=Hr(t);return r!==t.trim().toLowerCase()?null:r}function Es(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Dg(e){if(e==null)return;let t=ze(e);if(!t)return null;let r=Es(t.source),n=Es(t.signature),o=Es(t.attestation),i=t.verified===void 0||t.verified===null?void 0:typeof t.verified=="boolean"?t.verified:null;return i===null?null:{...r?{source:r}:{},...n?{signature:n}:{},...o?{attestation:o}:{},...typeof i=="boolean"?{verified:i}:{}}}function Pg(e){if(e==null)return;let t=ze(e);if(!t)return null;let r=gt(t.fs_read),n=gt(t.fs_write),o=gt(t.network),i=gt(t.env_read),s=gt(t.env_write),a=gt(t.process_spawn);return[r,n,o,i,s,a].includes(null)?null:{...typeof r=="boolean"?{fs_read:r}:{},...typeof n=="boolean"?{fs_write:n}:{},...typeof o=="boolean"?{network:o}:{},...typeof i=="boolean"?{env_read:i}:{},...typeof s=="boolean"?{env_write:s}:{},...typeof a=="boolean"?{process_spawn:a}:{}}}function Mg(e){if(e==null)return{capabilities:[],legacy_aliases:[]};if(!Array.isArray(e)||e.some(r=>typeof r!="string"))return null;let t=Td(e);return{capabilities:t.capabilities,legacy_aliases:t.legacy_aliases}}function $g(e){if(e==null)return;let t=ze(e);if(!t)return null;let r=t.commands;if(r==null)return;if(!Array.isArray(r)||r.some(o=>typeof o!="string"))return null;let n=[...new Set(r.map(o=>F(o)).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));return n.length>0?{commands:n}:void 0}function jg(e){let t=fl(e.manifest_version);if(t===null)return null;let r=ll(e,"pm_min_version");if(r===null)return null;let n=ll(e,"pm_max_version");if(n===null)return null;let o=Rg(e.engines);if(o===null)return null;let i=gt(e.trusted);if(i===null)return null;let s=Ng(e);if(s===null)return null;let a=Dg(e.provenance);if(a===null)return null;let c=Pg(e.permissions);if(c===null)return null;let d=Mg(e.capabilities);if(d===null)return null;let l=$g(e.activation);if(l===null)return null;let u=ao(e.contributions);return u===null?null:{manifest_version:t,pm_min_version:r,pm_max_version:n,engines:o,trusted:i,sandbox_profile:s,provenance:a,permissions:c,capabilities:d.capabilities,legacy_capability_aliases:d.legacy_aliases,activation:l,contributions:u}}function ks(e){if(typeof e!="object"||e===null)return null;let t=e,r=vs(t,"name");if(r===null)return null;let n=vs(t,"version");if(n===null)return null;let o=vs(t,"entry");if(o===null)return null;let i=xg(t);if(i===null)return null;let s=jg(t);return s===null?null:{name:r,version:n,entry:o,priority:i,manifest_version:s.manifest_version,pm_min_version:s.pm_min_version,pm_max_version:s.pm_max_version,engines:s.engines,trusted:s.trusted,provenance:s.provenance,sandbox_profile:s.sandbox_profile,permissions:s.permissions,activation:s.activation,contributions:s.contributions,capabilities:s.capabilities,legacy_capability_aliases:s.legacy_capability_aliases.length>0?s.legacy_capability_aliases:void 0}}import Lg from"node:fs/promises";import qr 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]="029e0066-2ef5-5204-92ad-4866321710f4")}catch{}})();async function ml(e,t){let r=qr.dirname(t.manifest_path),n=qr.relative(r,t.entry_path);if(n.startsWith("..")||qr.isAbsolute(n))throw new Error(`Cannot snapshot extension entry outside its package directory: ${t.entry_path}`);let o=qr.join(e,`${t.layer}-${t.directory.replace(/[^a-zA-Z0-9._-]/gu,"_")}`);return await Dd("extension_module_graph_snapshot",()=>Lg.cp(r,o,{recursive:!0,force:!0})),qr.join(o,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]="bf5c3834-b388-507e-a13c-3beb5d096abb")}catch{}})();function pl(e){let t=typeof e=="function"?e:e.run;if(typeof t!="function")throw new TypeError("registerPreflight override requires a function handler");let r=[...new Set((typeof e=="function"?[]:e.commands??[]).map(n=>{if(typeof n!="string"||n.trim().length===0)throw new TypeError("registerPreflight ownership.commands must contain non-empty command paths");return F(n)}))];return{run:t,...r.length>0?{commands:r}:{}}}function _l(e){let t=[];for(let r=1;r<e.overrides.length;r+=1){let n=e.overrides[r];for(let o of e.overrides.slice(0,r))n.commands?.length&&o.commands?.length&&!o.commands.some(i=>n.commands.includes(i))||t.push(`extension_preflight_override_collision:${n.layer}:${n.name}:${o.layer}:${o.name}`)}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]="47d10c23-88f8-5ba1-bcc2-458f339121a8")}catch{}})();var mo=Gt;function yl(e){let t=e.trim().toLowerCase();return mo.includes(t)?t:null}function hl(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let r=Math.max(1,Math.floor(t.length*.34));for(let n of mo)if(co(t,n,r)!==null)return n;return 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]="355fe619-e6f3-51d9-b88c-0b57267c25be")}catch{}})();function gl(e){return e==="toon"||e==="json"}function bl(e){return Vt.includes(e)}function bt(e,t){if(typeof t!="function")throw new TypeError(`api.hooks.${e} requires a function handler`)}var wl=Symbol("extension_registration_trace");function Pe(e,t){let r=new TypeError(e);return Object.defineProperty(r,wl,{value:t,enumerable:!1,configurable:!1,writable:!1}),r}function vl(e){return e instanceof Error?e[wl]:void 0}function Vr(e){if(e===null)return null;if(Array.isArray(e))return e.map(t=>Vr(t));if(typeof e=="function")return"[Function]";if(typeof e=="bigint"||typeof e=="symbol")return e.toString();if(typeof e=="object"){let t=e,r={};for(let n of Object.keys(t).sort((o,i)=>o.localeCompare(i)))r[n]=Vr(t[n]);return r}return e}function Br(e){if(Array.isArray(e))return e.map(t=>Br(t));if(typeof e=="object"&&e!==null){let t=e,r={};for(let n of Object.keys(t).sort((o,i)=>o.localeCompare(i)))r[n]=Br(t[n]);return r}return e}function Qt(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return Vr(t)}function Wr(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return Br(t)}function Gr(e,t){if(!Array.isArray(t))throw new TypeError(`${e} requires an array of object definitions`);return t.map(r=>Qt(e,r))}function ee(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function Kr(e,t){if(typeof t!="function")throw new TypeError(`${e} requires a function handler`)}function Ss(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Os(e,t){return F(`${e} ${t}`)}function Yr(e,t){return Object.defineProperty(e,"runtime_definition",{value:t,enumerable:!1,writable:!1,configurable:!1}),e}var Fg=new Set(["low","medium","high"]),zg=new Set(["number","string_set"]),Ug=new Set(["string","number","boolean"]);function El(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function Hg(e,t,r){let n=`registerAssuranceMeasurementProvider provider.keys.${t}`,o=G(n,r);if(!zg.has(String(o.value_type)))throw new TypeError(`${n}.value_type must be number or string_set`);if(q(`${n}.description`,o.description),o.parameters===void 0)return;let i=G(`${n}.parameters`,o.parameters);for(let[s,a]of Object.entries(i)){let c=`${n}.parameters.${s}`;El(`${c}.name`,s);let d=G(c,a);if(!Ug.has(String(d.type)))throw new TypeError(`${c}.type must be string, number, or boolean`);Z(`${c}.required`,d.required),q(`${c}.description`,d.description)}if(Object.keys(i).length>50)throw new TypeError(`assurance provider ${e} key ${t} exceeds 50 parameters`)}function kl(e){let t=G("registerAssuranceMeasurementProvider provider",e),r=El("registerAssuranceMeasurementProvider provider.id",t.id);if(!/^[a-z0-9][a-z0-9-]*$/u.test(r))throw new TypeError("registerAssuranceMeasurementProvider provider.id must be a stable lowercase id");if(!Fg.has(String(t.cost_class)))throw new TypeError("registerAssuranceMeasurementProvider provider.cost_class must be low, medium, or high");if(typeof t.network!="boolean")throw new TypeError("registerAssuranceMeasurementProvider provider.network must be boolean");let n=G("registerAssuranceMeasurementProvider provider.keys",t.keys);if(Object.keys(n).length===0)throw new TypeError("registerAssuranceMeasurementProvider provider.keys requires at least one key");for(let[o,i]of Object.entries(n)){if(!/^[a-z0-9][a-z0-9-]*$/u.test(o))throw new TypeError(`registerAssuranceMeasurementProvider provider key ${o} must be a stable lowercase id`);Hg(r,o,i)}if(t.timeout_ms!==void 0&&(typeof t.timeout_ms!="number"||!Number.isInteger(t.timeout_ms)||t.timeout_ms<1||t.timeout_ms>3e5))throw new TypeError("registerAssuranceMeasurementProvider provider.timeout_ms must be an integer from 1 through 300000");if(typeof t.resolve!="function")throw new TypeError("registerAssuranceMeasurementProvider provider.resolve requires a function handler")}(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]="4abca948-e9ba-52b5-b63c-a20fc344980a")}catch{}})();var qg=new Set(["default","description","enabled","list","long","repeatable","required","short","type","value_name","value_type","value_validation","visible"]);function po(e,t){return Gr(e,t).map(r=>(r.repeatable===!0&&(r.list=!0),r))}function Vg(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function As(e,t){if(t===void 0)return e.replace(/\s+/g,"-");if(typeof t!="string"||t.trim().length===0)throw new TypeError("registerCommand definition.action must be a non-empty string when provided");let r=Vg(t);if(r.length===0)throw new TypeError("registerCommand definition.action must contain alphanumeric characters");return r}function Is(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("registerCommand definition.arguments must be an array when provided");let t=[];for(let[n,o]of e.entries()){let i=G(`registerCommand definition.arguments[${n}]`,o),s=ee(`registerCommand definition.arguments[${n}].name`,i.name);if(Z(`registerCommand definition.arguments[${n}].required`,i.required),Z(`registerCommand definition.arguments[${n}].variadic`,i.variadic),q(`registerCommand definition.arguments[${n}].description`,i.description),s.includes(" "))throw new TypeError(`registerCommand definition.arguments[${n}].name must not contain spaces`);let a={name:s};i.required===!0&&(a.required=!0),i.variadic===!0&&(a.variadic=!0),typeof i.description=="string"&&(a.description=i.description.trim()),t.push(a)}let r=t.map((n,o)=>n.variadic?o:-1).filter(n=>n>=0);if(r.length>1)throw new TypeError("registerCommand definition.arguments supports at most one variadic argument");if(r.length===1&&r[0]!==t.length-1)throw new TypeError("registerCommand definition.arguments variadic argument must be the final argument");return t}function _o(e){if(!Array.isArray(e))throw new TypeError("registerFlags flags requires an array of object definitions");for(let[t,r]of e.entries()){let n=G(`registerFlags flags[${t}]`,r),o=Object.keys(n).filter(c=>!qg.has(c)).sort((c,d)=>c.localeCompare(d));if(o.length>0)throw new TypeError(`registerFlags flags[${t}] contains unknown field(s): ${o.join(", ")}`);let i=n.long,s=n.short;if(i===void 0&&s===void 0)throw new TypeError(`registerFlags flags[${t}] requires at least one of long or short`);q(`registerFlags flags[${t}].long`,i),q(`registerFlags flags[${t}].short`,s);let a=Md(i,s);if(a!==null)throw new TypeError(`registerFlags flags[${t}] ${$d(a.token,a.failure)}`);if(q(`registerFlags flags[${t}].value_name`,n.value_name),q(`registerFlags flags[${t}].description`,n.description),Z(`registerFlags flags[${t}].required`,n.required),Z(`registerFlags flags[${t}].enabled`,n.enabled),Z(`registerFlags flags[${t}].visible`,n.visible),Z(`registerFlags flags[${t}].list`,n.list),Z(`registerFlags flags[${t}].repeatable`,n.repeatable),n.list!==void 0&&n.repeatable!==void 0&&n.list!==n.repeatable)throw new TypeError(`registerFlags flags[${t}].list and repeatable must match when both are provided`);if(Kd(`registerFlags flags[${t}].default`,n.default),Array.isArray(n.default)&&n.list!==!0&&n.repeatable!==!0)throw new TypeError(`registerFlags flags[${t}].default cannot be an array unless list is true.`);Sl(`registerFlags flags[${t}]`,n),Bg(`registerFlags flags[${t}]`,n)}}function Bg(e,t){if(t.value_validation===void 0)return;if(t.value_validation!=="coerce"&&t.value_validation!=="strict")throw new TypeError(`${e}.value_validation must be "coerce" or "strict" (received ${JSON.stringify(t.value_validation)}).`);if(t.value_validation!=="strict")return;let r=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0),n=r===void 0?null:lo(r);if(n!=="number"&&n!=="boolean")throw new TypeError(`${e}.value_validation "strict" requires value_type "number" or "boolean" (string values are never malformed).`)}function Sl(e,t){let r=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0);if(r===void 0)return;let n=lo(r);if(n===null)throw new TypeError(`${e} value_type "${r}" is not a known flag value type (expected one of: string, number, boolean).`);if(t.default===void 0)return;let o=t.list===!0||t.repeatable===!0?Ld(t.default):[t.default];for(let[i,s]of o.entries())if(!Fd(s,n)){let a=o.length>1?`default[${i}]`:"default";throw new TypeError(`${e}.${a} (${JSON.stringify(s)}) is not coercible to ${n}.`)}}function Ol(e){if(!Array.isArray(e))throw new TypeError("registerItemFields fields requires an array of object definitions");for(let[t,r]of e.entries()){let n=G(`registerItemFields fields[${t}]`,r);ee(`registerItemFields fields[${t}].name`,n.name);let o=ee(`registerItemFields fields[${t}].type`,n.type);if(yl(o)===null){let i=hl(o),s=i?` Did you mean "${i}"?`:"";throw new TypeError(`registerItemFields fields[${t}].type "${o}" is not a known field type (expected one of: ${mo.join(", ")}).${s}`)}Z(`registerItemFields fields[${t}].optional`,n.optional)}}function Wg(e,t){if(t===void 0)return;let r=`registerItemTypes types[${e}].command_option_policies`;if(!Array.isArray(t))throw new TypeError(`${r} must be an array when provided`);for(let[n,o]of t.entries()){let i=`${r}[${n}]`,s=G(i,o);ee(`${i}.command`,s.command),ee(`${i}.option`,s.option),Z(`${i}.enabled`,s.enabled),Z(`${i}.required`,s.required),Z(`${i}.visible`,s.visible)}}function Gg(e,t){if(t===void 0)return;let r=`registerItemTypes types[${e}].options`;if(!Array.isArray(t))throw new TypeError(`${r} must be an array when provided`);for(let[n,o]of t.entries()){let i=`${r}[${n}]`,s=G(i,o);ee(`${i}.key`,s.key),ht(`${i}.values`,s.values),Z(`${i}.required`,s.required),ht(`${i}.aliases`,s.aliases)}}function Al(e){if(!Array.isArray(e))throw new TypeError("registerItemTypes types requires an array of object definitions");for(let[t,r]of e.entries()){let n=`registerItemTypes types[${t}]`,o=G(n,r);ee(`${n}.name`,o.name),q(`${n}.folder`,o.folder),ht(`${n}.aliases`,o.aliases),ht(`${n}.required_create_fields`,o.required_create_fields),ht(`${n}.required_create_repeatables`,o.required_create_repeatables),Wg(t,o.command_option_policies),Gg(t,o.options)}}function Il(e){let t=G("registerMigration definition",e);if(t.id!==void 0&&typeof t.id!="string")throw new TypeError("registerMigration definition.id must be a string when provided");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("registerMigration definition.description must be a string when provided");if(t.status!==void 0&&typeof t.status!="string")throw new TypeError("registerMigration definition.status must be a string when provided");if(Z("registerMigration definition.mandatory",t.mandatory),t.run!==void 0&&typeof t.run!="function")throw new TypeError("registerMigration definition.run must be a function when provided")}var Tl=["types","statuses","fields","workflows","config","templates","packages"],Kg={types:(e,t)=>{if(t.name!==void 0&&typeof t.name!="string")throw new TypeError(`${e}.name must be a string when provided`)},workflows:(e,t)=>{if(typeof t.type!="string")throw new TypeError(`${e}.type must be a string`);if(!Array.isArray(t.allowed_transitions))throw new TypeError(`${e}.allowed_transitions must be an array`);for(let[r,n]of t.allowed_transitions.entries())if(!Array.isArray(n))throw new TypeError(`${e}.allowed_transitions[${r}] must be a [from, to] array`)},templates:(e,t)=>{if(typeof t.name!="string")throw new TypeError(`${e}.name must be a string`);if(typeof t.options!="object"||t.options===null||Array.isArray(t.options))throw new TypeError(`${e}.options must be an object`)},packages:(e,t)=>{if(typeof t.spec!="string")throw new TypeError(`${e}.spec must be a string`)}};function Cl(e){let t=G("registerProfile profile",e);if(ee("registerProfile profile.name",t.name),ee("registerProfile profile.title",t.title),t.summary!==void 0&&typeof t.summary!="string")throw new TypeError("registerProfile profile.summary must be a string when provided");for(let r of Tl){let n=t[r];if(n!==void 0){if(!Array.isArray(n))throw new TypeError(`registerProfile profile.${r} must be an array when provided`);for(let[o,i]of n.entries()){if(typeof i!="object"||i===null||Array.isArray(i))throw new TypeError(`registerProfile profile.${r}[${o}] must be an object`);Kg[r]?.(`registerProfile profile.${r}[${o}]`,i)}}}}function Rl(e){e.summary===void 0&&(e.summary="");for(let t of Tl)e[t]===void 0&&(e[t]=[]);return 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]="45ff820c-32af-5bdb-a570-3059684129ce")}catch{}})();function xl(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("registerService ownership must be an object");if(Reflect.ownKeys(e).some(t=>t!=="passThrough"))throw new TypeError("registerService ownership supports only passThrough");if(e.passThrough!==void 0&&typeof e.passThrough!="boolean")throw new TypeError("registerService ownership.passThrough must be a boolean when provided");return e.passThrough===!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]="b5de5028-f981-599b-8d11-0fc7b07beda4")}catch{}})();function Nl(e){return typeof e=="string"?e:String(e)}function Xr(e){let t=e.trim().replace(/^>=\s*/,"").replace(/^v/i,"").split(/[+-]/,1)[0];return/^\d+(?:[.-]\d+)*$/.test(t)?t.split(/[.-]/).map(r=>Number(r)):null}function Ts(e,t){let r=Xr(e),n=Xr(t);if(!r||!n)return null;let o=Math.max(r.length,n.length);for(let i=0;i<o;i+=1){let s=r[i]??0,a=n[i]??0;if(s>a)return 1;if(s<a)return-1}return 0}function Dl(e,t){if(e==null)return{kind:"pm_min_version",status:"absent",allowed:!0,required:"",current:t};let r=Nl(e);if(typeof e!="string"||r.trim().length===0)return{kind:"pm_min_version",status:"invalid",allowed:!1,required:r,current:t};if(!Xr(r))return{kind:"pm_min_version",status:"invalid",allowed:!1,required:r,current:t};if(t===null)return{kind:"pm_min_version",status:"unchecked",allowed:!0,required:r,current:null};let n=Ts(t,r);return n===null?{kind:"pm_min_version",status:"unchecked",allowed:!0,required:r,current:t}:n<0?{kind:"pm_min_version",status:"unmet",allowed:!1,required:r,current:t}:{kind:"pm_min_version",status:"ok",allowed:!0,required:r,current:t}}function Pl(e,t,r){if(e==null)return{kind:"pm_max_version",status:"absent",allowed:!0,required:"",current:t};let n=Nl(e);if(typeof e!="string"||n.trim().length===0)return{kind:"pm_max_version",status:"invalid",allowed:!1,required:n,current:t};if(/^[<>=~^]/.test(n.trim())||!Xr(n))return{kind:"pm_max_version",status:"invalid",allowed:!1,required:n,current:t};if(t===null)return{kind:"pm_max_version",status:"unchecked",allowed:!0,required:n,current:null};let o=Ts(t,n);return o===null?{kind:"pm_max_version",status:"unchecked",allowed:!0,required:n,current:t}:o>0?r==="warn"?{kind:"pm_max_version",status:"exceeded_warn",allowed:!0,required:n,current:t}:{kind:"pm_max_version",status:"exceeded",allowed:!1,required:n,current:t}:{kind:"pm_max_version",status:"ok",allowed:!0,required:n,current: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]="187f03b7-1a62-500c-9ebf-4d5a053afa74")}catch{}})();var Ml=null,Xg=Object.freeze(Gc()),$l=0;function Jg(e=Date.now()){return $l+=1,`${$l}-${e}`}function Zg(e,t,r){return r.has(e)?!1:t.size===0?!0:t.has(e)}async function Qg(e,t){let[r,n]=await Promise.all([vt.realpath(e),vt.realpath(t)]);return hs(r,n)}function eb(e,t=process.cwd()){return{global:wt.join(bd(t),"extensions"),project:wt.join(e,"extensions")}}async function tb(e){try{return(await vt.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,r)=>t.localeCompare(r))}catch{return[]}}function rb(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.manifest.name,version:e.manifest.version,entry:e.manifest.entry,priority:e.manifest.priority,entry_path:e.entry_path,manifest_version:e.manifest.manifest_version,pm_min_version:e.manifest.pm_min_version,pm_max_version:e.manifest.pm_max_version,engines:e.manifest.engines,trusted:e.manifest.trusted,provenance:e.manifest.provenance,sandbox_profile:e.manifest.sandbox_profile,permissions:e.manifest.permissions,capabilities:[...e.manifest.capabilities],activation:e.manifest.activation?{commands:[...e.manifest.activation.commands]}:void 0,contributions:e.manifest.contributions??e.contributions};return e.source_package&&(t.source_package=e.source_package),e.source_aliases&&(t.source_aliases=[...e.source_aliases]),t}function jl(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}async function nb(e){let t=new Map;try{let r=JSON.parse(await vt.readFile(wt.join(e,".managed-extensions.json"),"utf8")),n=ze(r)?.entries;if(!Array.isArray(n))return t;for(let o of n){if(typeof o!="object"||o===null)continue;let i=o,s=jl(i.source?.package),a=[i.source?.input,i.source?.name,s].map(l=>jl(l)).filter(l=>l!==void 0),c=ao(i.contributions),d={aliases:[...new Set(a)],...s?{package_name:s}:{},...c?{contributions:c}:{}};typeof i.directory=="string"&&i.directory.trim().length>0&&t.set(`directory:${i.directory.trim()}`,d),typeof i.name=="string"&&i.name.trim().length>0&&t.set(`name:${i.name.trim()}`,d)}}catch{return t}return t}function Ll(e){return[...e].sort((t,r)=>{if(t.manifest.priority!==r.manifest.priority)return t.manifest.priority-r.manifest.priority;let n=t.manifest.name.localeCompare(r.manifest.name);return n!==0?n:t.directory.localeCompare(r.directory)})}function ob(e,t){let r=[...Ll(e),...Ll(t)],n=[];for(let o of r){let i=n.findIndex(s=>s.manifest.name===o.manifest.name);i>=0&&n.splice(i,1),n.push(o)}return n}async function Fl(e,t,r,n,o){let i=[],s=[],a=[],c=await tb(t),d=await nb(t);for(let l of c){let u=await ab(e,t,l,r,n,d,o);i.push(u.diagnostic),s.push(...u.warnings),u.candidate&&a.push(u.candidate)}return{diagnostics:i,warnings:s,candidates:a}}function ib(){return{diagnostics:[],warnings:[],candidates:[]}}function zl(e,t,r,n){return{diagnostic:{layer:e,directory:t,manifest_path:r,name:null,version:null,entry:null,priority:null,entry_path:null,enabled:null,status:"warn"},warnings:[n],candidate:null}}function sb(e,t,r,n,o,i,s){let a=xd(e,t,r);Array.isArray(t.legacy_capability_aliases)&&t.legacy_capability_aliases.length>0&&a.push(Rd(e,t.name,t.legacy_capability_aliases));for(let c of Id(t.capabilities))a.push(Cd(e,t.name,c));return n?o||a.push(`extension_entry_missing:${e}:${t.name}`):a.push(`extension_entry_outside_extension:${e}:${t.name}`),i.warning&&a.push(i.warning),s.warning&&a.push(s.warning),a}async function ab(e,t,r,n,o,i,s){let a=wt.join(t,r),c=wt.join(a,"manifest.json");if(!await mt(c))return zl(e,r,c,`extension_manifest_missing:${e}:${r}`);let d,l;try{let ke=JSON.parse(await vt.readFile(c,"utf8"));l=ze(ke),d=ks(ke)}catch{l=null,d=null}if(!d||!l)return zl(e,r,c,`extension_manifest_invalid:${e}:${r}`);let u=wt.resolve(a,d.entry),f=hs(a,u),m=f?await mt(u):!1,_=f&&m?await Qg(a,u):f,y=Zg(d.name,n,o),w=await lb(e,d),v=await ub(e,d,s),C=sb(e,d,l,_,m,w,v),K=_&&m&&w.allowed&&v.allowed,Ee=i.get(`directory:${r}`)??i.get(`name:${d.name}`);return{diagnostic:{layer:e,directory:r,manifest_path:c,name:d.name,version:d.version,entry:d.entry,priority:d.priority,entry_path:u,enabled:y,status:K?"ok":"warn"},warnings:C,candidate:Zd({layer:e,directory:r,manifestPath:c,entryPath:u,manifest:d,sourceIdentity:Ee,extensionReady:K,enabledForLoad:y})}}async function cb(e){let t=eb(e.pmRoot,e.cwd??process.cwd()),r=Lr(e.settings.extensions.enabled),n=Lr(e.settings.extensions.disabled),o=nl(e.settings),i=ol(o);if(e.noExtensions)return{disabled_by_flag:!0,roots:t,configured_enabled:r,configured_disabled:n,discovered:[],effective:[],warnings:[...o.warnings],policy:i};let s=new Set(r),a=new Set(n),c=e.ignoreGlobalExtensions===!0?ib():await Fl("global",t.global,s,a,o.pmMaxVersionExceededMode.global),d=await Fl("project",t.project,s,a,o.pmMaxVersionExceededMode.project),l=[...o.warnings],u=ob(c.candidates,d.candidates),f=[];for(let m of u){let _={layer:m.layer,name:m.manifest.name,trusted:m.manifest.trusted===!0,provenanceVerified:m.manifest.provenance?.verified===!0,sandboxProfile:m.manifest.sandbox_profile,permissions:m.manifest.permissions&&typeof m.manifest.permissions=="object"?{fs_read:m.manifest.permissions.fs_read,fs_write:m.manifest.permissions.fs_write,network:m.manifest.permissions.network,env_read:m.manifest.permissions.env_read,env_write:m.manifest.permissions.env_write,process_spawn:m.manifest.permissions.process_spawn}:void 0},y=al(o,_);if(y.warning&&l.push(y.warning),!!y.allowed){for(let w of m.manifest.capabilities){let v=cl(o,_,w);v.warning&&l.push(v.warning)}f.push(rb(m))}}return{disabled_by_flag:!1,roots:t,configured_enabled:r,configured_disabled:n,discovered:[...c.diagnostics,...d.diagnostics],effective:f,warnings:[...new Set([...c.warnings,...d.warnings,...l])],policy:i}}function yo(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}async function db(){try{let e=Bn(import.meta.url,["../../.."]),t=await vt.readFile(wt.join(e,"package.json"),"utf8"),r=JSON.parse(t);return typeof r.version=="string"&&r.version.trim().length>0?r.version.trim():null}catch{return null}}function ql(){return Ml??=db(),Ml}function Vl(e,t,r){let n=r.current??"unknown";if(r.kind==="pm_min_version")switch(r.status){case"invalid":return`extension_pm_min_version_invalid:${e}:${t.name}:required=${r.required}`;case"unchecked":return`extension_pm_min_version_unchecked:${e}:${t.name}:required=${r.required}:current=${n}`;case"unmet":return`extension_pm_min_version_unmet:${e}:${t.name}:required=${r.required}:current=${n}`;default:return}switch(r.status){case"invalid":return`extension_pm_max_version_invalid:${e}:${t.name}:allowed=${r.required}`;case"unchecked":return`extension_pm_max_version_unchecked:${e}:${t.name}:allowed=${r.required}:current=${n}`;case"exceeded_warn":return`extension_pm_max_version_exceeded_warn:${e}:${t.name}:allowed=${r.required}:current=${n}`;case"exceeded":return`extension_pm_max_version_exceeded:${e}:${t.name}:allowed=${r.required}:current=${n}`;default:return}}async function lb(e,t){if(t.pm_min_version===void 0)return{allowed:!0};let r=Dl(t.pm_min_version,await ql()),n=Vl(e,t,r);return n?{allowed:r.allowed,warning:n}:{allowed:r.allowed}}async function ub(e,t,r){if(t.pm_max_version===void 0)return{allowed:!0};let n=Pl(t.pm_max_version,await ql(),r),o=Vl(e,t,n);return o?{allowed:n.allowed,warning:o}:{allowed:n.allowed}}async function Ul(e){try{let t=await vt.stat(e);return`${Math.trunc(t.mtimeMs)}-${t.size}`}catch{return"missing"}}async function fb(e,t){let r=e.entry_path;t.module_graph_snapshot_root&&(r=await ml(t.module_graph_snapshot_root,e));let n=new URL(Yg(r).href);if(!(t.cache_bust===!0||typeof t.reload_token=="string"))return n.href;let[o,i]=await Promise.all([Ul(e.entry_path),Ul(e.manifest_path)]),s=t.reload_token??Jg();return n.searchParams.set("pm_ext_reload",s),n.searchParams.set("pm_ext_entry",o),n.searchParams.set("pm_ext_manifest",i),n.href}async function Lx(e){let t=await cb(e),r=[],n=[],o=[...t.warnings];if(t.disabled_by_flag)return{...t,warnings:o,loaded:r,failed:n};let i=typeof e.extensionFilter=="function"?t.effective.filter(e.extensionFilter):t.effective;for(let s of i)try{let a=await import(await fb(s,e));r.push({...s,module:a})}catch(a){o.push(`extension_load_failed:${s.layer}:${s.name}`),n.push({layer:s.layer,name:s.name,entry_path:s.entry_path,error:yo(a)})}return{...t,warnings:o,loaded:r,failed:n}}var Hl=5e3,mb=2147483647;function pb(e){let t={activate:e.activate.bind(e)};if(typeof e.deactivate=="function"){let r=e.deactivate;t.deactivate=r.bind(e)}return t}function Bl(e){let t=nd(e);return t?pb(t):null}async function Fx(e,t,r={}){let n=_b(r?.deactivate_timeout_ms),o=new Set((t?.failed??[]).map(l=>`${l.layer}:${l.name}`)),i=[];for(let l of e.loaded){if(o.has(`${l.layer}:${l.name}`))continue;let u=Bl(l.module);!u||typeof u.deactivate!="function"||i.push({extension:l,deactivate:u.deactivate})}let s=await Promise.all(i.map(async({extension:l,deactivate:u})=>{try{return await yb(u,n),{ok:!0}}catch(f){return{ok:!1,layer:l.layer,name:l.name,error:yo(f)}}})),a=[],c=[],d=0;for(let l of s){if(l.ok){d+=1;continue}a.push(`extension_deactivate_failed:${l.layer}:${l.name}`),c.push({layer:l.layer,name:l.name,error:l.error})}return{deactivated:d,warnings:a,failed:c}}function _b(e){return typeof e!="number"||e<0?Hl:e===0||e===1/0?0:Number.isFinite(e)?Math.min(mb,Math.max(1,Math.floor(e))):Hl}async function yb(e,t){if(t===0){await e();return}let r;try{let n=Promise.resolve().then(()=>e());n.catch(()=>{}),await Promise.race([n,new Promise((o,i)=>{r=setTimeout(()=>{i(new Error(`extension deactivate timed out after ${t}ms`))},t),r.unref?.()})])}finally{clearTimeout(r)}}function hb(e){if(!Array.isArray(e.capabilities))return null;let t=new Set;for(let r of e.capabilities){let n=r.trim().toLowerCase();He(n)&&t.add(n)}return t}function z(e,t,r){let n=hb(e);if(n!==null&&!n.has(t))throw Pe(`${r} requires capability '${t}' in extension manifest capabilities`,{method:r,registration_index:-1,capability:t,missing_capability:t,expected_schema:`"capabilities": [..., "${t}"]`,received:e.capabilities,hint:`Add "${t}" to ${e.name} manifest capabilities, or remove the ${r} registration call.`})}function gb(e){return Object.freeze({name:e.name,layer:e.layer,version:e.version,capabilities:Object.freeze((e.capabilities??[]).filter(t=>xe.includes(t))),pm_min_version:e.pm_min_version,pm_max_version:e.pm_max_version,source_package:e.source_package})}function bb(e){return{layer:e.layer,name:e.name,trusted:e.trusted===!0,provenanceVerified:e.provenance?.verified===!0,sandboxProfile:e.sandbox_profile,permissions:e.permissions&&typeof e.permissions=="object"?{fs_read:e.permissions.fs_read,fs_write:e.permissions.fs_write,network:e.permissions.network,env_read:e.permissions.env_read,env_write:e.permissions.env_write,process_spawn:e.permissions.process_spawn}:void 0}}var Cs=class{extension;hooks;#e;#r;#o;#n;#s;#a;#i;#c;#t;#d;#l;#u;constructor(t,r,n,o,i,s,a,c,d,l,u){this.#e=t,this.extension=gb(t),this.#r=bb(t),this.#o=r,this.#n=n,this.#s=o,this.#a=i,this.#i=s,this.#c=a,this.#t=c,this.#d=d,this.#l=l,this.#u=u,this.registerCommand=this.registerCommand.bind(this),this.registerParser=this.registerParser.bind(this),this.registerPreflight=this.registerPreflight.bind(this),this.registerService=this.registerService.bind(this),this.registerFlags=this.registerFlags.bind(this),this.registerItemFields=this.registerItemFields.bind(this),this.registerItemTypes=this.registerItemTypes.bind(this),this.registerRelationshipKinds=this.registerRelationshipKinds.bind(this),this.registerMigration=this.registerMigration.bind(this),this.registerProfile=this.registerProfile.bind(this),this.registerRenderer=this.registerRenderer.bind(this),this.registerImporter=this.registerImporter.bind(this),this.registerExporter=this.registerExporter.bind(this),this.registerSearchProvider=this.registerSearchProvider.bind(this),this.registerVectorStoreAdapter=this.registerVectorStoreAdapter.bind(this),this.registerAssuranceMeasurementProvider=this.registerAssuranceMeasurementProvider.bind(this),this.hooks={beforeCommand:f=>this.registerBeforeCommand(f),beforeMutation:f=>this.registerBeforeMutation(f),afterCommand:f=>this.registerAfterCommand(f),onWrite:f=>this.registerOnWrite(f),onRead:f=>this.registerOnRead(f),onIndex:f=>this.registerOnIndex(f)}}allowRegistration(t,r,n,o){let i=dl(this.#u,this.#r,t,r,n,o);return i.warning&&this.#d.push(i.warning),i.allowed}registerCommandTrace(t,r,n,o,i){return{method:"registerCommand",registration_index:t==="override"?this.#n.overrides.length:this.#n.handlers.length,command:r,expected_schema:n,received:Vr(o),hint:i}}registerCommandOverride(t,r){let n=F(t);if(n.length===0)throw Pe("registerCommand requires a non-empty command name",this.registerCommandTrace("override",t,'registerCommand("<command>", (context) => unknown)',t,"Provide a non-empty command path as the first argument."));if(typeof r!="function"){let o=this.registerCommandTrace("override",n,'registerCommand("<command>", (context) => unknown)',r,"Provide a function as the second registerCommand argument.");throw Pe(`registerCommand requires an override function when command name is provided (command="${n}", registration_index=${o.registration_index})`,o)}this.allowRegistration("commands.override","registerCommand","commands",{command:n})&&this.#n.overrides.push({layer:this.#e.layer,name:this.#e.name,command:n,run:r})}resolveCommandDefinitionRunHandler(t,r){let n=typeof t.run=="function"?t.run:void 0,o=typeof t.handler=="function"?t.handler:void 0;return!n&&o&&this.#d.push(`extension_command_definition_legacy_handler_alias:${this.#e.layer}:${this.#e.name}:${r}`),n??o}registerCommandDefinition(t){if(typeof t!="object"||t===null)throw Pe("registerCommand requires a command definition object",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,'Use registerCommand({ name: "command path", run: (context) => ... }).'));if(typeof t.name!="string")throw Pe("registerCommand requires a command definition name",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,"Set command definition.name to a non-empty string command path."));let r=F(t.name);if(r.length===0)throw Pe("registerCommand requires a non-empty command definition name",this.registerCommandTrace("definition",t.name,"{ name: string; run: (context) => unknown; }",t,"Ensure command definition.name contains a non-empty command path."));let n=this.resolveCommandDefinitionRunHandler(t,r);if(typeof n!="function"){let o=this.registerCommandTrace("definition",r,"{ name: string; run: (context) => unknown; }",n,"Define command definition.run as a function.");throw Pe(`registerCommand requires a command definition run handler (command="${r}", registration_index=${o.registration_index})`,o)}try{Yd(t);let o=As(r,t.action),i=Xd(t.read_output,r,o);if(!this.allowRegistration("commands.handler","registerCommand","commands",{command:r,action:o}))return;let s=t.description?.trim(),a=t.intent?.trim(),c=Ur("registerCommand definition.examples",t.examples),d=Ur("registerCommand definition.failure_hints",t.failure_hints),l=Is(t.arguments);t.flags!==void 0&&(z(this.#e,"schema","registerCommand flags"),this.allowRegistration("schema.flags","registerCommand flags","schema")&&(_o(t.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:r,flags:po("registerCommand definition.flags",t.flags)})));let u={read_output:i,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:r,action:o,examples:c,failure_hints:d,arguments:l,tier:t.tier??"standard",family:t.family??"extensions"};s&&(u.description=s),a&&(u.intent=a),this.#t.commands.push(u)}catch(o){let i=yo(o),s=this.registerCommandTrace("definition",r,"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }",t,i),a=Pe(`registerCommand definition metadata invalid (command="${r}", registration_index=${s.registration_index}): ${i}`,s);this.#d.push(`extension_command_quarantined:${this.#e.layer}:${this.#e.name}:${r}`),this.#l.push({layer:this.#e.layer,name:this.#e.name,entry_path:this.#e.entry_path,error:a.message,trace:s});return}this.#n.handlers.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}registerCommand(t,r){if(z(this.#e,"commands","registerCommand"),typeof t=="string"){this.registerCommandOverride(t,r);return}this.registerCommandDefinition(t)}registerParser(t,r){if(z(this.#e,"parser","registerParser"),!this.allowRegistration("parser.override","registerParser","parser"))return;let n=F(ee("registerParser command",t));Kr("registerParser override",r),this.#s.overrides.push({layer:this.#e.layer,name:this.#e.name,command:n,run:r})}registerPreflight(t){if(z(this.#e,"preflight","registerPreflight"),!this.allowRegistration("preflight.override","registerPreflight","preflight"))return;let r=pl(t);this.#a.overrides.push({layer:this.#e.layer,name:this.#e.name,...r})}registerService(t,r,n={}){z(this.#e,"services","registerService");let o=String(t).trim().toLowerCase();if(!bl(o))throw new TypeError(`registerService service must be one of: ${Vt.join(", ")}`);this.allowRegistration("services.override","registerService","services",{service:o})&&(Kr("registerService override",r),this.#i.overrides.push({layer:this.#e.layer,name:this.#e.name,service:o,run:r,...xl(n)?{passThrough:!0}:{}}))}registerRenderer(t,r,n={}){if(z(this.#e,"renderers","registerRenderer"),!this.allowRegistration("renderers.override","registerRenderer","renderers"))return;if(typeof r!="function")throw new TypeError("registerRenderer requires a renderer function");let o=String(t).trim().toLowerCase();if(!gl(o))throw new Error(`registerRenderer format must be toon|json, received: ${String(t)}`);if(n.resultDiscriminator!==void 0&&typeof n.resultDiscriminator!="function")throw new TypeError("registerRenderer ownership.resultDiscriminator must be a function when provided");let i=[...new Set((n.commands??[]).map(s=>{if(typeof s!="string"||s.trim().length===0)throw new TypeError("registerRenderer ownership.commands must contain non-empty command paths");return F(s)}))];this.#c.overrides.push({layer:this.#e.layer,name:this.#e.name,format:o,run:r,commands:i,...n.resultDiscriminator?{resultDiscriminator:n.resultDiscriminator}:{}})}registerFlags(t,r){if(z(this.#e,"schema","registerFlags"),!this.allowRegistration("schema.flags","registerFlags","schema"))return;let n=F(ee("registerFlags targetCommand",t));_o(r);let o=po("registerFlags flags",r);if(o.length===0)throw new TypeError("registerFlags requires at least one flag definition");this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:o})}registerItemFields(t){if(z(this.#e,"schema","registerItemFields"),!this.allowRegistration("schema.itemfields","registerItemFields","schema"))return;Ol(t);let r=Gr("registerItemFields fields",t);if(r.length===0)throw new TypeError("registerItemFields requires at least one field definition");this.#t.item_fields.push({layer:this.#e.layer,name:this.#e.name,fields:r})}registerItemTypes(t){if(z(this.#e,"schema","registerItemTypes"),!this.allowRegistration("schema.itemtypes","registerItemTypes","schema"))return;Al(t);let r=Gr("registerItemTypes types",t);if(r.length===0)throw new TypeError("registerItemTypes requires at least one type definition");this.#t.item_types.push({layer:this.#e.layer,name:this.#e.name,types:r})}registerRelationshipKinds(t){if(z(this.#e,"schema","registerRelationshipKinds"),!this.allowRegistration("schema.relationshipkinds","registerRelationshipKinds","schema"))return;if(!Array.isArray(t))throw new TypeError("registerRelationshipKinds definitions requires an array of object definitions");if(t.length===0)throw new TypeError("registerRelationshipKinds requires at least one definition");let r=Ui();for(let o of this.#t.relationship_kinds)for(let i of o.definitions)r.register(i);let n=t.map(o=>(r.register(o),r.require(o.kind)));this.#t.relationship_kinds.push({layer:this.#e.layer,name:this.#e.name,definitions:n})}registerMigration(t){if(z(this.#e,"schema","registerMigration"),!this.allowRegistration("schema.migrations","registerMigration","schema"))return;Il(t);let r=Wr("registerMigration definition",t);this.#t.migrations.push(Yr({layer:this.#e.layer,name:this.#e.name,definition:Qt("registerMigration definition",t)},r))}registerProfile(t){if(z(this.#e,"schema","registerProfile"),!this.allowRegistration("schema.profiles","registerProfile","schema"))return;let r=Br(t);Cl(r),this.#t.profiles.push({layer:this.#e.layer,name:this.#e.name,profile:Rl(r)})}registerImportExportCommandFlags(t,r,n){n.flags!==void 0&&(z(this.#e,"schema",`${t} options.flags`),this.allowRegistration("schema.flags",`${t} options.flags`,"schema")&&(_o(n.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:r,flags:po(`${t} options.flags`,n.flags)})))}applyImportExportCommandMetadata(t,r,n){if(n!==void 0&&(typeof n!="object"||n===null||Array.isArray(n)))throw new TypeError(`${t} options must be an object when provided`);let o=`${t==="registerImporter"?"Import":"Export"} items with the registered extension adapter.`,i=[{name:"file",required:!1,description:"Optional input or output file path."}],s={...n,description:n?.description??o,arguments:n?.arguments??i},a=Jd(t,s,n?.description!==void 0);q(`${t} options.action`,s.action),q(`${t} options.description`,s.description),q(`${t} options.intent`,s.intent);let c=As(r,s.action),d=Ur(`${t} options.examples`,s.examples),l=Ur(`${t} options.failure_hints`,s.failure_hints),u=Is(s.arguments);this.registerImportExportCommandFlags(t,r,s);let f={layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:r,action:c,examples:d,failure_hints:l,arguments:u},m=s.description?.trim();m&&(f.description=m);let _=s.intent?.trim();return _&&(f.intent=_),this.#t.commands.push(f),a}registerImporter(t,r,n){if(z(this.#e,"importers","registerImporter"),!this.allowRegistration("importers.importer","registerImporter","importers"))return;let o=Ss(ee("registerImporter name",t));Kr("registerImporter importer",r);let i=Os(o,"import");this.applyImportExportCommandMetadata("registerImporter",i,n),this.#t.importers.push({layer:this.#e.layer,name:this.#e.name,importer:o}),this.#n.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async s=>r(bs(s,o,"import"))})}registerExporter(t,r,n){if(z(this.#e,"importers","registerExporter"),!this.allowRegistration("importers.exporter","registerExporter","importers"))return;let o=Ss(ee("registerExporter name",t));Kr("registerExporter exporter",r);let i=Os(o,"export"),s=this.applyImportExportCommandMetadata("registerExporter",i,n);this.#t.exporters.push({layer:this.#e.layer,name:this.#e.name,exporter:o,...s===void 0?{}:{output:s}}),this.#n.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async a=>{let c=await r(bs(a,o,"export"));return s?.receipt==="suppress"&&!Vn(c)?ed(c):c}})}registerSearchProvider(t){if(z(this.#e,"search","registerSearchProvider"),!this.allowRegistration("search.provider","registerSearchProvider","search"))return;let r=Wr("registerSearchProvider provider",t);this.#t.search_providers.push(Yr({layer:this.#e.layer,name:this.#e.name,definition:Qt("registerSearchProvider provider",t)},r))}registerVectorStoreAdapter(t){if(z(this.#e,"search","registerVectorStoreAdapter"),!this.allowRegistration("search.vectorstore","registerVectorStoreAdapter","search"))return;let r=Wr("registerVectorStoreAdapter adapter",t);this.#t.vector_store_adapters.push(Yr({layer:this.#e.layer,name:this.#e.name,definition:Qt("registerVectorStoreAdapter adapter",t)},r))}registerAssuranceMeasurementProvider(t){if(z(this.#e,"services","registerAssuranceMeasurementProvider"),!this.allowRegistration("services.assuranceprovider","registerAssuranceMeasurementProvider","services"))return;if(kl(t),t.network&&this.#e.permissions?.network!==!0)throw new TypeError("registerAssuranceMeasurementProvider network provider requires permissions.network=true");let r=Wr("registerAssuranceMeasurementProvider provider",t);this.#t.assurance_providers.push(Yr({layer:this.#e.layer,name:this.#e.name,network_permission:this.#e.permissions?.network===!0,definition:Qt("registerAssuranceMeasurementProvider provider",t)},r))}registerBeforeCommand(t){z(this.#e,"hooks","api.hooks.beforeCommand"),this.allowRegistration("hooks.beforecommand","api.hooks.beforeCommand","hooks")&&(bt("beforeCommand",t),this.#o.beforeCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerBeforeMutation(t){z(this.#e,"hooks","api.hooks.beforeMutation"),this.allowRegistration("hooks.beforemutation","api.hooks.beforeMutation","hooks")&&(bt("beforeMutation",t),this.#o.beforeMutation.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerAfterCommand(t){z(this.#e,"hooks","api.hooks.afterCommand"),this.allowRegistration("hooks.aftercommand","api.hooks.afterCommand","hooks")&&(bt("afterCommand",t),this.#o.afterCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnWrite(t){z(this.#e,"hooks","api.hooks.onWrite"),this.allowRegistration("hooks.onwrite","api.hooks.onWrite","hooks")&&(bt("onWrite",t),this.#o.onWrite.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnRead(t){z(this.#e,"hooks","api.hooks.onRead"),this.allowRegistration("hooks.onread","api.hooks.onRead","hooks")&&(bt("onRead",t),this.#o.onRead.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnIndex(t){z(this.#e,"hooks","api.hooks.onIndex"),this.allowRegistration("hooks.onindex","api.hooks.onIndex","hooks")&&(bt("onIndex",t),this.#o.onIndex.push({layer:this.#e.layer,name:this.#e.name,run:t}))}};function wb(e,t,r,n,o,i,s,a,c,d,l){return new Cs(e,t,r,n,o,i,s,a,c,d,l)}function vb(e){let t=e.commands.length,r=e.flags.reduce((s,a)=>s+a.flags.length,0),n=e.item_fields.reduce((s,a)=>s+a.fields.length,0),o=e.item_types.reduce((s,a)=>s+a.types.length,0),i=(e.relationship_kinds??[]).reduce((s,a)=>s+a.definitions.length,0);return{commands:t,flags:r,item_fields:n,item_types:o,...i>0?{relationship_kinds:i}:{},migrations:e.migrations.length,profiles:e.profiles.length,importers:e.importers.length,exporters:e.exporters.length,search_providers:e.search_providers.length,vector_store_adapters:e.vector_store_adapters.length,...(e.assurance_providers?.length??0)>0?{assurance_providers:e.assurance_providers.length}:{}}}function Eb(e){let t=[],r=(i,s)=>{let a=new Map;for(let c of i){let d=a.get(c.command)??[];d.push(c),a.set(c.command,d)}for(let c of[...a.keys()].sort((d,l)=>d.localeCompare(l))){let d=a.get(c);if(d.length<=1)continue;let l=d[d.length-1];for(let u of d.slice(0,-1))t.push(`${s}:${c}:${l.layer}:${l.name}:${u.layer}:${u.name}`)}};r(e.handlers,"extension_command_handler_collision"),r(e.overrides,"extension_command_override_collision");let n=new Set(e.handlers.map(i=>i.command)),o=[...new Set(e.overrides.map(i=>i.command))].filter(i=>n.has(i));o.sort((i,s)=>i.localeCompare(s));for(let i of o){let s=e.handlers.filter(c=>c.command===i),a=e.overrides.filter(c=>c.command===i);for(let c of a)for(let d of s)t.push(`extension_command_override_handler_overlap:${i}:${c.layer}:${c.name}:${d.layer}:${d.name}`)}return t}function kb(e){let t=new Map;for(let n of e.overrides){let o=t.get(n.format)??[];o.push(n),t.set(n.format,o)}let r=[];for(let n of[...t.keys()].sort((o,i)=>o.localeCompare(i))){let o=t.get(n);if(o.length<=1)continue;let i=o[o.length-1];for(let s of o.slice(0,-1))i.commands?.length&&s.commands?.length&&!s.commands.some(a=>i.commands?.includes(a))||r.push(`extension_renderer_collision:${n}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return r}function Sb(e){let t=[],r=new Map;for(let n of e.overrides){let o=r.get(n.command)??[];o.push(n),r.set(n.command,o)}for(let n of[...r.keys()].sort((o,i)=>o.localeCompare(i))){let o=r.get(n);if(o.length<=1)continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_parser_override_collision:${n}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}var Ob=new Set(["output_format"]);function Ab(e){let t=[],r=new Map;for(let n of e.overrides){let o=r.get(n.service)??[];o.push(n),r.set(n.service,o)}for(let n of[...r.keys()].sort((o,i)=>o.localeCompare(i))){let o=r.get(n);if(o.length<=1||Ob.has(n))continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_service_override_collision:${n}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}async function zx(e){let t=il(e.policy??Xg),r=Fr(),n=Zi(),o=Qi(),i=es(),s=ts(),a=rs(),c=ns(),d=[],l=[];for(let m of e.loaded){let _=Bl(m.module);if(!_)continue;let y=d.length,w=Gd({hooks:r,commands:n,parsers:o,preflight:i,services:s,renderers:a,registrations:c});try{await _.activate(wb(m,r,n,o,i,s,a,c,l,d,t)),d.length>y&&(w(),l.push(`extension_activation_rolled_back:${m.layer}:${m.name}`))}catch(v){w(),l.push(`extension_activate_failed:${m.layer}:${m.name}`);let C=vl(v);d.push({layer:m.layer,name:m.name,entry_path:m.entry_path,error:yo(v),trace:C})}}let u=[...Eb(n),...Sb(o),..._l(i),...Ab(s),...kb(a)],f=[...new Set([...l,...u])];return{hooks:r,commands:n,parsers:o,preflight:i,services:s,renderers:a,registrations:c,failed:d,warnings:f,hook_counts:{before_command:r.beforeCommand.length,before_mutation:r.beforeMutation.length,after_command:r.afterCommand.length,on_write:r.onWrite.length,on_read:r.onRead.length,on_index:r.onIndex.length},command_override_count:n.overrides.length,command_handler_count:n.handlers.length,parser_override_count:o.overrides.length,preflight_override_count:i.overrides.length,service_override_count:s.overrides.length,renderer_override_count:a.overrides.length,registration_counts:vb(c)}}(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]="b1a38f8c-8f65-59e2-bddf-ed0606a0f0b5")}catch{}})();function Vx(e){return{...e,hooks:Fr(),profileEnabled:!!e.globalOptions.profile,migrationBlockers:[]}}(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]="4da25248-2914-5bc5-aa42-87f677ef4ea8")}catch{}})();function Wx(){let e=Promise.resolve(),t=new Set;return{async read(r){let n=e,o,i=new Promise(s=>{o=s});t.add(i),await n;try{return await r()}finally{t.delete(i),o()}},write(r){let n=Promise.all([e,...t]).then(()=>r());return e=n.then(()=>{},()=>{}),n}}}function Ib(){let e=Promise.resolve(),t=0,r=[],n=()=>{if(t!==0)return;let o=r.splice(0);for(let i of o)i()};return{enqueue(o){t++;let i=e.then(()=>o());return e=i.then(()=>{},()=>{}).finally(()=>{t--,n()}),i},idle(){return t===0?Promise.resolve():new Promise(o=>r.push(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]="d8844150-afb4-5f2e-a005-4cfb8482660c")}catch{}})();var Tb={commands:["registerCommand","command override","command handler"],renderers:["registerRenderer"],hooks:["hooks.beforeCommand","hooks.beforeMutation","hooks.afterCommand","hooks.onWrite","hooks.onRead","hooks.onIndex"],schema:["registerFlags","registerItemFields","registerItemTypes","registerRelationshipKinds","registerMigration","registerProfile"],importers:["registerImporter","registerExporter"],search:["registerSearchProvider","registerVectorStoreAdapter"],parser:["registerParser"],preflight:["registerPreflight"],services:["registerService","registerAssuranceMeasurementProvider"]},Wl=":";function Gl(e,t){return`${e}${Wl}${Rs(t)}`}function Cb(e){return e.slice(e.indexOf(Wl)+1)}function Rs(e){return e.trim().toLowerCase()}function Rb(e){if(!Array.isArray(e))return[];let t=new Set;for(let r of e){let n=Ad(r);n!==null&&t.add(n)}return[...t].sort((r,n)=>r.localeCompare(n))}function Kl(e){let t=new Map,r=(l,u)=>{for(let f of l){let m=Gl(f.layer,f.name),_=t.get(m);_===void 0&&(_=new Set,t.set(m,_)),_.add(u)}},{registrations:n,commands:o,parsers:i,preflight:s,services:a,renderers:c,hooks:d}=e;return r(n.commands,"commands"),r(o.overrides,"commands"),r(o.handlers,"commands"),r(n.flags,"schema"),r(n.item_fields,"schema"),r(n.item_types,"schema"),r(n.relationship_kinds??[],"schema"),r(n.migrations,"schema"),r(n.profiles,"schema"),r(n.importers,"importers"),r(n.exporters,"importers"),r(n.search_providers,"search"),r(n.vector_store_adapters,"search"),r(i.overrides,"parser"),r(s.overrides,"preflight"),r(a.overrides,"services"),r(n.assurance_providers??[],"services"),r(c.overrides,"renderers"),r(d.beforeCommand,"hooks"),r(d.beforeMutation,"hooks"),r(d.afterCommand,"hooks"),r(d.onWrite,"hooks"),r(d.onRead,"hooks"),r(d.onIndex,"hooks"),t}function xb(e,t={}){let r=Kl(e),n=new Set;t.extensionName!==void 0&&n.add(Rs(t.extensionName));for(let i of t.extensionNames??[])n.add(Rs(i));let o=new Set;for(let[i,s]of r)if(!(n.size>0&&!n.has(Cb(i))))for(let a of s)o.add(a);return[...o].sort((i,s)=>i.localeCompare(s))}function Nb(e,t){let r=Kl(t),n=[];for(let o of e){let i=Rb(o.capabilities);if(i.length===0)continue;let s=r.get(Gl(o.layer,o.name))??new Set,a=[...s].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>!s.has(d));n.push({layer:o.layer,name:o.name,declared:i,used:a,unused:c})}return n}import{existsSync as Db}from"node:fs";import{AsyncLocalStorage as Pb}from"node:async_hooks";import Me 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]="7c2e7a35-cbf9-5bb6-abfd-f1ae75c6afc2")}catch{}})();var $e=null,er=null,Jr=null,Zr=null,tr=null,Qr=null,en=null,Be=null,go,ho=[],Xl=new Pb;function M(){return Xl.getStore()}function eN(e){return Xl.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},e)}var Mb=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function Yl(e){let t=Me.resolve(e);for(;;){if(Db(Me.join(t,".git")))return t;let r=Me.dirname(t);if(r===t)return;t=r}}function bo(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),r=Yl(t)??Me.resolve(t),n=Yl(r);if(!e)return{source_workspace_root:r,...n?{repo_root:n}:{}};let o=Me.relative(r,Me.resolve(e)),i=o.length>0&&!o.startsWith(`..${Me.sep}`)&&o!==".."&&!Me.isAbsolute(o);return{source_workspace_root:r,...n?{repo_root:n}:{},...i?{pm_root_rel:o.split(Me.sep).join("/")}:{}}}function tN(e){let t=M();if(t){t.hooks=e;return}$e=e}function rN(e){let t=M();if(t){t.commands=e;return}er=e}function nN(e){let t=M();if(t){t.parsers=e;return}Jr=e}function oN(e){let t=M();if(t){t.preflight=e;return}Zr=e}function iN(e){let t=M();if(t){t.services=e;return}tr=e}function sN(e){let t=M();if(t){t.renderers=e;return}Qr=e}function aN(e){let t=M();if(t){t.registrations=e;return}en=e}function Jl(){let e=M();return e?e.registrations:en}function cN(){let e=M();if(e){e.hooks=null,e.commands=null,e.parsers=null,e.preflight=null,e.services=null,e.renderers=null,e.registrations=null,e.commandContext=null,e.commandResult=null,e.affectedItems=[];return}$e=null,er=null,Jr=null,Zr=null,tr=null,Qr=null,en=null,Be=null,go=null}function dN(e){let t=e?{...e,...bo(e.pm_root)}:null,r=M();if(r){r.commandContext=t;return}Be=t}function Zl(){let e=M(),t=e?e.commandContext:Be;return t?{...t,args:[...t.args],options:t.options?{...t.options}:{},global:t.global?{...t.global}:void 0}:null}function lN(e){let t=M()??{commandContext:Be,hooks:$e,commands:er,parsers:Jr,preflight:Zr,services:tr,renderers:Qr,registrations:en};return t.commandContext?.command!==e||[t.hooks,t.preflight,t.services,t.renderers].some(r=>Object.values(r??{}).some(n=>n.length>0))||[t.commands,t.parsers].some(r=>Object.values(r??{}).some(n=>n.some(o=>o.command===e)))?!1:!Object.entries(t.registrations??{}).some(([r,n])=>["migrations","search_providers","vector_store_adapters","assurance_providers"].includes(r)&&n.length>0)}function wo(e){let t=M();if(t){t.commandResult=e;return}go=e}function uN(){let e=M();return e?e.commandResult:go}function fN(e){if(!e)return;let t=M();t?t.affectedItems.push(e):ho.push(e)}function mN(e,t){if(!e||!e.id)return{};let r={id:e.id,type:e.type,status:e.status};if(!Array.isArray(t))return r;let n=e;for(let o of t){if(typeof o!="string")continue;let i=o.startsWith("unset:")?o.slice(6):o;i==="id"||i==="type"||i==="status"||Mb.has(i)||Object.hasOwn(n,i)&&n[i]!==void 0&&(r[i]=n[i])}return r}function pN(){let e=M(),t=e?.affectedItems??ho;if(t.length===0)return;let r=t;return e?e.affectedItems=[]:ho=[],r}function _N(){let e=M();if(e){e.hooks=null,e.commands=null,e.parsers=null,e.preflight=null,e.services=null,e.renderers=null,e.registrations=null,e.commandContext=null,e.commandResult=void 0,e.affectedItems=[];return}$e=null,er=null,Jr=null,Zr=null,tr=null,Qr=null,en=null,Be=null,go=void 0,ho=[]}async function vo(e){let t=M(),r=t?t.hooks:$e;return r?as(r,e):[]}async function yN(e){let t=M(),r=t?t.hooks:$e;r&&await ss(r,e)}async function rr(e){let t=M(),r=t?t.hooks:$e;return r?cs(r,e):[]}function hN(){let e=M();return((e?e.hooks:$e)?.onRead?.length??0)>0}async function gN(e){let t=M(),r=t?t.hooks:$e;return r?ds(r,e):[]}function Ql(e){let t=M(),r=t?t.commands:er,n=t?t.commandContext:Be;return!r||!n?{overridden:!1,result:e,warnings:[]}:_s(r,{command:n.command,args:[...n.args],options:n.options?{...n.options}:{},global:n.global?{...n.global}:void 0,pm_root:n.pm_root,source_workspace_root:n.source_workspace_root,repo_root:n.repo_root,pm_root_rel:n.pm_root_rel,result:e})}async function bN(e){let t=M(),r=t?t.commands:er;return r?ls(r,{...e,...bo(e.pm_root)}):{handled:!1,result:null,warnings:[]}}async function wN(e){let t=M(),r=t?t.parsers:Jr;return r?us(r,{...e,...bo(e.pm_root)}):{overridden:!1,context:{command:e.command,args:[...e.args],options:{...e.options},global:{...e.global},pm_root:e.pm_root},warnings:[]}}async function vN(e){let t=M(),r=t?t.preflight:Zr;return r?fs(r,{...e,...bo(e.pm_root)}):{overridden:!1,context:{command:e.command,args:[...e.args],options:{...e.options},global:{...e.global},pm_root:e.pm_root},decision:{...e.decision},warnings:[]}}function eu(e,t){let r=M(),n=r?r.renderers:Qr,o=r?r.commandContext:Be;return n?ys(n,{format:e,command:o?.command,args:o?[...o.args]:[],options:o?.options?{...o.options}:{},global:o?.global?{...o.global}:void 0,pm_root:o?.pm_root,source_workspace_root:o?.source_workspace_root,repo_root:o?.repo_root,pm_root_rel:o?.pm_root_rel,result:t}):{overridden:!1,rendered:null,warnings:[]}}function tu(e,t){let r=M(),n=r?r.commandContext:Be;return{service:e,command:n?.command,args:n?[...n.args]:[],options:n?.options?{...n.options}:{},global:n?.global?{...n.global}:void 0,pm_root:n?.pm_root,source_workspace_root:n?.source_workspace_root,repo_root:n?.repo_root,pm_root_rel:n?.pm_root_rel,payload:t}}async function nr(e,t){let r=M(),n=r?r.services:tr;return n?ps(n,tu(e,t)):{handled:!1,result:t,warnings:[]}}function xs(e,t){let r=M(),n=r?r.services:tr;return n?ms(n,tu(e,t)):{handled:!1,result:t,warnings:[]}}(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]="4a7b042c-7fb8-57a5-8f94-de44f82d7589")}catch{}})();function $b(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function We(e,t){let r=e.slice(0,t),n=r.charCodeAt(r.length-1),o=e.charCodeAt(r.length);return n>=55296&&n<=56319&&o>=56320&&o<=57343?r.slice(0,-1):r}function IN(e){return $b(e).split(/[^a-z0-9]+/).filter(t=>t.length>0)}function TN(e,t){if(e.length===0&&t.length===0)return 1;if(e.length===0||t.length===0)return 0;let r=new Set(e),n=new Set(t),o=0;for(let s of r)n.has(s)&&(o+=1);let i=new Set([...r,...n]).size;return o/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]="3a66ccfd-51fb-5d4a-b9cd-257c49997d52")}catch{}})();var ou=new WeakMap;function NN(e,t){ou.set(e,new Set(t))}var Eo='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',jb={context:{row_keys:["high_level","low_level"],fields:"supported"},get:{row_keys:["children"],fields:"supported"},list:{row_keys:["items"],fields:"supported"},next:{row_keys:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],fields:"unsupported"},search:{row_keys:["items"],fields:"supported"},activity:{row_keys:["activity_digest","compact_activity","provenance_activity","activity"],fields:"unsupported"},history:{row_keys:["compact_history","provenance_history","history","diff"],fields:"unsupported"},deps:{row_keys:["graph.nodes","graph.edges","context.nodes","context.edges"],fields:"unsupported"},health:{row_keys:["checks"],fields:"unsupported"},aggregate:{row_keys:["groups"],fields:"unsupported"},duplicates:{row_keys:["clusters"],fields:"unsupported"},stats:{row_keys:["by_type","by_status"],fields:"unsupported"},comments:{row_keys:["comments"],fields:"unsupported"},notes:{row_keys:["notes"],fields:"unsupported"},learnings:{row_keys:["learnings"],fields:"unsupported"},files:{row_keys:["files"],fields:"unsupported"},docs:{row_keys:["docs"],fields:"unsupported"},validate:{row_keys:["checks","warnings"],fields:"unsupported"},contracts:{row_keys:["command_summaries","commands"],fields:"unsupported"}},Lb=[{command:"activity",complete_mode:"full",omissions_by_mode:{digest:[{name:"event_rows",restore_with:"--raw"}],compact:[{name:"provenance",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}},{command:"history",complete_mode:"full",omissions_by_mode:{compact:[{name:"raw_history",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}}];function DN(e,t,r){if(e&&t)throw new g(`${r} cannot be combined with --full`,h.USAGE)}function Ae(e,t=new Set){let r=e.filter(n=>!t.has(n.name)).map(n=>({...n}));return{has_omissions:r.length>0,omitted_field_group_count:r.length,omitted_field_groups:r}}function PN(e,t){let r=Lb.find(o=>o.command===e);if(r===void 0)throw new TypeError(`Unknown mode-paired output command: ${e}`);if(t===r.complete_mode)return Ae([]);let n=r.omissions_by_mode[t];if(n===void 0)throw new TypeError(`Unknown ${e} output mode: ${t}`);return Ae(n)}var Fb=[{name:"hierarchy",restore_with:"--section hierarchy"},{name:"activity",restore_with:"--section activity"},{name:"progress",restore_with:"--section progress"},{name:"blockers",restore_with:"--section blockers"},{name:"recently_created",restore_with:"--section recently_created"},{name:"unparented",restore_with:"--section unparented"},{name:"files",restore_with:"--section files"},{name:"workload",restore_with:"--section workload"},{name:"staleness",restore_with:"--section staleness"},{name:"tests",restore_with:"--section tests"}];function te(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var zb=new Set([void 0,"tabular_when_uniform"]),Ub=new Set(["collection","none"]),Hb=new Set(["supported","unsupported"]);function ru(e,t){return Array.isArray(e)&&(t||e.length>0)&&e.every(r=>typeof r=="string"&&r.length>0)&&new Set(e).size===e.length}function qb(e){return te(e)&&typeof e.command=="string"&&e.command.trim().length>0&&Ub.has(e.row_kind)&&ru(e.row_keys,!0)&&(e.continuation_row_keys===void 0||ru(e.continuation_row_keys,!1))&&Hb.has(e.fields)&&zb.has(e.toon_encoding)&&(e.row_kind==="collection"?e.row_keys.length>0&&typeof e.jq_selector=="string"&&e.jq_selector.trim().length>0:e.row_keys.length===0&&e.jq_selector===void 0)}var Vb={ancestors:["ids"],descendants:["ids"],predecessors:["ids"],successors:["ids"],paths:["paths"],impact:["affected"],audit:["findings"],communities:["communities"],redundancy:["redundant"],dominators:["bottlenecks"],slack:["rows"],centrality:["rows"],articulation:["articulation_points","bridges"],plan:["steps"]},Bb={context:["sections_included","high_level","low_level"],get:["item"],list:["items","projection"],next:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items","projection"],activity:["activity_digest","compact_activity","provenance_activity","activity"],history:["compact_history","provenance_history","history","diff"],deps:["tree","graph","projection"],health:["checks"],aggregate:["groups"],duplicates:["clusters"],stats:["totals","by_type","by_status"],comments:["comments"],notes:["notes"],learnings:["learnings"],files:["files"],docs:["docs"],validate:["checks","warnings"],contracts:["command_summaries","commands","selected"]};function Wb(e,t){let r=e.trim().toLowerCase().split(/\s+/u,1)[0],n=r?.startsWith("list-")?"list":r;if(n==="graph"){let s=typeof t.subcommand=="string"?t.subcommand:"";if(s.length===0)return;let a=Vb[s];if(a===void 0)return;let c=a.filter(d=>Array.isArray(t[d])||te(t[d]));return{command:"graph",row_kind:c.length>0?"collection":"none",row_keys:c,fields:"unsupported",...c.length>0?{jq_selector:Eo}:{},toon_encoding:"tabular_when_uniform"}}let o=jb[n],i=Bb[n];return o===void 0||i===void 0||!i.some(s=>Object.hasOwn(t,s))?void 0:(()=>{let s=o.row_keys.filter(a=>{let c=a.split(".").reduce((d,l)=>te(d)?d[l]:void 0,t);return Array.isArray(c)||te(c)});return{command:n,row_kind:s.length>0?"collection":"none",row_keys:s,fields:o.fields,...s.length>0?{jq_selector:Eo}:{},toon_encoding:"tabular_when_uniform"}})()}function Gb(e){if(!te(e.projection)||typeof e.projection.mode!="string"||e.projection.mode.trim().length===0)return;let t=e.projection.declared_field_groups,r=e.projection.included_field_groups;if(!Array.isArray(t)||!Array.isArray(r))return;let n=t.filter(s=>te(s)&&typeof s.name=="string"&&s.name.trim().length>0&&typeof s.restore_with=="string"&&s.restore_with.trim().length>0),o=r.filter(s=>typeof s=="string");if(n.length!==t.length||o.length!==r.length)return;let i=new Set(n.map(s=>s.name));if(!(i.size!==n.length||new Set(o).size!==o.length||o.some(s=>!i.has(s))))return Ae(n,new Set(o))}function Kb(e){if(!Array.isArray(e.sections_included))return;let t=Ae(Fb,new Set(e.sections_included.filter(r=>typeof r=="string")));return te(e.summary)&&e.summary.scope==="matching_items"&&(t.summary_scope="matching_items"),t}function Yb(e,t,r){return e==="dependency_provenance"?!1:Object.hasOwn(t,e)||(e==="reminders"||e==="events")&&te(r.schedule)&&Object.hasOwn(r.schedule,e)||["files","tests","docs"].includes(e)&&te(r.linked)&&Array.isArray(r.linked[e])&&r.linked[e].length>0}function Xb(e){if(!te(e.item))return;let t=e.item,r=["comments","notes","learnings","files","tests","docs","reminders","events"],n=["body","children","claim_state","linked","schedule"],o=ou.get(e),i=a=>r.includes(a)||a==="body"||a==="dependency_provenance"?t:e,s=["body",...r,...n.slice(1),...o?.has("dependency_provenance")?["dependency_provenance"]:[],...o?.has("blockers")||Object.hasOwn(e,"blockers")?["blockers"]:[]].filter(a=>o===void 0||o.has(a)||Object.hasOwn(i(a),a)).map(a=>({name:a,restore_with:a==="blockers"?"--full":a==="dependency_provenance"?"--fields dependencies":`--fields ${a}`}));return Ae(s,new Set(s.flatMap(({name:a})=>Yb(a,i(a),e)?[a]:[])))}function nu(e){if(te(e.projection))return Ae([{name:"full_item_fields",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_item_fields"]:[]))}function Jb(e){if(!te(e.projection))return Ae([]);if(typeof e.projection.mode=="string")return Ae([{name:"full_check_details",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_check_details"]:[]))}function Zb(e){if(!(!te(e.selected)||typeof e.selected.summary!="boolean"))return Ae([{name:"full_contract_catalog",restore_with:"--full"}],new Set(e.selected.summary?[]:["full_contract_catalog"]))}function Qb(e,t){let r=Gb(t);if(r!==void 0)return r;let[n]=e.split(/\s+/u,1);if(n==="context")return Kb(t);if(n==="get")return Xb(t);if(n==="list"||n.startsWith("list-"))return nu(t);if(n==="search")return nu(t)??Ae([{name:"projection_metadata",restore_with:"--full"}]);if(n==="health")return Jb(t);if(n==="contracts")return Zb(t)}function iu(e,t){if(e===void 0||!te(t))return t;let r=Qb(e,t),n=t.row_contract,o=qb(n)?n:Wb(e,t),i=o!==void 0?{...t,row_contract:o}:Object.hasOwn(t,"row_contract")?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="row_contract")):t;return te(i.omission_receipt)||r===void 0?i:{...i,omission_receipt: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]="86412887-5659-5892-beaa-bdd15a02ff4c")}catch{}})();var su=e=>{let t='"',r=0;for(let n of e){if(n==="\\"){r+=1;continue}t+="\\".repeat(n==='"'?r*2+1:r),t+=n,r=0}return`${t}${"\\".repeat(r*2)}"`},au=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?su(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,or=(e,t=process.platform)=>{let r=e.map(n=>au(n,t)).join(" ");return r.length>0?`pm ${r}`:"pm"};(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]="7607f0d2-6e95-5b85-9bc2-18f643a64171")}catch{}})();var cu=new Set(["--pm-path","--path","--author","--output-include","--output-limit","--output-budget","--output-format","--format","--output-session","--output-cursor"]),ew=new Set(["--no-extensions","--no-pager","--json","--quiet","--lean","--token-accounting","--output-row-contract","--all"]);function tw(e){let t=e.indexOf("=");return t>0&&cu.has(e.slice(0,t))}function rw(e,t){return typeof t!="string"?!1:e==="--path"||e==="--pm-path"||!t.startsWith("-")}function ko(e){for(let t=0;t<e.length;t+=1){let r=e[t];if(r==="--")return;if(cu.has(r)){t+=rw(r,e[t+1])?1:0;continue}if(!(tw(r)||ew.has(r)||r==="--profile"||r==="--id-only"||r==="--explain")&&!r.startsWith("-"))return t}}function jN(e){let t=ko(e);return t===void 0?void 0:e[t].trim().toLowerCase()}(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]="98cde1d6-d5dd-56b9-89f9-51f5d08221d1")}catch{}})();var nw=new Set(["--literal","--regex","--replacement"]);function ow(e){let t=ko(e);if(t===void 0)return!1;if(e[t]==="history-redact")return!0;if(e[t]!=="history")return!1;let r=e.slice(t+1),n=ko(r);return n!==void 0&&r[n]==="redact"}function UN(e){if(!ow(e))return[...e];let t=[],r=!1;for(let n of e){if(r){t.push("[redacted]"),r=!1;continue}r=!1;let o=n.indexOf("="),i=o>=0?n.slice(0,o):n;if(!nw.has(i)){t.push(n);continue}if(o>=0){t.push(`${i}=[redacted]`);continue}t.push(i),r=!0}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]="b6db58d1-5d89-56b2-adee-13e985ebc675")}catch{}})();var iw=new Set(["applied_bound","completeness","budget_retention_policy","continuation_contract","continuation_kind","continuation_path","filters","omission_receipt","output_budget_truncation","projection","read_output","read_session","row_contract","sorting"]);function X(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function du(e,t){let r=e;for(let n of t.split("."))if(Array.isArray(r)){if(!/^\d+$/u.test(n))return;r=r[Number(n)]}else{if(!X(r))return;r=r[n]}return r}function Ns(e,t,r){let n=t.split("."),o=(i,s)=>{if(s===n.length)return r;let a=n[s];if(Array.isArray(i)){let d=Number(a),l=[...i];return l[d]=o(i[d],s+1),l}let c=i;return{...c,[a]:o(c[a],s+1)}};return o(e,0)}function lu(e,t,r){let n=ir(e).find(s=>s.path===t);if(!n)return e;let o=Array.isArray(n.value)?n.value.slice(r):Object.fromEntries(Object.entries(n.value).slice(r)),i=Ns(e,t,o);return X(i.summary)&&X(i.summary.focus_row_states)&&typeof i.summary.focus_row_states[t]=="string"&&(i.summary={...i.summary,focus_row_states:{...i.summary.focus_row_states,[t]:i.summary.focus_row_states[t].slice(r)}}),nn(i),i}function Oo(e){let t=e.row_contract;return X(t)&&Array.isArray(t.row_keys)?t.row_keys.filter(r=>typeof r=="string"&&r.trim().length>0):Object.entries(e).filter(([,r])=>Array.isArray(r)).map(([r])=>r)}function sw(e){let t=e.row_contract;return X(t)&&Array.isArray(t.continuation_row_keys)?t.continuation_row_keys.filter(r=>typeof r=="string"&&r.trim().length>0):Oo(e)}function Ge(e){return Oo(e).flatMap(t=>{let r=du(e,t);return Array.isArray(r)||X(r)?[{path:t,value:r}]:[]})}function ir(e){return sw(e).flatMap(t=>{let r=du(e,t);return Array.isArray(r)||X(r)?[{path:t,value:r}]:[]})}function tn(e){let t=Ge(e),r=new Set(t.map(o=>o.path)),n=(o,i)=>{if(Array.isArray(o)){r.has(i)||t.push({path:i,value:o}),o.forEach((s,a)=>n(s,`${i}.${a}`));return}if(X(o))for(let[s,a]of Object.entries(o))i.length===0&&iw.has(s)||n(a,i.length===0?s:`${i}.${s}`)};return n(e,""),t}function Ao(e){return Ge(e).reduce((t,r)=>t+(Array.isArray(r.value)?r.value.length:Object.keys(r.value).length),0)}function rn(e,t){let r=e;for(let n of Ge(r)){let o=Array.isArray(n.value)?n.value.map((i,s)=>t(i,n.path,s)):Object.fromEntries(Object.entries(n.value).map(([i,s],a)=>[i,t(s,n.path,a)]));r=Ns(r,n.path,o)}return r}function uu(e,t){let r=e,n=!1;for(let o of Ge(r)){let i=Array.isArray(o.value)?o.value:Object.entries(o.value);if(i.length<=t)continue;n=!0;let s=Array.isArray(o.value)?i.slice(0,t):Object.fromEntries(i.slice(0,t));r=Ns(r,o.path,s)}return{result:r,truncated:n}}var fu=["high_level","low_level","blocked_fallback"];function So(e){let t=e.status==="in_progress"?"i":"o";return e.blocked===!0?t.toUpperCase():t}function qN(e,t){if(!X(e.summary)||!X(e.summary.returned_focus))return;let r=new Map(t.map(n=>[n.id,n]));e.summary={...e.summary,focus_row_states:Object.fromEntries(fu.map(n=>[n,Array.isArray(e[n])?e[n].filter(X).map(o=>So(r.get(o.id)??o)).join(""):""]))}}function aw(e,t){if(e!==void 0){if(typeof e!="string"||e.length!==t||!/^[iIoO]*$/u.test(e))throw new TypeError("Context focus classification receipt must contain one i/I/o/O code per delivered record");return e}}function cw(e,t,r,n){let o=Array.isArray(t[r])?t[r].filter(X):[],i=aw(n[r],o.length)??o.map(So).join(""),s=new Map(o.flatMap((d,l)=>d.id===void 0?[]:[[d.id,i[l]]])),a=Array.isArray(e[r])?e[r].filter(X):[],c=!1;return{states:a.map((d,l)=>{let u=s.get(d.id)??(d.id===void 0?i[l]:void 0)??So(d);return u!==So(d)&&(c=!0),u}).join(""),needsStates:c}}function dw(e,t){typeof e.count=="number"&&(e.count_only===!0||t.count_only===!0?typeof t.count=="number"&&(e.count=t.count):Array.isArray(e.items)&&(e.count=e.items.length))}function nn(e,t=e){if(dw(e,t),!X(e.summary)||!X(e.summary.returned_focus))return;let r={...e.summary},n=X(t.summary)&&X(t.summary.focus_row_states)?t.summary.focus_row_states:{},o=fu.map(c=>({key:c,...cw(e,t,c,n)})),i=Object.fromEntries(o.map(({key:c,states:d})=>[c,d])),s=o.some(c=>c.needsStates),a=Object.values(i).join("");typeof r.high_level=="number"&&(r.high_level=Array.isArray(e.high_level)?e.high_level.length:0),typeof r.low_level=="number"&&(r.low_level=Array.isArray(e.low_level)?e.low_level.length:0),r.returned_focus={active_items:a.length,in_progress:[...a].filter(c=>c.toLowerCase()==="i").length,open:[...a].filter(c=>c.toLowerCase()==="o").length,blocked:[...a].filter(c=>c===c.toUpperCase()).length},s?r.focus_row_states=i:delete r.focus_row_states,e.summary=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]="9bdf8ad1-8d1e-5e3e-a23a-ba1d4293402b")}catch{}})();var Io="changed_fields",lw="changed_field_count",Ds="rows",uw=new Set(["apply","rollback"]),yu=new Set(["deleted","would_delete"]),mu=256,pu={start_task:["claim","update"],pause_task:["update","release"],close_task:["close","release"]};function fw(e,t){if(!re(e)||typeof e.action!="string"||typeof e.id!="string"||e.id.length===0)return null;let r=Object.hasOwn(pu,e.action)?pu[e.action]:void 0;if(!r||!r.every(i=>{let s=e[i];return re(s)&&re(s.item)&&s.item.id===e.id&&Array.isArray(s.changed_fields)&&s.changed_fields.every(a=>typeof a=="string")}))return null;let n=e[r.at(-1)],o=gu(n);return t.idOnly?o:!t.compactEnvelope&&t.changedFields!=="compact"?null:{...e,...t.compactEnvelope?{...o,changed_field_count:new Set(r.flatMap(i=>e[i].changed_fields)).size}:{},...Object.fromEntries(r.map(i=>[i,on(e[i],t)]))}}function _u(e){return typeof e!="string"||e.length<=mu?e:`${We(e,mu-1)}\u2026`}function mw(e){if(!re(e))return null;let t={...e};return t.reason=_u(t.reason),re(t.previous_terminal)&&(t.previous_terminal=Object.fromEntries(Object.entries(t.previous_terminal).map(([r,n])=>[r,_u(n)]))),t}function re(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function hu(e){let t=e[Io];if(!Array.isArray(t))return null;let r=Object.getPrototypeOf(e)===null?Object.create(null):{};for(let[n,o]of Object.entries(e))n!==Io&&(r[n]=o);return r[lw]=t.length,r}function pw(e){return"item"in e&&Array.isArray(e[Io])}function _w(e){return typeof e.mode=="string"&&uw.has(e.mode)&&Array.isArray(e[Ds])}function yw(e,t){let r=Object.getPrototypeOf(e)===null?Object.create(null):{};return Object.assign(r,e),r[Ds]=t,r}function gu(e){if(!re(e))return null;let t=re(e.item)?e.item:re(e.plan)?e.plan:null;if(t===null)return null;let r=typeof t.id=="string"?t.id:void 0,n=typeof e.outcome=="string"&&yu.has(e.outcome)?e.outcome:typeof t.status=="string"?t.status:void 0;return r?n?{id:r,status:n,...typeof e.deleted=="boolean"?{deleted:e.deleted}:{}}:{id:r}:null}function hw(e,t){if(!re(e))return null;if(re(e.plan)&&re(e.mutation_receipt)&&e.mutation_receipt.kind==="plan_mutation"&&e.mutation_receipt.id===e.plan.id&&e.mutation_receipt.action===e.action)return e.mutation_receipt;if(!t||!re(e.item)||typeof e.item.id!="string")return null;let r=e[Io];if(!Array.isArray(r))return null;let n={id:e.item.id,...typeof e.outcome=="string"&&yu.has(e.outcome)?{status:e.outcome}:typeof e.item.status=="string"?{status:e.item.status}:{},...typeof e.deleted=="boolean"?{deleted:e.deleted}:{},...typeof e.previous_status=="string"?{previous_status:e.previous_status}:{},changed_field_count:r.length};return gw(e,e.item,n),n}function gw(e,t,r){let n=typeof e.close_reason=="string"?e.close_reason:typeof t.close_reason=="string"?t.close_reason:void 0;n!==void 0&&(r.close_reason=n);let o=mw(e.recurrence);o!==null&&(r.recurrence=o),Array.isArray(e.warnings)&&e.warnings.length>0&&(r.warnings=e.warnings);for(let i of["recovery","follow_up","handoff"])re(e[i])&&(r[i]=e[i]);if(typeof e.claimed_by=="string"||typeof e.released_by=="string")for(let i of["claimed_by","released_by","previous_assignee","forced","skipped","available","attempts","suggestions"])Object.hasOwn(e,i)&&(r[i]=e[i])}function bw(e){let t=_w(e)?e[Ds]:void 0;if(!Array.isArray(t))return{projected:e,changed:!1};let r=!1,n=t.map(o=>{if(!re(o))return o;let i=hu(o);return i?(r=!0,i):o});return r?{projected:yw(e,n),changed:!0}:{projected:e,changed:!1}}function on(e,t={}){let r=fw(e,t);if(r!==null)return r;if(t.idOnly===!0){let a=gu(e);if(a!==null)return a}if(t.compactEnvelope===!0||t.changedFields==="compact"){let a=hw(e,t.compactEnvelope===!0);if(a!==null)return a}if((t.changedFields??"full")==="full"||!re(e))return e;let n=!1,o=e,i=pw(e)?hu(e):null;i!==null&&(o=i,n=!0);let s=bw(o);return s.changed&&(o=s.projected,n=!0),n?o:e}import{AsyncLocalStorage as $E}from"node:async_hooks";(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]="1b67272d-8924-5b1b-97cd-74a6a10493be")}catch{}})();function Ps(e){let t=e.trim().toLowerCase().startsWith("extension:"),r=e.trim().toLowerCase().replace(/^extension:/u,"");if(Xt(r))return;let n=Jl()?.commands??[],o=[...n].reverse().find(s=>s.command===r)?.command??(t?void 0:n.find(s=>s.action===r)?.command),i=[...n].reverse().find(s=>s.command===o);return i===void 0||Xt(i.command)||Xt(i.action)?void 0:i}function ww(e){let t=Ps(e);return t?.read_output===void 0?void 0:t}function bu(e,t){let r=ww(e),n=r?.read_output;if(n===void 0)return t;if(typeof t!="object"||t===null||Array.isArray(t))throw new g("Read-only extension commands must return a structured object.",h.USAGE,{code:"extension_read_output_invalid"});for(let o of n.row_keys){let i=t;for(let s of o.split("."))i=typeof i=="object"&&i!==null&&Object.hasOwn(i,s)?Reflect.get(i,s):void 0;if(i===null||typeof i!="object")throw new g(`Read-only extension result is missing declared row collection ${o}.`,h.USAGE,{code:"extension_read_output_invalid"})}return{...t,row_contract:{command:`extension:${r.command}`,row_kind:n.row_keys.length>0?"collection":"none",row_keys:[...n.row_keys],fields:"supported",...n.row_keys.length>0?{jq_selector:Eo}:{},toon_encoding:"tabular_when_uniform"}}}import{createHash as Cv}from"node:crypto";import{createHash as Sv}from"node:crypto";import{stripVTControlCharacters as vw}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]="c8a91fc2-57b4-5738-9428-9847ef7afadc")}catch{}})();var Ew=["full","compact","brief","summary","counts"],nD=["mutation","read","discovery","governance"],vu=["error","warning","validation_summary","recovery_bundle"],kw=["full","omit_explanation","limit_collections","compact_recovery","action_only"],Sw=new Set(["append","claim","close","close-many","close-task","comments","config","copy","create","delete","docs","event","files","focus","history-author-acknowledge","history-compact","history-redact","history-repair","init","item","learnings","meet","notes","pause-task","release","remind","restore","schema","start-task","update","update-many"]),Ow=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),Aw=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),Iw={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},Tw=3,Cw=2,Rw=192,xw={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},Nw=vu.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:xw[e],minimum_max_estimated_tokens:Rw,degradation_ladder:kw,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),Dw=new Map(Nw.map(e=>[e.diagnostic_class,e]));function Pw(e){let[t=""]=Nr(e).split(/\s+/u);return Sw.has(t)?"mutation":Ow.has(t)?"discovery":Aw.has(t)?"governance":"read"}function Eu(e,t=Pw(e)){let r=e.trim().replace(/\s+/gu," ");if(r.length===0)throw new TypeError("command must be a non-empty command path");let n=Iw[t];return Mw({command:r,budget_class:t,default_max_estimated_tokens:n,default_max_estimated_tokens_by_format:{toon:n,json:Math.ceil(n*Tw/Cw)},degradation_ladder:Ew,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function Mw(e){if(!Number.isSafeInteger(e.default_max_estimated_tokens)||e.default_max_estimated_tokens<=0)throw new RangeError("default_max_estimated_tokens must be a positive safe integer");for(let[t,r]of Object.entries(e.default_max_estimated_tokens_by_format))if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`default_max_estimated_tokens_by_format.${t} must be a positive safe integer`);return e}var $w=oo.map(e=>Eu(e)),jw=new Map($w.map(e=>[e.command,e]));function ku(e,t={}){let r=e.trim().replace(/\s+/gu," "),[n]=Nr(r).split(" "),o=jw.get(n);return o?{...o,command:r}:t.generateFallback?Eu(r):null}function kt(e){return Math.ceil(Math.max(0,e)/4)}function Su(e){let t=Dw.get(e);if(t===void 0)throw new TypeError(`diagnosticClass must be one of: ${vu.join(", ")}`);return t}function Ke(e){return kt(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))}function Lw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ms(e){if(!Lw(e))return;let t={};for(let r of["suggested_retry","suggested_retry_args","next_best_command","allowed_values","candidate_commands","missing","missing_required_fields","option_scope","retry_after_ms"]){let n=e[r];Array.isArray(n)?t[r]=r==="suggested_retry_args"?n:n.slice(0,3):n!==void 0&&(t[r]=n)}return Object.keys(t).length>0?t:void 0}function Fw(e,t){return typeof e!="string"||e.length<=t?e:`${We(e,Math.max(1,t-3))}...`}function Et(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;let r="...",n=Array.from(e),o=0,i=n.length;for(;o<i;){let s=Math.ceil((o+i)/2),a=`${n.slice(0,s).join("")}${r}`;Buffer.byteLength(a,"utf8")<=t?o=s:i=s-1}return`${n.slice(0,o).join("")}${r}`}function Ou(e){let t={};for(let r of["code","required","recovery","next_steps","exit_code","type","title","detail","why","examples"])Object.hasOwn(e,r)&&e[r]!==void 0&&(t[r]=e[r]);for(let[r,n]of Object.entries(e))r!=="__proto__"&&!Object.hasOwn(t,r)&&(t[r]=n);return t}var zw=new Set(["limit_collections","compact_recovery","action_only"]),Uw=new Set(["compact_recovery","action_only"]);function Hw(e){let t={code:typeof e.code=="string"?e.code:"diagnostic",required:Fw(e.required,160)??"Inspect the diagnostic code and retry with corrected input."},r=Ms(e.recovery);return r!==void 0?t.recovery=r:Array.isArray(e.next_steps)&&(t.next_steps=e.next_steps.slice(0,1)),e.exit_code!==void 0&&(t.exit_code=e.exit_code),e.type!==void 0&&(t.type=e.type),t}function qw(e,t){let r=structuredClone(e);if(t!=="full"&&(delete r.why,delete r.examples),zw.has(t))for(let[n,o]of Object.entries(r))Array.isArray(o)&&(r[n]=o.slice(0,3));if(Uw.has(t)){let n=Ms(r.recovery);n?r.recovery=n:delete r.recovery}return t!=="action_only"?Ou(r):Hw(r)}function sr(e,t){let r={...e,diagnostic_output:{...t,estimated_tokens:0}};for(let n=0;n<4;n+=1){let o=Ke(r),i=r.diagnostic_output;if(i.estimated_tokens===o)break;i.estimated_tokens=o}return r}function Vw(e,t,r){let n=sr(e,t);for(let i of["recovery","exit_code"])Ke(n)<=r||e[i]===void 0||(delete e[i],n=sr(e,t));let o=40;for(;Ke(n)>r&&o>4;)o-=4,e.code=Et(String(e.code),o),e.required=Et(String(e.required),o),n=sr(e,t);return n}function Bw(e,t){let r=e.diagnostic_output,{estimated_tokens:n,...o}=r,i=o.omitted_fields.slice(0,8).map(u=>Et(u,32)),s={...o,omitted_fields:i,...o.omitted_fields.length>i.length?{omitted_fields_overflow_count:o.omitted_fields.length-i.length}:{}},a=Ms(e.recovery),c=a&&Ke(a)<=48?a:void 0,d={code:Et(String(e.code),320),required:Et(String(e.required),320),...c?{recovery:c}:{},...e.exit_code!==void 0?{exit_code:e.exit_code}:{}},l=sr(d,s);for(;Ke(l)>t&&s.omitted_fields.length>0;)s.omitted_fields.pop(),s.omitted_fields_overflow_count=o.omitted_fields.length-s.omitted_fields.length,l=sr(d,s);return l=Vw(d,s,t),l}function oD(e,t={}){let r=e,n=t.diagnosticClass??"error",o=Su(n),i=t.maxEstimatedTokens;if(i!==void 0&&(!Number.isSafeInteger(i)||i<o.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${o.minimum_max_estimated_tokens}`);let s=i??o.default_max_estimated_tokens_by_format.json,a=Ke(r),c=Object.keys(r);if(a<=s)return Ou(structuredClone(r));let d;for(let[l,u]of o.degradation_ladder.entries()){let f=qw(r,u),m=c.filter(y=>!Object.hasOwn(f,y)),_=sr(f,{diagnostic_class:n,format:"json",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:a,truncated:l>0,degradation_steps:o.degradation_ladder.slice(0,l+1),omitted_fields:m});if(d=_,Ke(_)<=s)break}return Ke(d)>s&&(d=Bw(d,s)),d}function wu(e){return vw(e).replace(/\r\n/gu,`
2
- `).replace(/[^\P{Cc}\n]/gu," ")}function iD(e,t,r={}){let n=r.diagnosticClass??"error",o=Su(n),i=r.maxEstimatedTokens;if(i!==void 0&&(!Number.isSafeInteger(i)||i<o.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${o.minimum_max_estimated_tokens}`);let s=i??o.default_max_estimated_tokens_by_format.text,a=wu(e),c=kt(Buffer.byteLength(a,"utf8")),d=c>s,l=`What is required:
3
- `,u=`
4
-
5
- ${Et(a.trimStart().split(/\r?\n/u,1)[0].trim(),320)}
6
-
7
- Diagnostic output exceeded its declared ${s}-token ceiling; rerun with structured JSON for the bounded recovery envelope.`,f=wu(t).trim()||"Inspect the diagnostic code and retry with corrected input.",m=Math.max(1,s*4-Buffer.byteLength(`${l}${u}`,"utf8")),_=d?`${l}${Et(f,m)}${u}`:a;return{output:_,diagnostic_output:{diagnostic_class:n,format:"text",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:c,estimated_tokens:kt(Buffer.byteLength(_,"utf8")),truncated:d,degradation_steps:d?[...o.degradation_ladder]:["full"],omitted_fields:d?["explanation","collections"]:[]}}}(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]="f7d00f9c-6e95-5426-971d-9b30e2ec1652")}catch{}})();var $s=256,js=1e4,Ww=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,Au=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,Gw=new Set(["version","id","token_budget","spent_tokens","seen_item_ids"]),Kw=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&Ww.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=$s,reason:`token_budget must be a safe integer of at least ${$s}.`},{valid:e=>Number.isSafeInteger(e.spent_tokens)&&e.spent_tokens>=0&&e.spent_tokens<=e.token_budget,reason:"spent_tokens must be a non-negative safe integer no larger than token_budget."},{valid:e=>Array.isArray(e.seen_item_ids)&&e.seen_item_ids.length<=js&&e.seen_item_ids.every(t=>typeof t=="string"&&Au.test(t)),reason:`seen_item_ids must contain at most ${js} portable item identifiers.`}];function Co(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function To(e){throw new g(`--output-session ${e}`,h.USAGE,{code:"invalid_read_output_session",field:"outputSession"})}function Ro(e){if(e===void 0)return;let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{To("must be a valid JSON object.")}Co(t)||To("must be a JSON object.");let r=Object.keys(t).filter(i=>!Gw.has(i));r.length>0&&To(`contains unknown field "${r.sort()[0]}".`);let n=Kw.find(i=>!i.valid(t));n!==void 0&&To(n.reason);let o=[...new Set(t.seen_item_ids)].sort();return{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:o}}function Iu(e){if(Co(e))return typeof e.id=="string"?e.id:typeof e.item_id=="string"?e.item_id:Co(e.item)&&typeof e.item.id=="string"?e.item.id:void 0}function Yw(e){let t=new Set,r=0,n=Ge(e),o=new Set(n.map(({path:s})=>s)),i=Object.entries(e).flatMap(([s,a])=>Array.isArray(a)&&!o.has(s)?[{path:s,value:a}]:[]);for(let s of[...n,...i]){let a=Array.isArray(s.value)?s.value:Object.values(s.value);for(let c of a){if(!Co(c))continue;if(typeof c.context_ref=="string"){r+=1;continue}let d=Iu(c);d!==void 0&&Au.test(d)&&t.add(d)}}return{deliveredIds:t,suppressedRepeatCount:r}}function Tu(e,t){let r=new Set(t.seen_item_ids);return rn(e,n=>{let o=Iu(n);return o!==void 0&&r.has(o)?{id:o,context_ref:`session:${t.id}:${o}`}:n})}function Ls(e,t,r){let{deliveredIds:n,suppressedRepeatCount:o}=Yw(e),i=new Set(t.seen_item_ids),s=[...n].filter(y=>!i.has(y)).sort(),a=s.slice(0,js-t.seen_item_ids.length),c=[...t.seen_item_ids,...a].sort(),d=s.length-a.length,l={contract_version:1,id:t.id,measurement_scope:"complete_read_envelope",estimator:"ceil(utf8_bytes / 4)",token_budget:t.token_budget,spent_before_tokens:t.spent_tokens,spent_this_call_tokens:0,charged_this_call_tokens:0,spent_total_tokens:t.spent_tokens,remaining_tokens:t.token_budget-t.spent_tokens,exhausted:!1,seen_before_count:t.seen_item_ids.length,new_item_count:n.size,...d===0?{}:{seen_item_overflow_count:d},suppressed_repeat_count:o,reference_format:"session:<session-id>:<item-id>",restore_reference_with:"pm get <item-id> --brief",next_state:{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:c}},u={...e,read_session:l},f=y=>{l.spent_this_call_tokens=y,l.charged_this_call_tokens=Math.min(t.token_budget-t.spent_tokens,y),l.spent_total_tokens=Math.min(t.token_budget,t.spent_tokens+l.charged_this_call_tokens),l.remaining_tokens=Math.max(0,t.token_budget-l.spent_total_tokens),l.exhausted=l.remaining_tokens<$s,l.next_state.spent_tokens=l.spent_total_tokens},m=0,_=0;for(let y=0;y<8;y+=1){f(m);let w=sn(u,r);if(w===m)return u;_=Math.max(_,w),m=w}return f(_),u}function Cu(e){return Math.max(0,e.token_budget-e.spent_tokens)}(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]="1cc0fcb7-2aaa-5233-bdfd-4b4d0fb3e9c1")}catch{}})();var an=Symbol.for("pm.readOutputInvocationProvenance");function fD(e,t){return Reflect.set(e,an,{canonical_include_modes:[...t],explicit_legacy_aliases:[],sdk_invocation_observed:!0}),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]="d8782989-f417-515e-892a-17ae8ff2b5fa")}catch{}})();var St=["include","amount","cost","encoding"],ju=["canonical","legacy","intent","default"],dn=io,CD=Object.freeze(St.map(e=>dn[e])),RD=so,Lu={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],cost:["--token-budget"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}},Fu=new Set(["--collapse","--fields","--section"]),zs=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--collapse":"--collapse retains dependency grouping semantics; --output-include does not replace it.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--no-truncate":"--no-truncate is a compatibility alias; prefer --output-limit unbounded --output-budget unbounded.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding.","--unbounded":"--unbounded is a compatibility alias; prefer --output-limit unbounded."});function Us(e){return e.slice(2).replaceAll("-","_")}function Xw(e,t){let r=zs[e];if(r!==void 0)return r;let n=t==="include"?Fu.has(e)?"<csv>":Us(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${dn[t]} ${n}.`}function zu(e){let t=Lu[e]??{},r=Object.freeze(Object.fromEntries(St.map(n=>[n,Object.freeze({dimension:n,canonical_option:dn[n],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[n]??[]).map(o=>Object.freeze({flag:o,semantics:zs[o]===void 0?"replacement":"behavior_preserving",migration_hint:Xw(o,n),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:r,precedence:ju,budget_retention_policy:e==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...Hu(e).keys()])})}var Jw=Object.freeze(Yt.map(zu)),Zw=new Map(Jw.map(e=>[e.command,e]));function dr(e,t={}){let r=Nr(e.trim().toLowerCase()),n=Ps(r);return n!==void 0?n.read_output===void 0?void 0:`extension:${n.command}`:Qw(r,t)}function Qw(e,t){let r=e==="package catalog"||e==="packages catalog"||e==="package-catalog"||(e==="package"||e==="packages"||e==="extension")&&(t.catalog===!0||t.target==="catalog"||t.action==="catalog")?"package-catalog":e==="package manage"||e==="package-manage"?"package-manage":e.split(" ")[0],n=r.startsWith("list-")?"list":r==="ctx"?"context":r;return Yt.includes(n)?n:void 0}var ev=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],tv={comments:["add","body","stdin","file","edit","delete"],notes:["add","addJson","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function rv(e){return ev.some(t=>t!=="outputFormat"&&t!=="output_format"&&e[t]!==void 0)}var nv=[{keys:["outputInclude","output_include"],valid:e=>cn(e)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:e=>e==="unbounded"||cr(e)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:e=>e==="unbounded"||cr(e)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:e=>(Ro(e),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:e=>typeof e=="string"&&e.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}];function xD(e,t){let r=t.outputFormat??t.output_format;if(r!==void 0&&r!=="json"&&r!=="toon")throw new g("--output-format must be toon or json.",h.USAGE);if(!rv(t))return;let n=dr(e,t);if(!n)throw new g(`Universal output controls apply only to read commands; ${e||"this command"} is not a read surface.`,h.USAGE);if((tv[n]??[]).some(o=>t[o]!==void 0&&t[o]!==!1))throw new g(`Universal output controls cannot be combined with a ${n} mutation.`,h.USAGE);for(let o of nv){let i=o.keys.map(s=>t[s]).find(s=>s!==void 0);if(i!==void 0&&!o.valid(i))throw new g(o.message,h.USAGE)}}function Uu(e){let t=dr(e);return t?Hu(t):new Map}function Hu(e){return new Map((Lu[e]?.include??[]).filter(t=>!Fu.has(t)&&zs[t]===void 0).map(t=>[Us(t),qu(t)]))}function ov(e,t,r){let n=cn(t)??[],o=Uu(e),i=[],s=[],a=r,c=a[an],d=new Set(c?.canonical_include_modes??[]),l=new Set(c?.explicit_legacy_aliases??[]);for(let m of n){let _=o.get(m);if(_===void 0){i.push(m);continue}let y=`--${m.replaceAll("_","-")}`;qs(Hs(r,y))&&l.add(y),r[_]=!0,s.push(m),d.add(m)}let u=dr(e)==="get"?i.filter(m=>m!=="item"):[],f=u.length>0;return f&&(r.fields=[...new Set([...cn(r.fields)??[],...u])].join(","),d.add("fields")),(s.length>0||f)&&(a[an]={canonical_include_modes:[...d],explicit_legacy_aliases:[...l],...c?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors:i,modes:s}}function ND(e,t){let r=t.outputInclude??t.output_include;if(r===void 0)return;let{selectors:n,modes:o}=ov(e,r,t);if(o.length===0)return;let i=n.length>0?n.join(","):void 0;t.outputInclude=i,Object.hasOwn(t,"output_include")&&(t.output_include=i)}function qu(e){return e.slice(2).replace(/-([a-z])/gu,(t,r)=>r.toUpperCase())}function Hs(e,t){let r=qu(t);if(Object.hasOwn(e,r))return e[r];let n=t.slice(2).replaceAll("-","_");if(Object.hasOwn(e,n))return e[n];if(t==="--no-truncate"&&e.truncate===!1)return!0}function qs(e){return e!==void 0&&e!==!1&&e!==null}function cn(e){let t=(Array.isArray(e)?e:[e]).flatMap(r=>typeof r=="string"?r.split(","):[]).map(r=>r.trim()).filter(Boolean);return t.length>0?[...new Set(t)]:void 0}function cr(e){let t=typeof e=="number"?e:typeof e=="string"&&/^\d+$/u.test(e.trim())?Number(e):Number.NaN;return Number.isSafeInteger(t)&&t>0?t:void 0}function iv(e,t,r,n){for(let o of e.legacy_aliases){if(n(o.flag))continue;let i=Hs(t,o.flag),s={value:i,flag:o.flag};if(qs(i)&&r(s))return s}}function Ru(e,t){let r=cn(e);if(r)return{source:"canonical",value:r};if(t)return{source:"legacy",value:cn(t.value)??[Us(t.flag)]}}function xu(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let r=cr(e);if(r!==void 0)return{source:"canonical",value:r};if(!t)return;if(t.flag==="--no-truncate"||t.flag==="--unbounded")return{source:"legacy",value:"unbounded"};let n=cr(t.value);return n===void 0?void 0:{source:"legacy",value:n}}function Nu(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let r=cr(e);if(r!==void 0)return{source:"canonical",value:r};if(!t)return;let n=cr(t.value);return n===void 0?void 0:{source:"legacy",value:n}}function Du(e,t){if(e==="json"||e==="toon")return{source:"canonical",value:e};if(t)return t.flag==="--stream"||t.flag==="--follow"?{source:"legacy",value:"stream"}:t.value==="json"||t.value==="toon"?{source:"legacy",value:t.value}:void 0}function Vu(e,t,r){if(!e)return!1;let n=new Set(e.explicit_legacy_aliases);if(e.cli_invocation_observed===!0||e.sdk_invocation_observed===!0)return!n.has(r);let o=new Set(e.canonical_include_modes.map(i=>`--${i.replaceAll("_","-")}`));return t==="include"&&o.has(r)&&!n.has(r)}function sv(e,t,r,n){return e.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||qs(Hs(n,"--no-truncate"))&&!Vu(r,"amount","--no-truncate")||t.amount?.flag==="--no-truncate"||t.include?.flag==="--full"||r?.canonical_include_modes.includes("full")===!0}function av(e,t){return St.flatMap(r=>e[r]?.source==="canonical"||r==="include"&&(t?.canonical_include_modes.length??0)>0?[dn[r]]:[])}function Bu(e,t){let r=dr(e,t);if(!r)return;let n=Zw.get(r)??zu(r),o=t[an],i={include:v=>Ru(void 0,v),amount:v=>xu(void 0,v),cost:v=>Nu(void 0,v),encoding:v=>Du(void 0,v)},s=Object.fromEntries(St.map(v=>[v,iv(n.dimensions[v],t,C=>i[v](C)!==void 0,C=>Vu(o,v,C))])),a=St.flatMap(v=>{let C=s[v];return C?[C.flag]:[]}),c=St.flatMap(v=>{let C=s[v];return C?[n.dimensions[v].legacy_aliases.find(K=>K.flag===C.flag).migration_hint]:[]}),d=Du(t.outputFormat??t.output_format,s.encoding),l=Ru(t.outputInclude??t.output_include,s.include),u=xu(t.outputLimit??t.output_limit,s.amount),f=Nu(t.outputBudget??t.output_budget,s.cost),m=sv(e,s,o,t),_=ku(e,{generateFallback:!0}),y=d?.value==="json"||t.resolvedOutputFormat==="json"?"json":"toon",w=f??(m?{source:"intent",value:"unbounded"}:{source:"default",value:_.default_max_estimated_tokens_by_format[y]});return{command:r,include:l,amount:u,cost:w,encoding:d,canonical_options_used:av({include:l,amount:u,cost:w,encoding:d},o),legacy_aliases_used:a,migration_hints:c,precedence:ju}}function Q(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Vs=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),cv=["collection_counts","notes_count","tests_count"];function Wu(e,t){let r=new Set(t.map(n=>n.split(".")[0]));return Object.fromEntries(Object.entries(e).filter(([n])=>r.has(n)))}function dv(e){let t=Q(e.item)?e.item:{},r=[...new Set([...Object.keys(t),...cv.filter(o=>Object.hasOwn(t,o))])].sort((o,i)=>o.localeCompare(i)),n=Object.keys(e).filter(o=>o!=="item"&&o!=="read_output"&&!Vs.has(o)).sort((o,i)=>o.localeCompare(i));return{item:t,itemFields:r,sections:n,valid:[...r,"item",...r.map(o=>`item.${o}`),...n]}}function lv(e,t){let r=dv(e),n=t.filter(l=>!r.valid.includes(l));if(n.length>0)throw new g(`Unknown --output-include selector(s) for get: ${n.join(", ")}. Valid selectors: ${r.valid.join(", ")}.`,h.USAGE);let o=t.includes("item"),i=t.flatMap(l=>l.startsWith("item.")?[l.slice(5)]:r.itemFields.includes(l)?[l]:[]).filter((l,u,f)=>f.indexOf(l)===u);if(o&&i.length>0)throw new g("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",h.USAGE);let s=new Set(t.filter(l=>r.sections.includes(l))),a=Object.fromEntries(Object.entries(e).filter(([l])=>Vs.has(l)||s.has(l)));o?a.item=r.item:i.length>0&&(a.item=Wu(r.item,i));let c=[...o?[]:i.length>0?r.itemFields.filter(l=>!i.includes(l)).map(l=>({name:`item.${l}`,restore_with:`--output-include item.${l}`})):[{name:"item",restore_with:"--output-include item"}],...r.sections.filter(l=>!s.has(l)).map(l=>({name:l,restore_with:`--output-include ${l}`}))],d=[...Q(a.omission_receipt)&&Array.isArray(a.omission_receipt.omitted_field_groups)?a.omission_receipt.omitted_field_groups:[],...c];return a.omission_receipt={has_omissions:d.length>0,omitted_field_group_count:d.length,omitted_field_groups:d},a}function Pu(e){let t=0;return rn({...e},r=>(Q(r)&&Object.keys(r).length>0&&(t+=1),r)),t}function uv(e,t,r,n){if(Pu(t)===0||Pu(r)>0)return;let o=[...Uu(e).keys()],i=o.length>0?` Declared ${e} projection modes: ${o.join(", ")}.`:` The ${e} surface declares no projection modes; name row fields instead.`;throw new g(`Unknown --output-include selector(s) for ${e}: ${n.join(", ")}. No selector matched any returned row field.${i}`,h.USAGE)}function fv(e,t,r){if(e==="get")return lv(t,r);let n=Oo(t),o=r.flatMap(s=>n.flatMap(a=>s.startsWith(`${a}.`)?[s.slice(a.length+1)]:[])),i=r.some(s=>Object.hasOwn(t,s.split(".")[0])&&!n.some(a=>s.startsWith(`${a}.`)));if(n.length>0&&(!i||o.length>0)){let s={...t},a=o.length>0?o:r,c=rn(s,d=>Q(d)?Wu(d,a):d);return uv(e,t,c,a),c}return Object.fromEntries(Object.entries(t).filter(([s])=>r.some(a=>a.split(".")[0]===s)||Vs.has(s)))}function mv(e,t){if(t==="unbounded")return e;let{result:r,truncated:n}=uu(e,t);if(!n)return r;if(r.has_more=!0,r.truncated=!0,typeof r.count=="number"){let o=Q(r.projection)?r.projection.row_key:void 0;r.count=typeof o=="string"&&Array.isArray(r[o])?r[o].length:Ao(r)}return r.applied_bound={kind:"output_limit",source:"explicit",value:t},r}function pv(e){return St.filter(t=>e[t]!==void 0&&e[t]?.source!=="default"||e.canonical_options_used.includes(dn[t]))}function Gu(e){let t=e.resolvedOutputFormat??e.outputFormat??e.output_format??e.format;return t==="json"||t==="toon"?t:void 0}function xo(e,t,r,n){let o=Ls(e,t,n);ar(e,o);for(let i=0;i<8;i+=1){let s=r.estimated_tokens,a=o.read_session.spent_this_call_tokens;Ye(o,r,n);let c=o;o=Ls(o,t,n),ar(c,o);let d=o.read_session.spent_this_call_tokens;if(r.estimated_tokens===s&&d===a)return o}return o}function Bs(e,t){if(!Q(e.read_output))return e;let r=Gu(t),n=e.read_output,o=Ro(t.outputSession??t.output_session);return o===void 0?(Ye(e,n,r),e):xo(e,o,n,r)}function _v(e,t){if(e!=="validate")return t;let r=Q(t.projection)?t.projection:void 0;if(!(Array.isArray(r?.declared_field_groups)?r.declared_field_groups:[]).some(l=>Q(l)&&l.name==="diagnostic_rows"))return t;let n=[...new Set(tn(t).map(({path:l})=>l).filter(l=>/^checks\.\d+\.details\./u.test(l)))],o=n.filter(l=>!n.some(u=>u!==l&&l.startsWith(`${u}.`)));if(o.length===0)return t;let i=Q(t.row_contract)?t.row_contract:{},s=Array.isArray(i.row_keys)?i.row_keys.filter(l=>typeof l=="string"):[],a=Array.isArray(i.continuation_row_keys)?i.continuation_row_keys.filter(l=>typeof l=="string"):[],c=s.length>0?s:o,d=[...new Set(o)];return JSON.stringify(c)===JSON.stringify(s)&&JSON.stringify(d)===JSON.stringify(a)?t:{...t,row_contract:{...i,row_keys:c,continuation_row_keys:d,jq_selector:typeof i.jq_selector=="string"?i.jq_selector:".checks[].details"}}}function yv(e,t,r,n,o){let i={...e};if(t.include?.source==="canonical"&&(i=fv(t.command,i,t.include.value)),t.command==="assurance"&&(i=rf(i)),nn(i,e),i=nf(i,t.command,n),t.command==="history"&&n){let c=["compact_history","provenance_history","history","diff"];if(i=Object.fromEntries(Object.entries(i).filter(([d])=>!c.includes(d)||d===n.path)),Q(i.projection)&&(i.projection={...i.projection,row_key:n.path}),Q(i.row_contract)){let d=i.row_contract;i.row_contract={...d,row_keys:[n.path],...Array.isArray(d.continuation_row_keys)?{continuation_row_keys:[n.path]}:{}}}i.count=Object.keys(i[n.path]).length}let s=e.count_only===!0?{...i,count_only:!0,count:e.count}:i,a=Ev(i,e,t.command,n,o);return t.amount?.source==="canonical"&&(i=mv(i,t.amount.value),a.cursorContinuesExistingPage&&Ju(i,a.originalItems,a.cursorSource,!0,a.originalItemOffset)),nn(i,s),{projected:r===void 0?i:Tu(i,r),continuationState:a}}function hv(e,t){return[...e.cost!==void 0&&e.cost.value!=="unbounded"&&(e.cost.source==="canonical"||e.cost.source==="default"||e.command==="context"&&e.cost.source==="legacy")?[{source:e.cost.source,tokens:e.cost.value}]:[],...t===void 0?[]:[{source:"session",tokens:Cu(t)}]].sort((r,n)=>r.tokens-n.tokens)[0]}function Ku(e){let t=e.canonical_options_used;return t&&t.length>0?{canonical_options_used:t}:{}}function Yu(e,t){return Q(e.context_intent)&&e.context_intent.command==="context"&&e.context_intent.token_budget===t&&e.context_intent.within_budget===!0}function Xu(e,t={}){return e?.source==="default"||e?.source==="legacy"&&!Yu(t,e.tokens)?{budget_source:e.source,budget_tokens:e.tokens}:{}}function gv(e,t,r,n,o,i){let s={contract_version:1,command:e.command,requested_dimensions:t,...Xu(n),precedence:e.precedence,...Ku(e),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...r===void 0?{omitted_result_estimated_tokens:o}:{}},a={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:s},c=r===void 0?a:xo(a,r,s,i);if(r===void 0&&Ye(c,s,i),r!==void 0&&s.estimated_tokens>n.tokens)throw new g("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",h.USAGE);return c}function bv(e,t,r){return e.command==="context"&&e.cost?.source==="legacy"&&!Yu(r,e.cost.value)||t.outputRowContract===!0||t.output_row_contract===!0||e.canonical_options_used.includes("--output-include")||e.command==="list"&&e.canonical_options_used.length>0&&e.include?.value.includes("full")===!0}function wv(e,t,r,n,o){if(t!==void 0||bv(e,o,r))return!1;if(e.amount?.source==="canonical"&&e.amount.value!=="unbounded"){let i=e.amount.value;if(Ge(r).some(({value:s})=>(Array.isArray(s)?s.length:Object.keys(s).length)>i))return!1}return e.cost===void 0||e.cost.value==="unbounded"||e.cost.source==="legacy"&&e.command!=="context"||sn(o.outputRowContract===!1?Object.fromEntries(Object.entries(r).filter(([i])=>i!=="row_contract")):r,n)<=e.cost.value}function vv(e,t,r,n,o,i,s){if(!r.rows_compacted)return;let a=t.amount?.value==="unbounded"?["amount"]:[],c=new Map(ir(e).map(_=>[_.path,Array.isArray(_.value)?_.value.length:Object.keys(_.value).length])),d=[...s.entries()].flatMap(([_,y])=>{let w=c.get(_);if(w>=y.rows)return[];let v=y.baseOffset+w;return[{path:_,cursor:Ws({command:t.command,path:_,offset:v,total_rows:y.totalRows,fingerprint:y.fingerprint}),retained_rows:w,remaining_rows:y.totalRows-v,total_rows:y.totalRows}]}),l=d[0],u=l?"; page --output-cursor":"",f=n.source==="session"?`Truncated by the remaining ${n.tokens}-token session budget; start a new output session with a larger token_budget${u}.`:`${n.tokens}-token: raise --output-budget${u}`;r.migration_hints=[f,...t.migration_hints];let m=Fs({effective_budget_tokens:n.tokens,measured_result_tokens:i});l&&!o&&(typeof e.next_cursor!="string"||e.continuation_kind==="output_cursor")&&(e.next_cursor=l.cursor),e.continuation_kind=o?"producer_cursor":l?"output_cursor":"none",e.output_budget_truncation={reason:"output_budget_reached",budget_source:n.source,budget_tokens:n.tokens,overridden_dimensions:a,compacted_row_paths:r.compacted_row_paths,continuation_cursor_rebased:o,continuation_available:d.length>0,recovery_budget_multiplier:l?1:m.recovery_budget_multiplier,continuations:d,restore_with:l?"recovery":`Retry with --output-budget ${m.output_budget} because no declared row collection can be continued.`,recovery:l?{cursor:l.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${m.output_budget}`,sdk:{outputBudget:m.output_budget},mcp:{outputBudget:m.output_budget}}}}function Ju(e,t,r,n,o){if(typeof r!="string"||!Array.isArray(e.items))return!1;let i=e.items.length,s=t.length;if(i===0||i>=s)return!1;let a;try{a=Gs(r)}catch{return!1}let c=a.after_index;if(c===void 0)return!1;let d=t[i-1];if(Object.prototype.toString.call(d)!=="[object Object]")return!1;let l=Reflect.get(d,"id");if(typeof l!="string"||l.length===0)return!1;let u=n?c-(s-i):c+o+i;return u<0?!1:(e.next_cursor=un(a.fingerprint,l,u,a.snapshot),!0)}function Ev(e,t,r,n,o){let i=new Map(ir(e).map(c=>{let d=Array.isArray(c.value)?c.value.length:Object.keys(c.value).length,l=n?.path===c.path;return[c.path,{rows:d,totalRows:l?n.total_rows:d,baseOffset:l?n.offset:0,fingerprint:l?n.fingerprint:No(c.path,c.value,r)}]})),s=typeof e.next_cursor=="string",a=n?.path==="items"?n.offset:0;return{collectionsBeforeBudget:i,originalItems:Array.isArray(t.items)?a>0?t.items.slice(a):t.items:[],originalItemOffset:a,cursorContinuesExistingPage:s,cursorSource:s?e.next_cursor:o.after}}function kv(e,t,r,n,o,i,s,a,c,d){let l={...t,count_only:r},u=n.command==="assurance"&&Array.isArray(e.assertions)?e.assertions.filter(m=>Q(m)&&m.verdict!=="pass").length:0,f=new Map;if(u>0&&f.set("assertions",u),n.command==="history"&&Array.isArray(e.diff))for(let m of tn(e))m.path.startsWith("diff.")&&f.set(m.path,Object.keys(m.value).length);return $u(e,o,i.tokens,f,d,m=>{nn(m,l);let _=Ju(m,a.originalItems,a.cursorSource,a.cursorContinuesExistingPage,a.originalItemOffset);if(vv(m,n,o,i,_,c,a.collectionsBeforeBudget),n.command==="history"&&Q(m.projection)){m.has_more=typeof m.next_cursor=="string"||m.applied_bound?.kind==="output_limit";let y=m.projection.row_key;typeof y=="string"&&Array.isArray(m[y])&&(m.count=m[y].length)}s!==void 0&&Object.assign(m,xo(m,s,o,d))},n.command==="history"&&Array.isArray(e.diff))}function Zu(e,t,r){let n=Bu(e,t);if(!n)return r;let o=Gu(t),i=Ro(t.outputSession??t.output_session),s=t.outputCursor??t.output_cursor,a=typeof s=="string"?ln(s):void 0,c=pv(n),d=_v(n.command,r);if(a===void 0&&wv(n,i,d,o,t))return d;let l=hv(n,i),u=yv(d,n,i,a,t),f=u.projected;ar(f,f,t.outputRowContract===!1);let m={contract_version:1,command:n.command,requested_dimensions:c,...Xu(l,f),precedence:n.precedence,...Ku(n),legacy_aliases_used:n.legacy_aliases_used,migration_hints:n.migration_hints,estimated_tokens:0,within_budget:!0,strings_compacted:!1,rows_compacted:!1,result_omitted:!1};if(f.read_output=m,f=i===void 0?f:xo(f,i,m,o),Ye(f,m,o),l!==void 0&&m.estimated_tokens>l.tokens){let _=Mu(n.command,t,f);_!==void 0&&(m.applied_depth="brief",m.degradation_reason="output_budget_reached",ar(f,_),f=Bs(_,t)),m.estimated_tokens>l.tokens&&(f=kv(f,f,d.count_only===!0,n,m,l,i,u.continuationState,m.estimated_tokens,o))}return l!==void 0&&m.estimated_tokens>l.tokens?gv(n,c,i,l,m.estimated_tokens,o):f}function Qu(e){return Q(e)&&Q(e.output_budget_exceeded)&&e.output_budget_exceeded.omitted_result===!0&&e.output_budget_exceeded.reason==="requested_budget_infeasible"}function ef(e,t){let r=t.outputFormat??t.output_format;if(r==="json"||r==="toon")return r;let n=Bu(e,t)?.encoding;return n?.value==="json"||n?.value==="toon"?n.value: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]="f7f59eaa-9d5d-5797-99de-e672fdfba99d")}catch{}})();var Ov=4096,Av=Object.freeze(["queue_draining","queue_entries","queue_exists","queue_high_retry_entries","queue_invalid_rows","queue_max_attempts","queue_rows_total","queue_size_bytes","pending_otel_spans","last_attempted_flush_at","last_failed_flush_at","last_otel_attempt_at","last_otel_failure_at","last_otel_success_at","last_successful_flush_at"]),tf=Object.freeze({health:Object.freeze({version:3,paths:Object.freeze(["checks"]),ignored_detail_field_names_by_row:Object.freeze({telemetry:Av}),guarantee:"nonvolatile_snapshot_and_stable_configuration"})});function mn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fn(e){return Array.isArray(e)?e.map(fn):mn(e)?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,fn(r)])):e}function of(e,t){if(!mn(e))return fn(e);let r=typeof e.name=="string"?e.name:void 0,n=r!==void 0&&Object.hasOwn(t.ignored_detail_field_names_by_row,r)?t.ignored_detail_field_names_by_row[r]:void 0;return Object.fromEntries(Object.entries(e).map(([o,i])=>o!=="details"||!n||!mn(i)?[o,fn(i)]:[o,Object.fromEntries(Object.entries(i).filter(([s])=>!n.includes(s)).map(([s,a])=>[s,fn(a)]))]))}function Iv(e,t){return Array.isArray(e)?e.map(r=>of(r,t)):of(e,t)}function No(e,t,r){let n=r?tf[r]:void 0,o=n?.paths.includes(e)===!0;return Sv("sha256").update(R({path:e,value:o?Iv(t,n):t,...o?{fingerprint_policy_version:n.version}:{}})).digest("base64url").slice(0,16)}function Ws(e){return Buffer.from(JSON.stringify({v:1,c:e.command,p:e.path,o:e.offset,n:e.total_rows,f:e.fingerprint}),"utf8").toString("base64url")}function Tv(e){return typeof e=="string"&&(dr(e)===e||/^extension:\S(?:[^\r\n]*\S)?$/u.test(e))}function ln(e){if(e.length>Ov)throw new g("The read-output continuation cursor is malformed or unsupported.",h.USAGE,{code:"read_output_cursor_invalid"});let t;try{t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{t=null}if(!mn(t)||t.v!==1||!Tv(t.c)||typeof t.p!="string"||t.p.length===0||!Number.isSafeInteger(t.o)||t.o<0||!Number.isSafeInteger(t.n)||t.n<1||typeof t.f!="string"||t.f.length===0)throw new g("The read-output continuation cursor is malformed or unsupported.",h.USAGE,{code:"read_output_cursor_invalid"});return{version:1,command:t.c,path:t.p,offset:t.o,total_rows:t.n,fingerprint:t.f}}function rf(e){if(!Array.isArray(e.assertions))return e;let t=r=>!mn(r)||r.verdict==="pass"?4:r.verdict==="retired"?3:r.enforcement==="block"?0:r.enforcement==="warn"?1:2;return{...e,assertions:e.assertions.map((r,n)=>({row:r,index:n})).sort((r,n)=>t(r.row)-t(n.row)||r.index-n.index).map(({row:r})=>r),budget_retention_policy:"verdict_priority"}}function nf(e,t,r){if(!r)return e;if(r.command!==t)throw new g(`The read-output cursor belongs to ${r.command}, not ${t}.`,h.USAGE,{code:"read_output_cursor_command_mismatch"});let n=ir(e).find(i=>i.path===r.path),o=n?Array.isArray(n.value)?n.value.length:Object.keys(n.value).length:0;if(!n||o!==r.total_rows||r.offset>o||No(r.path,n.value,t)!==r.fingerprint)throw new g("The read-output continuation no longer matches the declared row collection; restart the bounded read.",h.USAGE,{code:"read_output_cursor_stale"});return lu(e,r.path,r.offset)}(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]="b6a81cf4-3095-5197-8e73-f017d98b1ccf")}catch{}})();var Ys=1,sf=4096,Rv=/^[A-Za-z0-9_-]+$/;function Ks(e){return e.replace(/^--/u,"").replace(/[-_]([a-z0-9])/gu,(t,r)=>r.toUpperCase())}function GD(e,t){let r=[...Object.values(io),...so],n=new Set(r.flatMap(o=>[Ks(o),o.slice(2).replaceAll("-","_")]));for(let o of t)if(o.cursor_semantics==="presentation"){n.add(Ks(o.flag));for(let i of o.aliases??[])n.add(Ks(i))}return Object.fromEntries(Object.entries(e).filter(([o])=>!n.has(o)))}function KD(e,t){return Cv("sha256").update(e).update("\0").update(R(t)).digest("hex").slice(0,24)}function un(e,t,r,n){return Buffer.from(JSON.stringify({version:Ys,fingerprint:e,after_id:t,...r===void 0?{}:{after_index:r},...n===void 0?{}:{snapshot:n}})).toString("base64url")}function Ot(e,t){return new g(e,h.USAGE,{code:"invalid_query_cursor",nextSteps:[`Repeat the original query without ${t} to obtain a fresh cursor.`]})}function xv(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return t.version===Ys&&typeof t.fingerprint=="string"&&typeof t.after_id=="string"&&t.after_id.length>0&&(t.after_index===void 0||Number.isSafeInteger(t.after_index)&&t.after_index>=0)&&(t.snapshot===void 0||typeof t.snapshot=="string"&&t.snapshot.length>0)}function Gs(e,t="--after"){if(typeof e!="string")throw Ot("Query cursor is malformed.",t);let r=e.trim();if(r.length===0||r.length>sf||!Rv.test(r))throw Ot("Query cursor is malformed.",t);let n;try{n=JSON.parse(Buffer.from(r,"base64url").toString("utf8"))}catch{throw Ot("Query cursor is malformed.",t)}if(!xv(n)){let o=!1;try{ln(r),o=!0}catch{}throw o?new g(`An output cursor must be continued with --output-cursor, not ${t}.`,h.USAGE,{code:"invalid_query_cursor",nextSteps:[`Repeat the same query, replacing ${t} with --output-cursor ${r}; retain any producer ${t} cursor from the original page.`]}):Ot("Query cursor version or payload is unsupported.",t)}return n}function Xs(e,t,r="--after"){let n=Gs(e,r);if(n.fingerprint!==t)throw Ot(`Query cursor does not match the current filters, sort, or query (${n.fingerprint} != ${t}).`,r);return{after_id:n.after_id,...n.after_index===void 0?{}:{after_index:n.after_index},...n.snapshot===void 0?{}:{snapshot:n.snapshot}}}function YD(e,t){return Xs(e,t).after_id}function Nv(e,t,r,n,o="--after"){if(t===void 0)return 0;let i=Xs(t,r,o),s=e.findIndex(a=>n(a)===i.after_id);if(s<0){if(i.after_index!==void 0)return Math.min(i.after_index,e.length);throw Ot(`Query cursor item ${i.after_id} is no longer present in this result set.`,o)}return s+1}function XD(e,t){if(t.cursor!==void 0&&Xs(t.cursor,t.fingerprint).snapshot!==t.snapshot)throw Ot("Query cursor does not match the requested snapshot.","--after");let r=Nv(e,t.cursor,t.fingerprint,t.readId),n=e.slice(r,r+t.limit),o=n.length>0&&r+n.length<e.length,i=n.at(-1);return{rows:n,has_more:o,...o&&i!==void 0?{next_cursor:un(t.fingerprint,t.readId(i),r+n.length-1,t.snapshot)}:{}}}var JD=Object.freeze({version:Ys,max_length:sf});import{randomUUID as AE}from"node:crypto";import{randomUUID as EE}from"node:crypto";import{constants as fr}from"node:fs";import{lstat as Cf,mkdir as kE,open as xf,rename as SE,rm as OE}from"node:fs/promises";import $o from"node:path";import{constants as nE}from"node:fs";import ae from"node:fs/promises";import Je from"node:path";import{randomUUID as Mo}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]="92573990-a040-526d-a0b1-b91d2ef401f1")}catch{}})();function Do(e){let t=Math.ceil(e.size/2);for(let r of e.keys()){if(t===0)return;e.delete(r),t-=1}}import Dv from"node:crypto";import{AsyncLocalStorage as Pv}from"node:async_hooks";(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]="ced47074-06d3-53b9-af75-63586cbd4f6a")}catch{}})();var Js=new Pv,af=1024;function Mv(e){let t=Date.parse(e.clock);if(!Number.isFinite(t))throw new Error(`Invalid reproducible workspace clock: ${e.clock}`);if(!Number.isSafeInteger(e.tickMs)||e.tickMs<0)throw new Error("Reproducible workspace tickMs must be a non-negative integer");if(e.seed.trim().length===0)throw new Error("Reproducible workspace seed must not be empty");return{...e,clock:new Date(t).toISOString()}}function $v(e){let t={...Mv(e),clockReads:0,tokenReads:0};return r=>Js.run(t,r)}async function rP(e,t){return $v(e)(t)}function cf(){let e=Js.getStore();if(e===void 0)return;let t=new Date(Date.parse(e.clock)+e.clockReads*e.tickMs).toISOString();return e.clockReads+=1,t}function nP(e){let t=Js.getStore();if(t===void 0)return;if(!Number.isSafeInteger(e)||e<0||e>af)throw new Error(`Reproducible token length must be an integer between 0 and ${af}`);let r="";for(;r.length<e;){let n=Dv.createHash("sha256").update(`${t.seed}\0${t.tokenReads}`).digest();t.tokenReads+=1;for(let o of n)if(r+=(o%36).toString(36),r.length===e)break}return 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]="0bf155fc-c690-5318-ba1e-275f1787858b")}catch{}})();var jv=/^([+-]?)(\d+)([hdwm])$/i,Lv=/^[+-]?\d+[hdwm](?:[+-]\d+[hdwm])+$/i,Fv=/^(\d{4})(\d{2})(\d{2})$/,zv=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Uv=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})-(\d{2})(?:-(\d{2}))?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Hv=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,qv=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function Ie(){return cf()??new Date().toISOString()}function je(e){return Number.isFinite(Date.parse(e))}function pn(e){let t=qv.exec(e);if(!t||!Number.isFinite(Date.parse(e)))return!1;let[,r,n,o,i,s,a,c,d]=t,[l,u,f,m,_,y]=[r,n,o,i,s,a].map(Number);return u>=1&&u<=12&&f>=1&&f<=ea(l,u-1)&&m<=23&&_<=59&&y<=59&&(c===void 0||Number(c)<=23)&&(d===void 0||Number(d)<=59)}function lr(e){let t=/\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/iu.exec(e)?.[1];return pn(e)&&(t===void 0||/^\d{0,3}0*$/u.test(t))}var Vv=1e4,Po=new Map;function df(e){let t=Po.get(e);if(t!==void 0)return t;let r=Date.parse(e);return Po.size>=Vv&&Do(Po),Po.set(e,r),r}function ne(e,t){let r=df(e),n=df(t);return Number.isFinite(r)&&Number.isFinite(n)&&r!==n?r-n:e.localeCompare(t)}function dP(e,t){return!(t.deadlineBefore&&(!e.deadline||ne(e.deadline,t.deadlineBefore)>0)||t.deadlineAfter&&(!e.deadline||ne(e.deadline,t.deadlineAfter)<0)||t.updatedAfter&&ne(e.updated_at,t.updatedAfter)<0||t.updatedBefore&&ne(e.updated_at,t.updatedBefore)>0||t.createdAfter&&ne(e.created_at,t.createdAfter)<0||t.createdBefore&&ne(e.created_at,t.createdBefore)>0)}function Zs(e){return e?`.${e.slice(1).padEnd(3,"0").slice(0,3)}`:""}function Qs(e){if(!e)return"";if(e.toUpperCase()==="Z")return"Z";let t=/^([+-]\d{2})(\d{2})$/.exec(e);return t?`${t[1]}:${t[2]}`:e}function Bv(e,t,r){r&&r!==t&&(e.includes(r)||e.push(r))}function Wv(e){let t=[],r=d=>Bv(t,e,d),n=Fv.exec(e);if(n){let[,d,l,u]=n;r(`${d}-${l}-${u}`)}let o=zv.exec(e);if(o){let[,d,l,u,f,m,_,y,w]=o,v=_?`:${_}`:"";r(`${d}-${l}-${u}T${f}:${m}${v}${Zs(y)}${Qs(w)}`)}let i=Uv.exec(e);if(i){let[,d,l,u,f,m,_]=i,y=f?`:${f}`:"";r(`${d}T${l}:${u}${y}${Zs(m)}${Qs(_)}`)}let s=Hv.exec(e);if(s){let[,d,l,u,f,m,_]=s,y=f?`:${f}`:"";r(`${d}T${l}:${u}${y}${Zs(m)}${Qs(_)}`)}let a=10,c=e.slice(0,a);if(Kv(c)){let d=a;for(;d<e.length&&Yv(e[d]);)d+=1;d<e.length&&r(`${c}T${e.slice(d)}`)}return t}function Gv(e){let t=Date.parse(e);if(Number.isFinite(t))return t;for(let r of Wv(e)){let n=Date.parse(r);if(Number.isFinite(n))return n}return Number.NaN}function Kv(e){if(e.length!==10)return!1;for(let t=0;t<e.length;t+=1){let r=e[t];if(t===4||t===7){if(r!=="-")return!1;continue}let n=r.charCodeAt(0);if(n<48||n>57)return!1}return!0}function Yv(e){return e?e===" "||e===" "||e===`
8
- `||e==="\r"||e==="\f"||e==="\v":!1}function ea(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}var Xv=["January","February","March","April","May","June","July","August","September","October","November","December"],Jv=/^(\d{4})-(\d{2})-(\d{2})/,Zv=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/;function Qv(e,t,r){let n=Jv.exec(t)??Zv.exec(t);if(!n)return;let o=Number.parseInt(n[1],10),i=Number.parseInt(n[2],10),s=Number.parseInt(n[3],10),a=r?.trim()||"deadline";if(i<1||i>12)throw new g(`Invalid ${a} value "${e}". Month "${n[2]}" is out of range \u2014 use a month between 01 and 12.`,h.USAGE,{field:a,value:e});let c=ea(o,i-1);if(s<1||s>c)throw new g(`Invalid ${a} value "${e}". ${Xv[i-1]} ${o} has ${c} days, so day "${n[3]}" does not exist. Use a real YYYY-MM-DD calendar date.`,h.USAGE,{field:a,value:e})}function eE(e,t){let r=new Date(e.getTime()),n=r.getUTCDate(),o=r.getUTCMonth()+t,i=r.getUTCFullYear()+Math.floor(o/12),s=(o%12+12)%12,a=Math.min(n,ea(i,s));return r.setUTCFullYear(i,s,a),r}function lP(e,t=new Date,r="deadline"){let n=e.trim();if(n.toLowerCase()==="now")return t.toISOString();let o=jv.exec(n);if(o){let s=o[1]==="-"?-1:1,a=Number.parseInt(o[2],10)*s,c=o[3].toLowerCase();if(c==="m")return eE(t,a).toISOString();let d=c==="h"?3600*1e3:c==="d"?1440*60*1e3:10080*60*1e3;return new Date(t.getTime()+a*d).toISOString()}Qv(e,n,r);let i=Gv(n);if(!Number.isFinite(i)){let s=r.trim().length>0?r.trim():"deadline",a=Lv.test(n)?"Compound relative expressions like +3d+1h are not supported; use a single relative token (for example +3d) or an ISO/date string.":'Use ISO/date string input, "now", or relative +6h/-6h/+1d/-1d/+2w/-2w/+6m/-6m.';throw new g(`Invalid ${s} value "${e}". ${a}`,h.USAGE,{field:s,value:e})}return new Date(i).toISOString()}import ta from"node:fs/promises";import{createHash as tE}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]="d1f829a5-70d6-5096-86f7-717440dd67d5")}catch{}})();function lf(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function rE(e){if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!lf(t,"ESRCH")}}function uf(e){let t=e.lastIndexOf(")");if(t<0)return null;let r=e.slice(t+2).trim().split(/\s+/u)[19];return r!==void 0&&/^\d+$/u.test(r)?r:null}async function ur(e){try{return uf(await ta.readFile(`/proc/${e}/stat`,"utf8"))}catch{return null}}async function _n(e=process.pid){let t=await ur(e);return{pid:e,...t===null?{}:{process_start_identity:t}}}async function yn(e,t,r){if(!rE(e.pid))return!1;let n=await ur(e.pid);return e.process_start_identity!==void 0&&n!==null?n===e.process_start_identity:t<=r}async function ff(){try{let[e,t]=await Promise.all([ta.readFile("/proc/sys/kernel/random/boot_id","utf8"),ta.readlink("/proc/self/ns/pid")]);return!/^[a-f0-9-]{36}\s*$/u.test(e)||!/^pid:\[\d+\]$/u.test(t)?null:tE("sha256").update(`${e.trim()}:${t}`).digest("hex")}catch{return null}}async function mf(){let[e,t]=await Promise.all([ff(),ur(process.pid)]);return e!==null&&t!==null?{host_identity:e,process_start_identity:t}:{}}async function ra(e){if(!e||typeof e.pid!="number"||!Number.isSafeInteger(e.pid)||e.pid<=0||typeof e.host_identity!="string"||typeof e.process_start_identity!="string"||!/^\d+$/u.test(e.process_start_identity))return"unknown";let t=await ff();if(t===null||t!==e.host_identity)return"unknown";try{process.kill(e.pid,0)}catch(n){return lf(n,"ESRCH")?"dead":"unknown"}let r=await ur(e.pid);return r===null?"unknown":r===e.process_start_identity?"alive":"dead"}(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]="8aac3d30-44d1-5876-ab56-6dbc2285d28f")}catch{}})();function oE(e){let t;try{t=JSON.parse(e)}catch{return{info:null,warnings:["lock_info_invalid_json"]}}if(typeof t!="object"||t===null||Array.isArray(t))return{info:null,warnings:["lock_info_invalid_shape"]};let r=t,n=r.id,o=r.pid,i=r.owner,s=r.token,a=r.created_at,c=r.ttl_seconds;return typeof n!="string"||typeof o!="number"||!Number.isFinite(o)||typeof i!="string"||s!==void 0&&(typeof s!="string"||s.trim().length===0)||typeof a!="string"||typeof c!="number"||!Number.isFinite(c)?{info:null,warnings:["lock_info_invalid_shape"]}:{info:{id:n,pid:o,owner:i,...typeof s=="string"?{token:s}:{},created_at:a,ttl_seconds:c,host_identity:r.host_identity,process_start_identity:r.process_start_identity},warnings:[]}}async function hn(e,t=!0){try{let r=await ae.readFile(e,"utf8");return t&&await rr({path:e,scope:"project"}),oE(r)}catch(r){return ue(r)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function Xe(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function iE(e,t,r=process.platform){if(Xe(e,"EEXIST"))return!0;if(!Xe(e,"EPERM")&&!Xe(e,"EACCES")&&!Xe(e,"EBUSY"))return!1;try{return await ae.lstat(t),!0}catch(n){if(r!=="win32"||!ue(n)&&!Xe(n,"EPERM")&&!Xe(n,"EACCES")&&!Xe(n,"EBUSY"))return!1}try{return await ae.access(Je.dirname(t),nE.W_OK),!0}catch{return!1}}async function gf(e,t){await vo({path:e,scope:"project",op:t})}async function sE(e,t,r,n=Mo()){return{...await mf(),id:e,pid:process.pid,owner:t,token:n,created_at:Ie(),ttl_seconds:r}}async function aE(e,t,r,n,o,i){i&&await ae.mkdir(Je.dirname(e),{recursive:!0});let s=await aa(e,t);if(s===null)throw await ae.access(Je.dirname(e)),Object.assign(new Error("Lock initialization is contended"),{code:"EEXIST"});try{let a=await ae.open(e,"wx");try{try{await a.writeFile(`${JSON.stringify(await sE(t,r,n,o),null,2)}
9
- `,"utf8")}finally{await a.close()}}catch(c){throw await oa(e,"lock:release"),c}}finally{await s()}await gf(e,"lock:create")}async function oa(e,t){try{return await ae.unlink(e),await gf(e,t),!0}catch{return!1}}async function cE(e,t,r,n){let o=Date.now(),i=kf;for(;;){let s=await aa(e,t);if(s!==null){try{let d=await hn(e,!1);pf(d.info,t,r,n)&&await oa(e,"lock:release")}finally{await s()}return}let a=await hn(e,!1);if(!pf(a.info,t,r,n))return;let c=Date.now()-o;if(c>=_f)return;await Af(Math.min(i,_f-c)),i=Math.min(i*2,ia)}}function pf(e,t,r,n){return e?.id===t&&e.pid===process.pid&&e.owner===r&&e.token===n}function bf(e,t){let r=e?.created_at?Date.parse(e.created_at):Number.NaN;return(Number.isFinite(r)?Date.now()-r:Number.POSITIVE_INFINITY)>t*1e3}async function wf(e){return e!==null&&Number.isFinite(Date.parse(e.created_at))&&await ra(e)==="dead"}async function vf(e,t){return bf(e,t)||await wf(e)}async function Ef(e,t,r){let{info:n}=await hn(Ki(e,t),!1);return n!==null&&n.owner.startsWith(r)&&!await vf(n,n.ttl_seconds)}function dE(e){return e?.owner?` (owner ${e.owner})`:""}var kf=25,ia=200,lE=250,uE=3,fE=".stale-cleanup",Sf="owner.json",Of=1e4,_f=Of+ia,mE=60*6e4;function na(e){if(typeof e=="string"){let t=e.trim();if(!/^\d+$/.test(t))return;let r=Number(t);return Number.isSafeInteger(r)?r:void 0}if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return Math.trunc(e)}function pE(e){let t=process.env.PM_LOCK_WAIT_MS,r=na(t);if(r!==void 0)return r;let n=na(e);return n!==void 0?n:0}function _E(e,t){return Math.min(pE(e),t??1/0)}function Af(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(r=>setTimeout(r,t))}async function If(e,t,r){let n=await ra(t),o=r>0?` after waiting ${r}ms`:"";return new g(`Item ${e} is locked${dE(t)} (owner process ${n})${o}`,h.CONFLICT,{code:"lock_conflict",item_id:e,reason:`lock_owner_${n}`,required:"Wait for the owner to release the lock, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget when contention is expected. Inspect stale receipts with pm gc --scope locks --dry-run.",recovery:{retry_after_ms:lE}})}function yE(e){if(typeof e=="function")return e;if(typeof e=="object"&&e!==null&&"release"in e){let t=e.release;return typeof t=="function"?t:null}return null}function hE(e,t,r,n){if(!r&&n){let o=t.warnings.length>0?` (${t.warnings.join(",")})`:"";throw new g(`Item ${e} lock is stale${o}; rerun with --force when supported for this command`,h.CONFLICT)}}function gE(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let r=t,n=r.pid,o=r.token,i=r.process_start_identity;return typeof n!="number"||!Number.isInteger(n)||n<=0||typeof o!="string"||o.length===0||i!==void 0&&(typeof i!="string"||!/^\d+$/u.test(i))?null:{pid:n,token:o,...typeof i=="string"?{process_start_identity:i}:{}}}async function Tf(e){try{return gE(await ae.readFile(Je.join(e,Sf),"utf8"))}catch{return null}}async function sa(e){try{return await ae.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function yf(e,t){let r=await Tf(e);r===null||r.token!==t||await sa(e)}async function hf(e){try{await ae.mkdir(e)}catch(r){return Xe(r,"EEXIST"),null}let t={...await _n(),token:Mo()};try{await ae.writeFile(Je.join(e,Sf),`${JSON.stringify(t)}
10
- `,"utf8")}catch{return await sa(e),null}return t}async function bE(e){let t;try{let n=await ae.stat(e);if(t=Date.now()-n.mtimeMs,t<=Of)return!1}catch(n){return ue(n)}let r=await Tf(e);return r!==null&&await yn(r,t,mE)?!1:sa(e)}async function aa(e,t){let r=`${e}${fE}`,n=await hf(r);if(n!==null)return async()=>yf(r,n.token);if(!await bE(r))return null;let o=await hf(r);return o===null?null:async()=>yf(r,o.token)}async function wE(e,t){let r=Je.join(Je.dirname(e),"recoveries");await ae.mkdir(r,{recursive:!0}),await ae.writeFile(Je.join(r,`${Mo()}.json`),`${JSON.stringify({event:"owner_dead_recovery_attempt",recorded_at:Ie(),lock:JSON.parse(t)})}
11
- `,{encoding:"utf8",flag:"wx",mode:384})}async function vE(e){let t=await aa(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let r=await hn(e.lockPath);if(r.info===null&&r.warnings.length===0)return{lockInfo:r,shouldRetryCreate:!0,staleRemovalCounted:!1};let n=await wf(r.info);if(!bf(r.info,e.ttlSeconds)&&!n)return{lockInfo:r,shouldRetryCreate:!1,staleRemovalCounted:!1};if(hE(e.id,r,e.force||n,e.forceRequiredForStaleLock),e.staleRemovals>=uE)throw await If(e.id,r.info,Date.now()-e.startedAtMs);return n&&await wE(e.lockPath,JSON.stringify(r.info)),{lockInfo:r,shouldRetryCreate:await oa(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function ce(e,t,r,n,o=!1,i=!0,s,a={}){let c=na(a.maxWaitMs),d=await nr("lock_acquire",{pm_root:e,id:t,ttl_seconds:r,owner:n,force:o,force_required_for_stale_lock:i,...c===void 0?{}:{max_wait_ms:c}});if(d.handled){let w=yE(d.result);if(w)return async()=>{await Promise.resolve(w()),await nr("lock_release",{pm_root:e,id:t,owner:n})}}let l=Ki(e,t),u=_E(s,c),f=Date.now(),m=0,_=kf,y=Mo();for(;;)try{return await aE(l,t,n,r,y,a.createParentDirectories!==!1),async()=>{await cE(l,t,n,y),await nr("lock_release",{pm_root:e,id:t,owner:n})}}catch(w){if(!await iE(w,l))throw new g(`Failed to acquire lock for ${t}: ${rd(w)}`,h.GENERIC_FAILURE);let v=await hn(l);if(await vf(v.info,r)){let K=await vE({lockPath:l,id:t,ttlSeconds:r,force:o,forceRequiredForStaleLock:i,staleRemovals:m,waitBudgetMs:u,startedAtMs:f,fallbackLockInfo:v});if(v=K.lockInfo,K.staleRemovalCounted&&(m+=1),K.shouldRetryCreate)continue}let C=Date.now()-f;if(u===0||C>=u)throw await If(t,v.info,u===0?0:C);await Af(Math.min(_,u-C)),_=Math.min(_*2,ia)}}(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]="71b65888-baa5-5c5f-a02c-4a0fd818fadb")}catch{}})();var Le={max_serving_rows:256,max_bytes:262144,max_event_bytes:32768,retained_byte_fraction:.5,max_events:2048,retention_days:30},Y=class extends TypeError{code="context_usage_validation_failed";constructor(t){super(t),this.name="ContextUsageValidationError"}};function At(e){let t=Date.parse(e.now??new Date().toISOString());if(!Number.isFinite(t))throw new Y("Context usage now must be a valid timestamp");return{iso:new Date(t).toISOString(),ms:t}}function Nf(e){let t=e.maxBytes??Le.max_bytes,r=e.maxEvents??Le.max_events,n=e.retentionDays??Le.retention_days;if(!Number.isSafeInteger(t)||t<1024||t>Le.max_bytes||!Number.isSafeInteger(r)||r<1||!Number.isFinite(n)||n<=0)throw new Y("Context usage retention requires positive maxEvents and retentionDays, and maxBytes from 1024 through 262144");return{maxBytes:t,maxEvents:r,cutoff:At(e).ms-n*864e5}}async function Df(e,t){if(!(await Cf($o.dirname(e))).isDirectory())throw new Y("Context usage runtime must be a real directory");try{if((await Cf(e)).isSymbolicLink())throw new Y("Context usage ledger must not be a symbolic link")}catch(n){if(!ue(n))throw n}let r=await xf(e,t|fr.O_NOFOLLOW|fr.O_NONBLOCK,384);try{let n=await r.stat();if(!n.isFile()||n.nlink!==1)throw new Y("Context usage ledger must be an unshared regular file");return r}catch(n){throw await r.close(),n}}async function jo(e){let t=Nf(e);try{let r=await Df($o.join(e.pmRoot,"runtime","context-usage.jsonl"),fr.O_RDONLY);try{let n=(await r.stat()).size,o=Math.max(0,n-t.maxBytes),i=Buffer.alloc(Math.min(n,t.maxBytes)),{bytesRead:s}=await r.read(i,0,i.length,o),a=i.subarray(0,s).toString("utf8");return(o>0?a.includes(`
12
- `)?a.slice(a.indexOf(`
13
- `)+1):"":a).split(`
14
- `).flatMap(c=>{try{let d=JSON.parse(c);return d&&Date.parse(d.at)>=t.cutoff?[d]:[]}catch{return[]}}).slice(-t.maxEvents)}finally{await r.close()}}catch{return[]}}function Rf(e,t,r){let n=[],o=0;for(let i=e.length-1;i>=0&&n.length<r;i-=1){let s=`${JSON.stringify(e[i])}
15
- `;if(o+=Buffer.byteLength(s),o>t)break;n.push(s)}return n.reverse().join("")}async function gn(e,t,r){let n=Nf(e),o=$o.join(e.pmRoot,"runtime","context-usage.jsonl"),i=Math.floor(n.maxBytes*Le.retained_byte_fraction),s=Math.min(Le.max_event_bytes,i);if(t.some(f=>Buffer.byteLength(`${JSON.stringify(f)}
16
- `)>s))throw new Y("Context usage event exceeds the declared byte ceiling");let a=t.filter(f=>Date.parse(f.at)>=n.cutoff),c=Rf(a,i,n.maxEvents),d=performance.now(),l=await ce(e.pmRoot,"context-usage-ledger",30,`context-usage:${process.pid}`,!1,!1,3e3),u=performance.now()-d;try{await kE($o.dirname(o),{recursive:!0});let f=await Df(o,fr.O_WRONLY|fr.O_CREAT|fr.O_APPEND);try{let m=(await f.stat()).size,_=r===void 0?void 0:await jo(e);if(_?.some(C=>C.kind==="delivery"&&C.serve_id===r))return{written_bytes:0,ledger_bytes:m,compacted:!1,lock_wait_ms:u};if(!(e.maxEvents!==void 0||e.retentionDays!==void 0)&&m+Buffer.byteLength(c)<=n.maxBytes)return await f.writeFile(c,"utf8"),{written_bytes:Buffer.byteLength(c),ledger_bytes:m+Buffer.byteLength(c),compacted:!1,lock_wait_ms:u};let y=Rf([..._??await jo(e),...a],i,n.maxEvents),w=`${o}.${process.pid}.${EE()}.tmp`,v=await xf(w,"wx",384);try{try{await v.writeFile(y,"utf8")}finally{await v.close()}return await f.close(),f=void 0,await SE(w,o),{written_bytes:Buffer.byteLength(y),ledger_bytes:Buffer.byteLength(y),compacted:!0,lock_wait_ms:u}}finally{await OE(w,{force:!0})}}finally{await f?.close()}}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]="e76b38ce-b2aa-589b-9d17-0952eca9e7a2")}catch{}})();var IE=864e5,Lo=Symbol.for("@unbrained/pm-cli/context-usage-serving-receipt");function J(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function FP(e,t){let r=J(e);r!==null&&t!==null&&(r[Lo]=t)}function mr(e,t){let r=J(e),n=J(t),o=r?.[Lo];n!==null&&o!==void 0&&(n[Lo]=o)}function TE(e){return J(e)?.[Lo]??null}function Mf(e){let t=J(e);for(let r of["read_output","context_intent"])if(J(t?.[r])?.result_omitted===!0)return!0;return!1}function Ze(e,t){typeof t=="string"&&t.trim().length>0&&e.add(t.trim())}function $f(e,t){if(Array.isArray(t))for(let r of t)Ze(e,J(r)?.id)}function Pf(e,t){if(Array.isArray(t))for(let r of t)Ze(e,r)}function CE(e,t){let r=J(e.recommended)===null?[]:[e.recommended];for(let n of["ready","decision_needed","gate_needed","containers","blocked","held_by_others"])Array.isArray(e[n])&&r.push(...e[n]);for(let n of r){let o=J(n);Ze(t,o?.id);for(let i of Array.isArray(o?.blockers)?o.blockers:[])Ze(t,J(i)?.id);for(let i of Array.isArray(o?.unblocks)?o.unblocks:[])Ze(t,i)}}function RE(e,t){for(let r of["high_level","low_level","blocked_fallback","recently_created","unparented","activity","progress","blockers","staleness"])$f(t,e[r]);for(let r of Array.isArray(e.blockers)?e.blockers:[])Ze(t,J(r)?.blocked_by);xE(e,t)}function xE(e,t){for(let o of Array.isArray(e.hierarchy)?e.hierarchy:[]){let i=J(o);Ze(t,i?.id),$f(t,i?.children)}for(let o of["files","workload"])for(let i of Array.isArray(e[o])?e[o]:[])Pf(t,J(i)?.items);let r=J(e.agenda);for(let o of Array.isArray(r?.events)?r.events:[])Ze(t,J(o)?.item_id);let n=J(e.tests);Pf(t,n?.items_failing)}function NE(e,t){let r=J(e);if(r===null||Mf(e))return[];let n=new Set;return t==="next"?CE(r,n):RE(r,n),[...n]}async function zP(e){let t=TE(e.result);if(t===null)return!1;let r=Mf(e.result);return await DE({pmRoot:e.pmRoot,receipt:t,deliveredItemIds:NE(e.result,t.surface),resultOmitted:r}),!0}async function UP(e){if([process.env.PM_CONTEXT_USAGE_DISABLED==="1",e.enabled===!1].includes(!0))return null;if(!e.author.trim()||e.rows.some(o=>!o.id.trim()||!Number.isInteger(o.rank)||o.rank<1))throw new Y("Context usage serving requires an author and valid ranked rows");let t=e.rows.map(o=>({id:o.id.trim(),rank:o.rank,included:o.included}));if(new Set(t.map(o=>o.id)).size!==t.length)throw new Y("Context usage serving requires unique normalized row ids");let r=t.slice(0,Le.max_serving_rows),n={serve_id:AE(),author:e.author.trim(),surface:e.surface,rows:t,recorded_item_ids:r.map(o=>o.id)};return n.storage=await gn(e,[{kind:"serve",schema_version:2,serve_id:n.serve_id,at:At(e).iso,author:e.author.trim(),surface:e.surface,profile:e.profile.trim()||"balanced",rows:r,candidate_count:t.length,omitted_row_count:t.length-r.length,result_omitted:!1,packed_item_ids:r.filter(o=>o.included).map(o=>o.id)}]),n}async function DE(e){if(e.receipt===null||process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)return;let t=new Set(e.receipt.rows.map(i=>i.id)),r=[...new Set(e.deliveredItemIds.map(i=>i.trim()))];if(r.some(i=>i.length===0||!t.has(i))||e.resultOmitted&&r.length>0)throw new Y("Context usage delivery requires emitted ranked ids and zero ids for an omitted result");let n=new Set(e.receipt.recorded_item_ids??e.receipt.rows.map(i=>i.id)),o={kind:"delivery",schema_version:2,serve_id:e.receipt.serve_id,at:At(e).iso,author:e.receipt.author,surface:e.receipt.surface,result_omitted:e.resultOmitted,delivered_item_ids:r.filter(i=>n.has(i))};await gn(e,[o],o.serve_id)}async function HP(e){if(!(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)){if(!e.author.trim()||!e.itemId.trim()||!e.intent.trim())throw new Y("Context usage touch requires author, itemId, and intent");await gn(e,[{kind:"touch",at:At(e).iso,author:e.author.trim(),item_id:e.itemId.trim(),intent:e.intent.trim()}])}}async function qP(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1||e.itemIds.length===0)return;let t=e.author.trim(),r=e.intent.trim();if(!t||!r)throw new Y("Context usage touch requires author and intent");let n=new Set;for(let s of e.itemIds){if(typeof s!="string")throw new Y("Context usage touch requires string itemIds");let a=s.trim();if(!a)throw new Y("Context usage touch requires non-empty itemId");n.add(a)}let o=At(e).iso,i=[...n].map(s=>({kind:"touch",at:o,author:t,item_id:s,intent:r}));await gn(e,i)}function PE(e,t,r,n){return e.find(({entry:o,time:i})=>o.item_id===t&&i>=r&&i-r<=n)?.time}function ME(e,t){let r=new Map;for(let n of e)n.kind==="delivery"&&n.schema_version===2&&n.author===t&&!r.has(n.serve_id)&&r.set(n.serve_id,n);return r}async function VP(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)return{affinity:{},positive_judgments:0,serving_events:0,untrusted_serving_events:0};let t=await jo(e),r=At(e).ms,n=(e.horizonHours??24)*36e5;if(![Number.isFinite(n),n>0].every(Boolean))throw new Y("Context usage horizonHours must be positive");let o=e.author.trim(),i=t.filter(f=>f.kind==="touch").filter(f=>f.author===o).map(f=>({entry:f,time:Date.parse(f.at)})),s=new Map,a=0,c=0,d=0,l=ME(t,o);t.filter(f=>f.kind==="serve").filter(f=>f.author===o).forEach(f=>{if(![f.schema_version===2,!!f.serve_id].every(Boolean)){c+=1;return}a+=1;let m=Date.parse(f.at),_=l.get(f.serve_id),y=new Set(_?.delivered_item_ids??[]);for(let w of f.rows){if(!y.has(w.id))continue;let v=PE(i,w.id,m,n);if(v===void 0)continue;d+=1;let C=Math.max(0,(r-v)/IE);s.set(w.id,(s.get(w.id)??0)+Math.exp(-C/14))}});let u=Math.max(0,...s.values());return{affinity:Object.fromEntries([...s.entries()].map(([f,m])=>[f,u===0?.05:.05+.95*m/u])),positive_judgments:d,serving_events:a,untrusted_serving_events:c}}(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]="6a604d54-5425-5ae7-8f20-9d5f1d33c20c")}catch{}})();var Lf=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),Ff=new $E;function jE(){return Ff.getStore()??Lf}function r1(e,t){return Ff.run(FE(e.workspaceContracts,e.packageContracts),t)}function LE(e,t){let r=e.command.trim().toLowerCase(),n=e.intent.trim().toLowerCase(),o=`${r}:${n}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(r)||!/^[a-z0-9][a-z0-9-]*$/.test(n))throw new TypeError(`Invalid context intent command or name: ${o}`);if(e.description.trim().length===0)throw new TypeError(`Context intent ${o} requires a non-empty description`);if(!Number.isSafeInteger(e.token_budget)||e.token_budget<=0)throw new TypeError(`Context intent ${o} requires a positive integer token_budget`);let i=[...new Set(e.included_field_groups.map(s=>s.trim()).filter(Boolean))];if(i.length===0)throw new TypeError(`Context intent ${o} requires included_field_groups`);return{command:r,intent:n,description:e.description.trim(),included_field_groups:i,token_budget:e.token_budget,source:t}}function FE(e=[],t=[]){let r=[{source:"core",contracts:Lf,allowOverride:!1},{source:"package",contracts:t,allowOverride:!1},{source:"workspace",contracts:e,allowOverride:!0}],n=new Map,o=new Set;for(let i of r){o.clear();for(let s of i.contracts){let a=LE(s,i.source),c=`${a.command}:${a.intent}`;if(o.has(c))throw new TypeError(`Duplicate context intent declaration: ${c}`);if(o.add(c),!i.allowOverride&&n.has(c))throw new TypeError(`Duplicate context intent declaration: ${c}`);n.set(c,a)}}return[...n.values()].sort((i,s)=>i.command.localeCompare(s.command)||i.intent.localeCompare(s.intent))}function zf(e,t,r=jE(),n=[]){let o=e.trim().toLowerCase(),i=t.trim().toLowerCase(),s=r.find(f=>f.command===o&&f.intent===i);if(s)return{...s,source:s.source??"core"};let a=r.filter(f=>f.command===o).map(f=>f.intent);if(a.length===0)return;let c=a.map(f=>{let m=Array.from({length:i.length+1},(_,y)=>y);for(let _=1;_<=f.length;_+=1){let y=m[0];m[0]=_;for(let w=1;w<=i.length;w+=1){let v=m[w];m[w]=Math.min(m[w]+1,m[w-1]+1,y+(f[_-1]===i[w-1]?0:1)),y=v}}return{candidate:f,distance:m[i.length]}}).sort((f,m)=>f.distance-m.distance||f.candidate.localeCompare(m.candidate))[0].candidate,d=[o,...n,"--for",i],l=[o,...n,"--for",c],u=or(l);throw new g(`Unknown context intent "${i}" for ${o}. Did you mean "${c}"?`,h.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:i,required:`Use a declared ${o} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[u],recovery:{recovery_mode:"compact",attempted_command:or(d),allowed_values:[...a].sort(),suggested_retry:u,suggested_retry_args:l}})}var Uf={context:(e,t,r)=>{e.section===void 0&&e.depth===void 0&&(e.section=t.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),e.depth===void 0&&(e.depth=t.intent==="handoff"?"deep":"standard");let n=zo(e.tokenBudget,t.token_budget),o=Uo("context",t.intent,n,r),i=It(e.limit),s=String(i===void 0?o:Math.min(i,o));(e.limit===void 0||i!==void 0)&&(e.limit=s),e.activityLimit===void 0&&(e.activityLimit=s)},get:e=>{e.depth===void 0&&e.fields===void 0&&(e.depth="standard")},list:(e,t,r)=>{e.brief===void 0&&e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");let n=zo(e.tokenBudget,t.token_budget),o=Uo("list",t.intent,n,r),i=It(e.limit);(e.limit===void 0||i!==void 0)&&(e.limit=String(i===void 0?o:Math.min(i,o)))},next:e=>{e.readyOnly===void 0&&(e.readyOnly=!0)},search:(e,t,r)=>{e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.compact=!0);let n=zo(e.tokenBudget,t.token_budget),o=Uo("search",t.intent,n,r),i=It(e.limit);(e.limit===void 0||i!==void 0)&&(e.limit=String(i===void 0?o:Math.min(i,o)))}};function n1(e,t,r=[]){let n=t.tokenBudget??t.token_budget;if(typeof t.for!="string"){if(n!==void 0&&(e==="get"||e==="list"||e==="search"))throw new g("--token-budget requires a declared context intent selected with --for",h.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(t.tokenBudget!==void 0||t.token_budget===void 0)return t;let a={...t,tokenBudget:n};return delete a.token_budget,a}let o=zf(e,t.for,void 0,r),i=It(n)!==void 0,s={...t};return s.tokenBudget===void 0&&n!==void 0&&(s.tokenBudget=n),delete s.token_budget,s.tokenBudget===void 0&&(s.tokenBudget=String(o.token_budget)),Uf[e](s,o,i),s}var zE={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},Fo=256;function ca(e){return Array.isArray(e)?e.map(ca):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,ca(r)])):typeof e=="string"&&e.length>240?`${We(e,240)}\u2026`:e}function It(e){let t=typeof e=="number"?e:typeof e=="string"&&/^\d+$/u.test(e.trim())?Number(e):Number.NaN;return Number.isSafeInteger(t)&&t>0?t:void 0}function zo(e,t){let r=It(e);if(r===void 0)return t;if(r<Fo)throw new g(`Context intent token budget must be at least ${Fo}`,h.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(e),required:`Use an integer token budget of at least ${Fo}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${Fo} or omit the override.`]});return r}function Uo(e,t,r,n){if(e==="get"||e==="next")return;let o=e==="context"&&t==="orient",i=e==="context"?o?1200:800:e==="list"?520:480,s=e==="context"?o?600:500:16,a=Math.max(e==="context"?1:2,Math.floor((r-i)/s));return n?a:Math.min(e==="context"?20:100,a)}function Qe(e,t){let r=t.estimated_tokens;for(;;){t.estimated_tokens=r;let n=Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4);if(n===r)return;r=n}}var jf={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function Hf(e){try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof t.fingerprint!="string"||!Number.isSafeInteger(t.after_index)?void 0:{fingerprint:t.fingerprint,after_index:t.after_index,...typeof t.snapshot=="string"?{snapshot:t.snapshot}:{}}}catch{return}}function UE(e){if(e===null||typeof e!="object")return;if(typeof e.id=="string")return e.id;let t=e.item?.id;return typeof t=="string"?t:void 0}function HE(e,t,r){let n=!1;for(;;){if(Qe(e,t),t.estimated_tokens<=t.token_budget||r.length<=1)return n;let o=Buffer.byteLength(JSON.stringify(r),"utf8"),i=(t.estimated_tokens-t.token_budget)*4;r.splice(-Math.min(r.length-1,Math.max(1,Math.ceil(i/Math.max(1,Math.ceil(o/r.length)))))),n=!0}}function qE(e,t,r){let n=e.items,o=typeof e.next_cursor=="string",i=o?e.next_cursor:r.after;if(!Array.isArray(n)||typeof i!="string")return!1;let s=Hf(i);if(s===void 0)return!1;let a=n.length,c=[...n],d=!1;for(;;){if(d=HE(e,t,n)||d,!d)return!1;let l=UE(n.at(-1));if(l===void 0)return n.splice(0,n.length,...c),Qe(e,t),!1;if(e.next_cursor=un(s.fingerprint,l,o?s.after_index-(a-n.length):s.after_index+n.length,s.snapshot),Qe(e,t),t.estimated_tokens<=t.token_budget||n.length<=1)break}return typeof e.count=="number"&&(e.count=n.length),typeof e.applied_limit=="number"&&(e.applied_limit=n.length),!0}function VE(e,t,r,n){if(e==="list"||e==="search")return qE(t,r,n);if(e!=="next"||typeof t.next_cursor=="string")return!1;let o=!1;for(;;){if(Qe(t,r),r.estimated_tokens<=r.token_budget)return o;let i=jf[e].map(f=>({key:f,rows:Array.isArray(t[f])?t[f]:[]})).filter(({rows:f})=>f.length>0).sort((f,m)=>m.rows.length-f.rows.length||f.key.localeCompare(m.key))[0];if(i===void 0)return o;let s=jf[e].reduce((f,m)=>f+(Array.isArray(t[m])?t[m].length:0),0);if(s<=1)return o;let a=Math.min(i.rows.length,s-1),c=Buffer.byteLength(JSON.stringify(i.rows),"utf8"),d=Math.max(1,Math.ceil(c/i.rows.length)),l=(r.estimated_tokens-r.token_budget)*4,u=Math.min(a,Math.max(1,Math.ceil(l/d)));i.rows.splice(-u,u),o=!0}}function BE(e,t,r){if(typeof t.for!="string")return r;let n=e.startsWith("list-")?"list":e;if(!(n in Uf))return r;let o=n,i=zf(o,t.for),s=zo(t.tokenBudget??t.token_budget,i.token_budget),a={command:o,intent:i.intent,source:i.source,included_field_groups:[...i.included_field_groups],token_budget:s,declared_token_budget:i.token_budget,token_budget_override:s-i.token_budget,estimated_tokens:0,within_budget:!0,degradation:zE[o],declaration_feasible:!0,result_omitted:!1},c={...r},d=Uo(o,i.intent,a.token_budget,It(t.tokenBudget??t.token_budget)!==void 0);if(d!==void 0){let u=It(t.limit),f=u!==void 0&&u<d;a.budget_derived_limit=d,a.binding_constraint=f?"explicit_limit":"token_budget",a.limit_reason=f?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",c.budget_derived_limit=d}let l={...c,context_intent:a};return Qe(l,a),a.estimated_tokens>a.token_budget&&(a.degradation="recursive_budget_compaction",l={...ca(c),context_intent:a},Qe(l,a)),a.estimated_tokens>a.token_budget&&VE(o,l,a,t)&&(a.degradation="budget_row_compaction",Qe(l,a)),a.declaration_feasible=a.estimated_tokens<=a.declared_token_budget,a.estimated_tokens>a.token_budget&&(a.degradation="budget_receipt_only",a.result_omitted=!0,a.within_budget=!1,l={budget_exceeded:{omitted_result:!0,reason:a.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:GE(e,o,i.intent,a,c)},context_intent:a}),l}function WE(e,t){if(typeof e.after!="string"||e.after.length===0)return t;let r=Hf(e.after)?.fingerprint??"opaque_cursor",n={...t};for(let o of["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"])delete n[o];return n.continuation_contract={fingerprint:r,metadata:"reference",restore_with:"omit --after"},n}function da(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function GE(e,t,r,n,o){let i=t==="get"&&da(o.item)&&typeof o.item.id=="string"?o.item.id:t==="search"&&typeof o.query=="string"?o.query:void 0,s=i===void 0?"":` '${i.replaceAll("'",`'"'"'`)}'`,a=t==="get"?"":` --limit ${n.budget_derived_limit??1}`;return`pm ${e}${s} --for ${r} --token-budget ${Math.ceil(n.estimated_tokens/100)*100}${a}`}function pr(e,t){if(da(e))return typeof e[t]=="number"?e[t]:void 0}function KE(e,t){let r=e;for(let n=0;n<8;n+=1){let o=pr(r.context_intent,"estimated_tokens"),i=pr(r.read_output,"estimated_tokens"),s=pr(r.read_session,"spent_this_call_tokens");if(da(r.context_intent)&&Qe(r,r.context_intent),r=Bs(r,t),pr(r.context_intent,"estimated_tokens")===o&&pr(r.read_output,"estimated_tokens")===i&&pr(r.read_session,"spent_this_call_tokens")===s)break}return r}function qf(e,t,r){let n=iu(e,bu(e??"",r)),o=typeof n=="object"&&n!==null&&!Array.isArray(n)?Zu(e??"",{...t,outputRowContract:t.outputRowContract===!0||t.output_row_contract===!0},WE(t,BE(e??"",t,n))):n;if(mr(r,o),t.outputRowContract===!0||t.output_row_contract===!0||typeof o!="object"||o===null||Array.isArray(o)||!Object.hasOwn(o,"row_contract"))return o;let i=Object.fromEntries(Object.entries(o).filter(([a])=>a!=="row_contract"));Object.defineProperty(i,"row_contract",{value:o.row_contract,enumerable:!1,configurable:!0});let s=KE(i,t);return delete s.row_contract,mr(o,s),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]="cb1266f3-8375-586f-87c6-356cf7843969")}catch{}})();var _r=["result_rows","envelope","diagnostics","hints"],YE=/^(?:items|results|rows|ready|blocked|recommended|decision_needed|children|dependencies|events|matches|commands|tools)$/u,XE=/^(?:diagnostics|errors?|warnings?|findings|violations|failures?)$/u,JE=/^(?:hints?|suggestions?|next_steps?|recovery|remediation|examples?)$/u,ZE=8;function la(e){return Buffer.byteLength(e,"utf8")}function Vf(e){return la(JSON.stringify(e)??"null")}function QE(e,t){return XE.test(e)?"diagnostics":JE.test(e)?"hints":YE.test(e)||Array.isArray(t)?"result_rows":"envelope"}function e0(e){let t={result_rows:0,envelope:0,diagnostics:0,hints:0};if(typeof e!="object"||e===null||Array.isArray(e))return t[Array.isArray(e)?"result_rows":"envelope"]=Vf(e),t;for(let[r,n]of Object.entries(e))t[QE(r,n)]+=Vf({[r]:n});return Object.values(t).every(r=>r===0)&&(t.envelope=1),t}function t0(e,t){let r=_r.reduce((s,a)=>s+t[a],0),n=_r.map(s=>({section:s,value:e*t[s]/r})),o={result_rows:0,envelope:0,diagnostics:0,hints:0};for(let s of n)o[s.section]=Math.floor(s.value);let i=e-_r.reduce((s,a)=>s+o[a],0);for(let s of[...n].sort((a,c)=>c.value-Math.floor(c.value)-(a.value-Math.floor(a.value))||_r.indexOf(a.section)-_r.indexOf(c.section))){if(i===0)break;o[s.section]+=1,i-=1}return o}function Bf(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,token_accounting:t}:{result:e,token_accounting:t}}function Wf(e,t){let r=la(t(e)),n=t0(r,e0(e)),o=Object.fromEntries(_r.map(a=>[a,{bytes:n[a],estimated_tokens:kt(n[a])}])),i={version:1,measurement_scope:"output_before_token_accounting",estimator:"ceil(utf8_bytes / 4)",total_bytes:r,total_estimated_tokens:kt(r),sections:o,accounting_receipt_bytes:0,accounting_receipt_estimated_tokens:0,excluded_fields:["token_accounting"],section_allocation:"proportional_canonical_json"},s=Bf(e,i);for(let a=0;a<ZE;a+=1){let c=la(t(s))-r;if(c===i.accounting_receipt_bytes)return s;i={...i,accounting_receipt_bytes:c,accounting_receipt_estimated_tokens:kt(c)},s=Bf(e,i)}return s}import{encode as ua}from"@toon-format/toon";(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]="8936e93f-25bf-58cc-ba91-37cc2677c5d2")}catch{}})();function Gf(e){let t=[...new Set(e.flatMap(i=>Object.keys(i)))],r=t.filter(i=>e.some(s=>{let a=s[i];return a!==null&&typeof a=="object"})),n=new Set(r),o=[];return{rows:e.map((i,s)=>Object.fromEntries(t.map(a=>{if(!Object.hasOwn(i,a))return o.push([s,a]),[a,null];let c=i[a];return[a,n.has(a)?JSON.stringify(c):c]}))),encoding:{json_columns:r,absent:o}}}function a1(e){let t=new Set(e.encoding.json_columns),r=new Set(e.encoding.absent.map(([n,o])=>JSON.stringify([n,o])));return e.rows.map((n,o)=>Object.fromEntries(Object.entries(n).flatMap(([i,s])=>r.has(JSON.stringify([o,i]))?[]:[[i,t.has(i)?JSON.parse(String(s)):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]="dc76b081-02dc-5b09-ab40-cd57c733b3ad")}catch{}})();var l1=["id","title","status","type","priority","parent","updated_at"],Ho=["id","status","type","title"],u1={list:"brief","list-all":"full","list-draft":"full","list-open":"brief","list-in-progress":"brief","list-blocked":"brief","list-closed":"brief","list-canceled":"full"},r0=["tree_depth","tree_parent","tree_children","tree_title"];function f1(e=[]){return[...new Set([...we,"body",...r0,...e])].flatMap(t=>[t,`item.${t}`]).sort()}var m1=["brief","standard","deep"],n0=["body","linked","claim_state","children","schedule","blockers"],o0=["linked.files","linked.tests","linked.docs"],i0=["claim_state.claimed","claim_state.assignee","claim_state.last_claim","claim_state.last_release"],s0=["schedule.deadline","schedule.start_at","schedule.end_at","schedule.location","schedule.reminders","schedule.events"];function p1(e=[]){return[...[...new Set([...we,...e,"notes_count","tests_count","collection_counts"])].flatMap(t=>[t,`item.${t}`]),...n0,...o0,...i0,...s0].sort()}var _1=["id","title","status","type","priority","updated_at","score","matched_fields"],a0=["score","matched_fields","highlights"],Kf=["id","title","description","type","status","priority","tags","created_at","updated_at","deadline","assignee","author","estimated_minutes","acceptance_criteria","dependencies","comments","notes","learnings","reminders","events","files","tests","docs","close_reason","parent","reviewer","risk","confidence","sprint","release","blocked_by","blocked_reason","reporter","severity","environment","repro_steps","resolution","expected_result","actual_result","affected_version","fixed_version","component","regression","customer_impact","definition_of_ready","order","rank","goal","objective","value","impact","outcome","why_now","plan"];function y1(e=[]){let t=[...new Set(e)];return[...a0,...Kf,...Kf.map(r=>`item.${r}`),...t,...t.map(r=>`item.${r}`)].sort()}(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]="95103919-d686-5c3b-bd51-928f5b2314ef")}catch{}})();function yr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function c0(e){if(!yr(e))return!1;let t=e.fields;return e.mode==="brief"&&Object.keys(e).length===2&&Array.isArray(t)&&(t.length===Ho.length||t.length===Ho.length+1&&t.at(-1)==="priority")&&Ho.every((r,n)=>t[n]===r)}function d0(e,t){return typeof e.has_more=="boolean"&&e.truncated===e.has_more&&e.count===t&&typeof e.total=="number"&&Number.isSafeInteger(e.total)&&(e.has_more?e.total>t&&typeof e.next_cursor=="string"&&e.next_cursor.length>0:e.total===t&&e.next_cursor==null)}function l0(e){return yr(e)&&(e.status==="complete"||e.status==="unchecked")&&e.unreadable_item_count===0&&e.unreadable_directory_count===0}function u0(e){if(!yr(e)||!Array.isArray(e.omitted_field_groups))return!1;let t=e.omitted_field_groups,r=t[0];return e.has_omissions===!0&&e.omitted_field_group_count===1&&Object.keys(e).length===3&&t.length===1&&yr(r)&&Object.keys(r).length===2&&r.name==="full_item_fields"&&r.restore_with==="--full"}function Yf(e){if(!yr(e)||!Array.isArray(e.items)||Object.hasOwn(e,"details")||!c0(e.projection)||!l0(e.completeness)||!d0(e,e.items.length)||!u0(e.omission_receipt))return e;let{total:t,has_more:r,truncated:n,next_cursor:o,completeness:i,projection:s,now:a,omission_receipt:c,sorting:d,...l}=e,u=i.status==="complete"&&!r&&Object.keys(i).length===3,{unreadable_item_count:f,unreadable_directory_count:m,..._}=i;return{...l,...u?{}:{total:t,has_more:r,completeness:_},...r?{next_cursor:o}:{},...yr(d)&&d.sort==="default"&&d.order==="asc"&&Object.keys(d).length===2?{}:{sorting:d},details:"--full"}}(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]="dd3b19cb-eda3-5ee9-a838-f0abaa5cc8ea")}catch{}})();var f0=new Set(Object.values(h)),m0=new Map([["notes_count","notes"],["tests_count","tests"]]),fa="__pm_native_output",Xf=!1;function U(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ya(e){let t={read_output:{result_omitted:!0}};mr(e,t),wo(t)}function p0(e,t,r){if(r){wo(e);return}ya(t)}function _0(e){if(!U(e)||e[fa]!==!0)return e;let{[fa]:t,...r}=e;return r}function ma(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function y0(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.SUCCESS)}function h0(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.GENERIC_FAILURE)}function pa(e){if(e==="stdout"){y0();return}h0()}function Jf(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function g0(){Xf||(Xf=!0,process.stdout.on("error",e=>{if(ma(e)){pa("stdout");return}Jf(e)}),process.stderr.on("error",e=>{if(ma(e)){pa("stderr");return}Jf(e)}))}function Zf(e,t){g0();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(r){if(ma(r))return pa(e),!1;throw r}}function b0(e){return Zf("stdout",e)}function bn(e){return Zf("stderr",e)}function Qf(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function w0(e){let t=Object.keys(e[0]);return t.length>0&&e.every(r=>Object.keys(r).length===t.length&&t.every(n=>{if(!Object.hasOwn(r,n))return!1;let o=r[n];return o===null||typeof o=="string"||typeof o=="number"||typeof o=="boolean"}))}function _a(e,t){let r=" ".repeat(t);return e.split(`
17
- `).map(n=>`${r}${n}`).join(`
18
- `)}function v0(e){let t=new Set,r=0;for(let n of e){let o=Object.keys(n);r+=o.length;for(let i of o)t.add(i)}return e.length*t.size<=r*2}function E0(e,t,r,n){let o=" ".repeat(r);if(!U(t)&&!Array.isArray(t))return`${o}${e}: ${Qf(t)}`;if(Array.isArray(t)){if(t.length===0)return`${o}${e}: []`;let i=_a(ua({[e]:t}),r);if(n&&t.length>=2&&t.every(U)&&!w0(t)&&v0(t)){let s=Gf(t),a=_a(ua({[e]:s.rows,[`${e}_encoding`]:s.encoding}),r);if(Buffer.byteLength(a)<Buffer.byteLength(i))return a}return i}return U(t)&&Object.keys(t).length===0?`${o}${e}: {}`:`${o}${e}:
19
- ${em(t,r+1)}`}function k0(e,t,r){let n=e.map(o=>Vo(o,t,r||t.preserveRowFacts&&U(o))).filter(o=>o!==void 0);return n.length>0||r?n:void 0}function Vo(e,t={omitDuplicateCountAliases:!0,preserveRowFacts:!0},r=!1){if(e===null)return r?null:void 0;if(Array.isArray(e))return k0(e,t,r);if(U(e)){let n=[],o=Object.entries(e).filter(([i,s])=>{let a=m0.get(i);return!t.omitDuplicateCountAliases||a===void 0||!U(e.collection_counts)||s!==e.collection_counts[a]});for(let[i,s]of o){if(i==="omitted_field_groups"&&Array.isArray(s)&&s.length===0){n.push([i,[]]);continue}let a=Vo(s,t,r);a!==void 0&&n.push([i,a])}return n.length>0||r?Object.fromEntries(n):void 0}return e}function em(e,t){let r=" ".repeat(t);if(Array.isArray(e))return e.length===0?"[]":_a(ua(e),t);if(U(e)){let n=Object.entries(e);return n.length===0?"{}":n.map(([o,i])=>E0(o,i,t,!Object.hasOwn(e,`${o}_encoding`)&&!(o==="checks"&&U(e.verdict)&&e.verdict.authority==="ok"))).join(`
20
- `)}return`${r}${Qf(e)}`}function S0(e){if(!U(e)||e.output_default!=="markdown"||typeof e.view!="string"||!Array.isArray(e.events)||!Array.isArray(e.days))return null;let t=[`# pm calendar (${e.view})`,""],r=U(e.summary)?e.summary:{};if(t.push(`- events: ${String(r.events??0)}`),t.push(""),e.events.length===0)return t.push("No calendar events matched the selected filters."),`${t.join(`
21
- `)}
22
- `;for(let n of e.events){if(!U(n))continue;let o=typeof n.kind=="string"?n.kind:"event",i=typeof n.item_title=="string"?n.item_title:"",s=typeof n.item_id=="string"?n.item_id:"",a=typeof n.reminder_text=="string"&&n.reminder_text.length>0?` ${n.reminder_text}`:"";t.push(`- [${o}] ${s} ${i}${a}`.trim())}return`${t.join(`
23
- `)}
24
- `}var O0=new Set(["filters","now","projection","sorting"]);function A0(e){let t=Vo(e,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!U(t)||!Array.isArray(t.items))return t??null;let r=Object.fromEntries(Object.entries(t).filter(([n])=>!O0.has(n)));return r.has_more!==!0&&delete r.next_cursor,r}function I0(e,t){if(!U(e)||!Array.isArray(e.run_results)||!e.run_results.every(U))return e;let r=e.run_results,n=r.map(s=>s.execution_context).filter(s=>s!==void 0),o=n.length===r.length&&n.length>0&&n.every(s=>JSON.stringify(s)===JSON.stringify(n[0]))?n[0]:void 0,i=r.map(s=>{let{execution_context:a,stdout:c,stderr:d,...l}=s;return o===void 0?s:!t||s.status!=="passed"?{...l,stdout:c,stderr:d}:l});return{...e,...o===void 0?{}:{execution_context:o},run_results:i}}function T0(e){return!U(e)||e.ok!==!0||!U(e.verdict)||e.verdict.authority!=="ok"||!Array.isArray(e.checks)?e:{...e,checks:e.checks.map(C0)}}function C0(e){if(!U(e)||e.ok!==!0||!U(e.details)||Object.keys(e.details).length!==0)return e;let{details:t,...r}=e;return r}function qo(e,t,r=!1){if(t==="json"){let o=r?A0(e):e,i=U(e)&&U(e.projection)&&e.projection.mode==="brief"&&Array.isArray(e.items);return`${JSON.stringify(o,null,i?void 0:2)}
25
- `}let n=Vo(T0(Yf(e)),{omitDuplicateCountAliases:!0,preserveRowFacts:!0});return n===void 0?`{}
26
- `:`${em(n,0)}
27
- `}function R0(e,t,r,n){let o=t?{handled:!1,result:e,warnings:[]}:xs("output_format",{command:r.command,args:r.commandArgs,command_options:r.commandOptions,global:{...r},pm_root:r.pmRoot,format:n,options:{...r},result:e}),i=o.warnings.find(s=>s.startsWith("extension_output_format_payload_echo_deprecated:"));return i!==void 0&&bn(`Warning: ${i}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
28
- `),o.handled&&typeof o.result=="string"?{result:o.result,rendered:o.result.endsWith(`
29
- `)?o.result:`${o.result}
30
- `,structuredDeliveryPreserved:!1}:{result:o.handled?o.result:e,rendered:null,structuredDeliveryPreserved:!o.handled||U(o.result)}}function x0(e,t,r,n){let o=Zl(),i=r.command??o?.command,s={...o?.options,...r.commandOptions,...Object.fromEntries([["outputInclude",r.outputInclude],["outputLimit",r.outputLimit],["outputBudget",r.outputBudget],["outputFormat",r.outputFormat],["outputSession",r.outputSession],["outputCursor",r.outputCursor],["outputRowContract",r.outputRowContract]].filter(C=>C[1]!==void 0))},a=ef(i??"",s)??n,c={...s,resolvedOutputFormat:a},d={...r,command:i,commandOptions:c},l=R0(e,t,d,a);if(l.rendered!==null)return ya(e),l.rendered;let u=l.result;mr(e,u);let f=i==="test"?I0(u,r.lean===!0):u,m=qf(i,c,f);Qu(m)&&(process.exitCode||=h.USAGE);let{structuredDeliveryPreserved:_}=l,y=C=>{if(a==="toon"){let Ee=S0(C);if(Ee!==null)return Ee}let K=t?{rendered:null}:eu(a,C);return K.rendered!==null?(_=!1,K.rendered.endsWith(`
31
- `)?K.rendered:`${K.rendered}
32
- `):a==="json"?qo(C,"json",r.lean===!0):qo(C,"toon")},w=r.tokenAccounting===!0?Wf(m,y):m,v=y(w);return p0(w,e,r.quiet!==!0&&_),v}function N0(e,t){let r=Ql(e),n=Vn(r.result)?r.result:null,o=r.result,i=U(o)&&o[fa]===!0,s=n?n.result:_0(r.result);if(wo(s),n)return ya(s),"";let a=t.json===!0||t.json===void 0&&t.defaultOutputFormat==="json"?"json":"toon";return x0(s,i,t,a)}function x1(e,t){U(e)&&Number.isInteger(e.exit_code)&&f0.has(Number(e.exit_code))&&(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=Number(e.exit_code));let r=t.idOnly?on(e,{idOnly:!0}):t.fullChangedFields?e:t.noChangedFields?on(e,{changedFields:"compact"}):on(e,{compactEnvelope:!0}),n=N0(r,t);t.quiet||b0(n)}function N1(e){let t=xs("error_format",{message:e}),r=t.handled&&typeof t.result=="string"?t.result:e;bn(r.endsWith(`
33
- `)?r:`${r}
34
- `)}(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]="13e57322-501d-5927-8254-f6196854d434")}catch{}})();var D0=8,P0=64,M0=5,$0=4,tm=100;function Mu(e,t,r){if(e!=="get"||!ha(r.item)||["fields","outputInclude","output_include","outputCursor","output_cursor"].some(c=>t[c]!==void 0)||t.full===!0||t.tree===!0||t.depth!==void 0&&t.depth!=="standard")return;let n=r.item,o=["linked","claim_state","schedule"],i=o.filter(c=>Object.hasOwn(r,c)),s=Object.fromEntries(Object.entries(r).filter(([c])=>!o.includes(c)));s.item=Object.fromEntries(Object.entries(n).filter(([c])=>c!=="body")),Object.hasOwn(n,"body")&&i.push("body");let a=[...ha(r.omission_receipt)&&Array.isArray(r.omission_receipt.omitted_field_groups)?r.omission_receipt.omitted_field_groups:[],...i.map(c=>({name:c,restore_with:`--fields ${c}`}))];return s.omission_receipt={has_omissions:a.length>0,omitted_field_group_count:a.length,omitted_field_groups:a},s}function Fs(e){let t=Math.trunc(e.effective_budget_tokens),r=Math.trunc(e.measured_result_tokens);if(!Number.isSafeInteger(t)||t<=0||!Number.isSafeInteger(r)||r<=0)return{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"};let n=Math.max(t+1,r),o=Math.ceil(n*M0/$0),i=Math.ceil(o/tm)*tm;return Number.isSafeInteger(i)?{output_budget:i,recovery_budget_multiplier:i/t,rule_version:"v1"}:{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"}}function ar(e,t,r=!1){let n=Object.getOwnPropertyDescriptor(e,"row_contract");n&&(r||n.enumerable===!1)&&Object.defineProperty(t,"row_contract",{...n,enumerable:!1})}function sn(e,t){let r=t===void 0?JSON.stringify(e):qo(e,t);return Math.ceil(Buffer.byteLength(r,"utf8")/4)}function ha(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ga(e,t,r=!1){return typeof e=="string"?r||e.length<=240?e:(t.compacted=!0,`${We(e,240)}\u2026`):Array.isArray(e)?e.map(n=>ga(n,t,r)):ha(e)?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,ga(o,t,r||n==="focus_row_states")])):e}function Ye(e,t,r){let n=t.estimated_tokens;for(let o=0;o<D0;o+=1){t.estimated_tokens=n;let i=sn(e,r);if(i===n)return;n=i}t.estimated_tokens=n}function j0(e,t){return tn(e).filter(r=>(Array.isArray(r.value)?r.value.length:Object.keys(r.value).length)>Math.max(1,t.get(r.path)??0)).map(r=>({collection:r,length:Array.isArray(r.value)?r.value.length:Object.keys(r.value).length})).sort((r,n)=>n.length-r.length||r.collection.path.localeCompare(n.collection.path))[0]?.collection}function L0(e,t,r,n,o,i){for(let s=0;s<P0;s+=1){if(i?.(e),Ye(e,t,o),t.estimated_tokens<=r)return;let a=j0(e,n);if(!a)return;let c=Math.max(1,n.get(a.path)??0),d=Array.isArray(a.value)?[...a.value]:Object.entries(a.value),l=_=>{if(Array.isArray(a.value)){a.value.length=_;for(let y=0;y<_;y+=1)a.value[y]=d[y]}else{for(let y of Object.keys(a.value))delete a.value[y];Object.defineProperties(a.value,Object.getOwnPropertyDescriptors(Object.fromEntries(d.slice(0,_))))}typeof e.count=="number"&&(e.count=Ao(e)),a.path==="items"&&(e.applied_limit=_),i?.(e),Ye(e,t,o)};t.rows_compacted=!0,t.compacted_row_paths=[...new Set([...t.compacted_row_paths??[],a.path])].sort((_,y)=>_.localeCompare(y)),e.has_more=!0,e.truncated=!0;let u=c,f=d.length-1,m=c;for(;u<=f;){let _=Math.floor((u+f)/2);l(_),t.estimated_tokens<=r?(m=_,u=_+1):f=_-1}l(m)}}function $u(e,t,r,n=new Map,o,i,s=!1){let a={compacted:!1},c=Object.fromEntries(Object.entries(e).map(([d,l])=>[d,ga(l,a,s&&d==="diff")]));return ar(e,c),t.strings_compacted=a.compacted,c.read_output=t,L0(c,t,r,n,o,i),Ye(c,t,o),c}import wa from"node:fs/promises";import Bo 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]="658ab1c3-da92-5af6-a170-85ed7befaad6")}catch{}})();function et(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function rm(e){let t=["--pm-path",e,"init","--defaults","--agent-guidance","skip"];return{suggested_retry:or(t),suggested_retry_args:t}}function Wo(e){return new g(`Tracker root is not a directory at ${e}.`,h.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",resolved_path:e,nextSteps:["Pass a tracker directory, usually <workspace>/.agents/pm, rather than a file path."]})}function ba(e){return new g(`Tracker root is not readable at ${e}.`,h.GENERIC_FAILURE,{code:"tracker_root_unreadable",reason:"unreadable",resolved_path:e,nextSteps:["Grant read and directory-search permission to the tracker root, then retry."]})}async function F0(e){let t=Bo.resolve(e),r=Bo.parse(t).root,n=Bo.dirname(t);for(;n!==r;){let o;try{o=await wa.stat(n)}catch(i){if(et(i,"ENOTDIR"))throw Wo(e);if(!et(i,"ENOENT"))throw i;n=Bo.dirname(n);continue}if(!o.isDirectory())throw Wo(e);return}}async function z0(e){let t;try{t=await wa.stat(e)}catch(r){throw et(r,"ENOENT")?(await F0(e),new g(`Tracker is not initialized at ${e}. Tracker root does not exist. Run pm init first.`,h.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",resolved_path:e,nextSteps:["Confirm the tracker root path or initialize it with the emitted retry."],recovery:rm(e)})):et(r,"ENOTDIR")?Wo(e):et(r,"EACCES")||et(r,"EPERM")?ba(e):r}if(!t.isDirectory())throw Wo(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw ba(e);try{await(await wa.opendir(e)).close()}catch(r){throw et(r,"EACCES")||et(r,"EPERM")?ba(e):r}}async function B1(e){if(await z0(e),!await mt(Oe(e)))throw new g(`Tracker is not initialized at ${e}. Run pm init first.`,h.NOT_FOUND,{code:"tracker_not_initialized",reason:"settings_missing",resolved_path:e,nextSteps:["Initialize the selected tracker root with the emitted retry."],recovery:rm(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]="6fd537c2-9d10-5a26-81a9-ac931151017b")}catch{}})();var nm=["append","cancel","claim","close","comment_add","comment_edit","comment_delete","create","delete","docs_add","docs_remove","files_add","files_remove","files_discover","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","import","improvement_observe","learning_add","learning_edit","learning_delete","normalize","note_add","note_edit","note_delete","plan_create_metadata","plan_create_initial_step","plan_add_step","plan_reorder_step","plan_remove_step","plan_link_step","plan_unlink_step","plan_append_decision","plan_append_discovery","plan_append_validation","plan_resume","plan_approve","plan_materialize","plan_update_step","plan_complete_step","plan_block_step","policy_approve","policy_refused","release","reopen","restore","schema_migration","schema_migration_reference","test_run_track","tests_add","tests_remove","tests_update","update","update_audit","update_ownership_bypass","workspace_snapshot_restore","extension_migrations_apply","merge_reconcile"],om=["history:author-acknowledge","settings:write","init:type_preset","templates:save","profile:apply-types","profile:apply-statuses","profile:apply-fields","profile:apply-config","schema:add-type","schema:remove-type","schema:add-status","schema:remove-status","schema:add-field","schema:remove-field","schema:apply-preset","schema:infer-types","schema:policy-put","schema:policy-remove","schema:policy-mode","assurance:bundle:apply","assurance:gate:verdict","telemetry:install_id","telemetry:first_run_prompt","telemetry:clear","item_format:auto_select_default"],va={"init:type-preset":"init:type_preset"},im=["^config:(?:set|unset):[a-z][a-z0-9_.:-]*$","^assurance:(?:measurement|invariant|gate):(?:put|remove)$","^schema_(?:rename_type|rename_status|remap_status|rename_field|remove_type|remove_status|remove_field)(?:_compensate)?$","^extension:[a-z][a-z0-9_-]*:[a-z][a-z0-9_]*$"],G1={version:1,item:nm,workspace:om,aliases:va,patterns:im,read_policy:"preserve_original_operation",custom_operation_grammar:"extension:<package_name>:<snake_case_operation>",legacy_custom_operation_grammar:"lowercase segments separated by underscore, hyphen, colon, or dot; optional opaque colon-suffixed retry key",excluded_surfaces:["json_patch","on_write_hook","telemetry_span"]},U0=new Set([...nm,...om]),H0=im.map(e=>new RegExp(e,"u"));function sm(e){return Object.hasOwn(va,e)?va[e]:e}function K1(e){let t=sm(e);if(U0.has(t)||H0.some(r=>r.test(t)))return t;throw new TypeError("Undeclared history operation; use a native contract identity or extension:<package_name>:<snake_case_operation>.")}function am(e){let t=sm(e),r=t.indexOf(":"),n=r<0?t:t.slice(0,r),o=r<0||r<t.length-1&&!/[\s\p{C}]/u.test(t.slice(r+1));if(/^[a-z][a-z0-9]*(?:[_.-][a-z0-9]+)*$/u.test(n)&&o)return t;throw new TypeError("History operation must use lowercase alphanumeric segments with an optional non-whitespace colon-suffixed retry key.")}import{createHash as q0}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]="ca5b60a5-80a7-5e7d-917f-4c7649bcbab6")}catch{}})();var J1=["sha256","sha512"],V0="sha256",cm="sha256";function Tt(e){if(e===void 0)return V0;if(e==="sha256"||e==="sha512")return e;throw new TypeError(`unsupported_history_hash_algorithm:${String(e)}`)}function tt(e,t){return q0(Tt(t)).update(e,"utf8").digest("hex")}import lm from"node:path";import{link as B0,mkdir as W0,mkdtemp as G0,rm as K0,writeFile as Y0}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]="71c2fed9-81e1-5723-8e34-e6327c07a130")}catch{}})();async function dm(e,t){let r=Ea.dirname(e);await W0(r,{recursive:!0});let n=await G0(Ea.join(r,".pm-seed-")),o=Ea.join(n,"value");try{await Y0(o,t,"utf8");try{return await B0(o,e),!0}catch(i){if(i.code==="EEXIST")return!1;throw i}}finally{await K0(n,{recursive:!0,force:!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]="2075887b-6d4b-582f-9da2-bab13198f9a5")}catch{}})();var X0=2e3,Go=new Map;function rt(e){if(typeof e!="string")return"";let t=Go.get(e);if(t!==void 0)return t;let r=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return Go.size>=X0&&Do(Go),Go.set(e,r),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]="6e07b1b6-1757-54dd-8833-9d3f984ccf79")}catch{}})();var oe=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),mm=Yc,Sa=Kc,J0=["create","update"],Z0=new Set(Gn),Q0=new Set(Gt),ek=new Set(Kn),tk=new Set(Yn),rk=new Set(["string","number","boolean","array","object"]),nk=16;function pm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ok=[e=>e.type===void 0||typeof e.type=="string"&&rk.has(e.type),e=>!Object.hasOwn(e,"const")||Yo(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>Yo(t)),e=>e.min_length===void 0||Number.isInteger(e.min_length)&&e.min_length>=0,e=>e.min_items===void 0||Number.isInteger(e.min_items)&&e.min_items>=0,e=>e.format===void 0||e.format==="date-time",e=>e.required===void 0||Array.isArray(e.required)&&e.required.every(t=>typeof t=="string"&&t.length>0),e=>e.additional_properties===void 0||typeof e.additional_properties=="boolean",e=>e.properties===void 0||pm(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function Yo(e,t=new Set){if(e===null||typeof e=="string"||typeof e=="boolean")return!0;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e))return!1;t.add(e);let r=Array.isArray(e)?e.every(n=>Yo(n,t)):Object.values(e).every(n=>Yo(n,t));return t.delete(e),r}function Ko(e,t=0,r=new Set){if(!pm(e)||t>nk||r.has(e))return;r.add(e);let n=e,o=n.type,i=n.enum,s=n.one_of,a=n.properties,c=n.items,d=n.required,l=n.min_length,u=n.min_items,f=n.format,m=n.additional_properties;if(!ok.every(v=>v(n))){r.delete(e);return}let _=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([v,C])=>[v,Ko(C,t+1,r)])),y=c===void 0?void 0:Ko(c,t+1,r),w=s===void 0?void 0:s.map(v=>Ko(v,t+1,r));if([...Object.values(_??{}),...c===void 0?[]:[y],...w??[]].some(v=>v===void 0)){r.delete(e);return}return r.delete(e),Object.fromEntries(Object.entries({type:o,const:Object.hasOwn(n,"const")?n.const:void 0,enum:i,min_length:l,min_items:u,format:f,properties:_,required:d===void 0?void 0:[...new Set(d)],additional_properties:m,items:y,one_of:w}).filter(([,v])=>v!==void 0))}function vn(e){let t=Array.isArray(e)?e:[];return[...new Set(t.map(r=>typeof r=="string"?r.trim():"").filter(r=>r.length>0))].sort((r,n)=>r.localeCompare(n))}function pe(e){if(typeof e!="string"||e.length===0)return;let t=rt(e);return t.length>0?t:void 0}function ik(e){return e.startsWith("--")?e.slice(2):e}function um(e){return typeof e=="string"?ik(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function _m(e){return e.replaceAll("_","-")}function sk(e){let t=e.replaceAll(/[^A-Za-z0-9]+/g," ").trim().split(/\s+/).filter(o=>o.length>0).map(o=>o.toLowerCase());if(t.length===0)return e;let[r,...n]=t;return`${r}${n.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function ka(e,t){let r=pe(e.id);if(!r)return null;let n=[...new Set(vn(e.aliases).map(rt).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=vn(e.roles).filter(a=>Z0.has(a)),i=e.description?.trim(),s=typeof e.order=="number"&&Number.isFinite(e.order)?e.order:t;return{id:r,aliases:n,roles:o,description:i&&i.length>0?i:void 0,order:s}}function ak(e){return{draft_status:pe(e?.draft_status),open_status:pe(e?.open_status),in_progress_status:pe(e?.in_progress_status),blocked_status:pe(e?.blocked_status),close_status:pe(e?.close_status),canceled_status:pe(e?.canceled_status)}}function ym(e,t){if(!Array.isArray(t)||t.length!==2)return;let r=rt(t[0]),n=rt(t[1]);r.length===0||n.length===0||e.pairs.some(o=>o[0]===r&&o[1]===n)||e.pairs.push([r,n])}function ck(e){let t=typeof e?.type=="string"?e.type.trim():"";if(t.length===0||!Array.isArray(e?.allowed_transitions))return null;let r={type:t,pairs:[],denyAll:e.allowed_transitions.length===0};for(let n of e.allowed_transitions)ym(r,n);return{typeKey:t.toLowerCase(),record:r}}function dk(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let n of e){let o=ck(n);if(o===null)continue;let i=t.get(o.typeKey)??o.record;i.denyAll||=o.record.denyAll;for(let s of o.record.pairs)ym(i,s);t.set(o.typeKey,i)}let r=[];for(let n of t.values())(n.pairs.length>0||n.denyAll)&&r.push({type:n.type,allowed_transitions:n.pairs});return r.sort((n,o)=>n.type.localeCompare(o.type)),r.length>0?r:void 0}function hm(e){let t=rt(e.key??"");if(!t)return null;let r=rt(e.metadata_key??e.front_matter_key??t),n=um(e.cli_flag??_m(t));if(!n)return null;let o=vn(e.cli_aliases).map(u=>um(u)).filter(u=>u.length>0&&u!==n),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=Q0.has(i)?i:"string",a=(()=>{let u=vn(e.commands).filter(f=>ek.has(f));return u.length>0?u:[...J0]})(),c=e.description?.trim(),d=vn(e.required_types),l=e.value_schema===void 0?void 0:Ko(e.value_schema);return e.value_schema!==void 0&&l===void 0?null:{key:t,metadata_key:r,cli_flag:n,cli_aliases:o,description:c&&c.length>0?c:void 0,type:s,commands:a,repeatable:[e.repeatable===!0,s==="string_array"].includes(!0),required:e.required===!0,required_on_create:e.required_on_create===!0,required_types:d,allow_unset:e.allow_unset!==!1,value_schema:l}}function lk(e){let t=new Map;for(let[n,o]of e.entries()){let i=ka(o,n);i&&t.set(i.id,i)}let r=fm([...t.values()]);return r.length>0?r:fm(Sa.map((n,o)=>ka(n,o)).filter(n=>n!==null))}function fm(e){return e.sort((t,r)=>t.order===r.order?t.id.localeCompare(r.id):t.order-r.order)}function uk(e){let t=new Map;for(let r of e??[]){let n=hm(r);n&&t.set(n.key,n)}return[...t.values()].sort((r,n)=>r.key.localeCompare(n.key))}function fk(e){return{id:e.id,aliases:e.aliases.length>0?[...e.aliases]:void 0,roles:e.roles.length>0?[...e.roles]:void 0,description:e.description,order:e.order}}function mk(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==_m(e.key)?e.cli_flag:void 0,cli_aliases:e.cli_aliases.length>0?[...e.cli_aliases]:void 0,description:e.description,type:e.type,commands:[...e.commands],repeatable:e.repeatable===!0?!0:void 0,required:e.required===!0?!0:void 0,required_on_create:e.required_on_create===!0?!0:void 0,required_types:e.required_types.length>0?[...e.required_types]:void 0,allow_unset:e.allow_unset===!1?!1:void 0,value_schema:e.value_schema}}function pk(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return tk.has(t)?t:"allow"}function Te(e){let t={...oe,...e?.files},r=e?.statuses&&e.statuses.length>0?e.statuses:Sa,n=lk(r),o=uk(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:n.map(fk),fields:o.map(mk),workflow:{...mm,...ak(e?.workflow)},type_workflows:dk(e?.type_workflows),unknown_field_policy:pk(e?.unknown_field_policy)}}function _k(e,t,r){try{return JSON.parse(e)}catch{r.push(t);return}}function yk(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.definitions))return t.definitions;if(typeof t.item_types=="object"&&t.item_types!==null){let r=t.item_types;if(Array.isArray(r.definitions))return r.definitions}}function hk(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function gk(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function bk(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;return typeof t.workflow=="object"&&t.workflow!==null&&!Array.isArray(t.workflow)?t.workflow:typeof t.workflows=="object"&&t.workflows!==null&&!Array.isArray(t.workflows)?t.workflows:t}function wk(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(Array.isArray(t.type_workflows))return t.type_workflows}function de(e,t,r){let n=t?.trim()||r;return lm.isAbsolute(n)?n:lm.join(e,n)}function lM(e,t){return de(e,t.files.types,oe.types)}async function gm(e,t){let r=Te(t),n=[{path:de(e,r.files.types,oe.types),seed:{definitions:[]}},{path:de(e,r.files.statuses,oe.statuses),seed:{statuses:Sa}},{path:de(e,r.files.fields,oe.fields),seed:{fields:[]}},{path:de(e,r.files.workflows,oe.workflows),seed:{workflow:mm}}],o=[];for(let i of n)await mt(i.path)||await dm(i.path,`${JSON.stringify(i.seed,null,2)}
35
- `)&&o.push(i.path);return{created_paths:o}}async function bm(e,t){let r=Te(t),n=[],o=de(e,r.files.types,oe.types),i=de(e,r.files.statuses,oe.statuses),s=de(e,r.files.fields,oe.fields),a=de(e,r.files.workflows,oe.workflows),c,d,l,u,f,m=async(C,K)=>{let Ee=await ge(C);if(Ee!==null)return _k(Ee,K,n)},_=await m(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=yk(_),c===void 0&&n.push("runtime_schema_types_invalid_shape"));let y=await m(i,"runtime_schema_statuses_invalid_json");y!==void 0&&(d=hk(y),d===void 0&&n.push("runtime_schema_statuses_invalid_shape"));let w=await m(s,"runtime_schema_fields_invalid_json");w!==void 0&&(l=gk(w),l===void 0&&n.push("runtime_schema_fields_invalid_shape"));let v=await m(a,"runtime_schema_workflows_invalid_json");return v!==void 0&&(u=bk(v),u===void 0&&n.push("runtime_schema_workflows_invalid_shape"),f=wk(v)),{schema:Te({...r,statuses:[...r.statuses,...d??[]],fields:[...r.fields,...l??[]],workflow:{...r.workflow,...u},type_workflows:[...r.type_workflows??[],...f??[]]}),type_definitions_from_file:c,warnings:n,created_paths:[]}}function wn(e,t,r,n=!1){let o=r.map(s=>pe(s)).filter(s=>typeof s=="string").find(s=>e.some(a=>a.id===s));if(n&&o!==void 0)return o;let i=e.find(s=>s.roles.includes(t));return i!==void 0?i.id:o??e[0]?.id}function vk(e){let t=new Map,r=new Map;for(let n of e){r.set(n.id,n),t.set(n.id,n.id),t.set(n.id.replaceAll("_","-"),n.id),t.set(n.id.replaceAll("_"," "),n.id);for(let o of n.aliases)t.set(o,n.id),t.set(o.replaceAll("_","-"),n.id),t.set(o.replaceAll("_"," "),n.id)}return{aliasToId:t,byId:r}}function Ek(e){let t={activeStatuses:new Set,blockedStatuses:new Set,draftStatuses:new Set,terminalCanceledStatuses:new Set,terminalDoneStatuses:new Set,terminalStatuses:new Set};for(let r of e){let n=new Set(r.roles);(n.has("terminal")||n.has("terminal_done")||n.has("terminal_canceled"))&&t.terminalStatuses.add(r.id),n.has("terminal_done")&&t.terminalDoneStatuses.add(r.id),n.has("terminal_canceled")&&t.terminalCanceledStatuses.add(r.id),n.has("active")&&t.activeStatuses.add(r.id),n.has("blocked")&&t.blockedStatuses.add(r.id),n.has("draft")&&t.draftStatuses.add(r.id)}return t}function wm(e){let t=Te(e),r=t.statuses.map((v,C)=>ka(v,C)).filter(v=>v!==null),{aliasToId:n,byId:o}=vk(r),{activeStatuses:i,blockedStatuses:s,draftStatuses:a,terminalCanceledStatuses:c,terminalDoneStatuses:d,terminalStatuses:l}=Ek(r),u=t.workflow,f=pe(u.open_status)??wn(r,"default_open",["open","in_progress",Wt[0]]),m=pe(u.in_progress_status)??wn(r,"active",["in_progress","in-progress",f],!0),_=pe(u.blocked_status)??wn(r,"blocked",["blocked"]),y=pe(u.close_status)??wn(r,"default_close",["closed","done","complete"]),w=pe(u.canceled_status)??wn(r,"default_cancel",["canceled","cancelled"]);return{definitions:r,by_id:o,alias_to_id:n,terminal_statuses:l,terminal_done_statuses:d,terminal_canceled_statuses:c,active_statuses:i,blocked_statuses:s,draft_statuses:a,open_status:f,in_progress_status:m,blocked_status:_,close_status:y,canceled_status:w}}function Oa(e,t){let r=rt(e);if(r)return t.alias_to_id.get(r)}function vm(e){let t=Te(e),r=new Map,n=t.fields.map(c=>hm(c)).filter(c=>c!==null);for(let c of n)r.set(c.key,c);let o=[...r.values()].sort((c,d)=>c.key.localeCompare(d.key)),i=new Map,s=new Map,a=new Map;for(let c of o){i.set(c.key,c),s.set(c.cli_flag,c);for(let d of c.cli_aliases)s.set(d,c);for(let d of c.commands){let l=a.get(d)??[];l.push(c),a.set(d,l)}}for(let[c,d]of a.entries())d.sort((l,u)=>l.key.localeCompare(u.key)),a.set(c,d);return{definitions:o,by_key:i,by_cli_token:s,command_to_fields:a}}function Em(e){return sk(e.key)}function uM(e,t){let r=Oa(e,t);return r?t.terminal_statuses.has(r):!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]="4d5692ce-ec33-5eb4-bd9b-7497ffe25b0e")}catch{}})();var kk=16;function Aa(e){let t=e.trim().replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(o=>o.length>0).map(o=>o.toLowerCase());if(t.length===0)return e;let[r,...n]=t;return`${r}${n.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function Sk(e){return[...new Set([Em(e),Aa(e.key),Aa(e.cli_flag),...e.cli_aliases.map(t=>Aa(t))])]}function Om(e,t){for(let r of Sk(t)){if(!Object.hasOwn(e,r))continue;let n=e[r];if(n!==void 0)return n}}function Am(e){return Array.isArray(e)?e.flatMap(t=>Am(t)).map(t=>t.trim()).filter(t=>t.length>0):typeof e=="string"?e.split(/[,\n|]/).map(t=>t.trim()).filter(t=>t.length>0):e==null?[]:[String(e).trim()].filter(t=>t.length>0)}function km(e,t){if(typeof e=="boolean")return e;if(typeof e=="number"){if(e===1)return!0;if(e===0)return!1}if(typeof e=="string"){let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1}throw new g(`${t} must be one of true|false|1|0|yes|no`,h.USAGE)}function Sm(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;let r=typeof e=="string"?e.trim():String(e),n=Number(r);if(!Number.isFinite(n))throw new g(`${t} must be a number`,h.USAGE);return n}function Ok(e,t,r){let n=typeof e=="string"?(()=>{try{return JSON.parse(e)}catch{return}})():e;if(r==="array"&&Array.isArray(n)||r==="object"&&typeof n=="object"&&n!==null&&!Array.isArray(n))return n;throw new g(`${t} must be valid JSON ${r}`,h.USAGE)}function Ak(e,t){return t===void 0?!0:t==="array"?Array.isArray(e):t==="object"?typeof e=="object"&&e!==null&&!Array.isArray(e):typeof e===t}function Ik(e,t,r){if(t.const!==void 0&&R(e)!==R(t.const))return`${r} must equal ${R(t.const)}`;if(t.enum!==void 0&&!t.enum.some(n=>R(n)===R(e)))return`${r} must be one of ${t.enum.map(n=>R(n)).join("|")}`;if(!Ak(e,t.type))return`${r} must match configured type ${String(t.type)}`;if(typeof e=="string"){if(t.min_length!==void 0&&e.length<t.min_length)return`${r} must contain at least ${t.min_length} characters`;if(t.format==="date-time"&&!pn(e))return`${r} must be an RFC 3339 date-time`}}function Tk(e,t,r,n){if(Array.isArray(e)){if(t.min_items!==void 0&&e.length<t.min_items)return`${r} must contain at least ${t.min_items} items`;if(t.items)for(let[o,i]of e.entries()){let s=Xo(i,t.items,`${r}[${o}]`,n+1);if(s)return s}}}function Ck(e,t,r,n){if(typeof e!="object"||e===null||Array.isArray(e))return;let o=e;for(let i of t.required??[])if(!Object.hasOwn(o,i))return`${r}.${i} is required`;for(let[i,s]of Object.entries(o)){let a=t.properties?.[i];if(!a){if(t.additional_properties===!1)return`${r}.${i} is not allowed`;continue}let c=Xo(s,a,`${r}.${i}`,n+1);if(c)return c}}function Xo(e,t,r,n=0){if(n>kk)return`${r} value schema exceeds maximum depth`;let o=Ik(e,t,r);if(o)return o;let i=Tk(e,t,r,n);if(i)return i;let s=Ck(e,t,r,n);if(s)return s;if(!t.one_of)return;let a=0;for(let c of t.one_of)if(Xo(e,c,r,n+1)===void 0&&(a+=1,a>1))break;return a===1?void 0:`${r} must match exactly one configured schema variant`}function Ct(e,t,r){if(!e.value_schema||t===void 0)return t;let n=Xo(t,e.value_schema,r);if(n)throw new g(n,h.USAGE);return t}function Rk(e,t,r,n){let o=n==="option"&&Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return Ct(e,Ok(o,r,e.type),r)}function En(e,t,r,n="option"){let o=r??`--${e.cli_flag}`;if(e.type==="array"||e.type==="object")return Rk(e,t,o,n);if(e.repeatable||e.type==="string_array"){let s=Am(t);return e.type==="number"?Ct(e,s.map(a=>Sm(a,o)),o):e.type==="boolean"?Ct(e,s.map(a=>km(a,o)),o):Ct(e,s,o)}let i=Array.isArray(t)?t[t.length-1]:t;if(i!==void 0)return e.type==="number"?Ct(e,Sm(i,o),o):e.type==="boolean"?Ct(e,km(i,o),o):Ct(e,typeof i=="string"?i:String(i),o)}function xk(e,t){return!e.required&&!e.required_on_create?!1:e.required_types.length===0?!0:t?e.required_types.map(r=>r.toLowerCase()).includes(t.trim().toLowerCase()):!1}function gM(e,t,r){let n={},o=[];for(let i of t.command_to_fields.get("create")??[]){let s=Om(e,i);if(s===void 0){xk(i,r)&&o.push(`--${i.cli_flag}`);continue}n[i.metadata_key]=En(i,s)}return{values:n,missing_required_flags:[...new Set(o)].sort((i,s)=>i.localeCompare(s))}}function bM(e,t,r=["update"]){let n={},o=(r??["update"]).flatMap(s=>t.command_to_fields.get(s)??[]),i=new Set;for(let s of o){let a=Om(e,s);a!==void 0&&(i.has(s.metadata_key)||(i.add(s.metadata_key),n[s.metadata_key]=En(s,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]="c35d4830-d7d1-5ee4-99bc-ab52cc3e4e09")}catch{}})();var Ia=1,Ta=2;function vM(e){return Math.max(Ca(e),e.tests?.some(t=>t.updated_by!==void 0||t.updated_at!==void 0)?2:1)}function Ca(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:1}function Im(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=1))return e}function Nk(e,t=2,r=t){return e<r?"outdated":e>t?"ahead":"current"}function EM(e,t=2,r=t){let n=[],o=[];for(let i of e){let s=Nk(i.version,t,r);s==="outdated"?n.push(i.ref):s==="ahead"&&o.push(i.ref)}return{outdated:n.sort((i,s)=>i.localeCompare(s)),ahead:o.sort((i,s)=>i.localeCompare(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]="515840b7-cf86-5d71-8ac1-beac7fd7c8a8")}catch{}})();var Dk={"in-progress":"in_progress",cancelled:"canceled"};function Jo(e,t){if(t){let o=Oa(e,t);if(o)return o}if(typeof e!="string")return;let r=e.trim().toLowerCase();if(!r)return;let n=Dk[r]??r;if(Wt.includes(n))return n}function Pk(e,t){return Jo(e,t)??e}function AM(e,t){return t.terminal_statuses.has(Pk(e,t))}import{encode as Lk}from"@toon-format/toon";import{isDeepStrictEqual as Tm}from"node:util";import{decode as Mk}from"@toon-format/toon";(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]="aaa2be03-9478-5fbe-82e6-e4fc86e3735b")}catch{}})();function Ra(e){return{value:Mk(e),usedScalarBracketEscape:!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]="79626299-17a8-573a-9b66-ce37c65e2f5d")}catch{}})();var $k=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function jk(e){if(e.length===0)return[];let t=e.split(/\r?\n/),r=[];for(let n=0;n<t.length;n+=1){let o=t[n]??"",i=o.match($k);if(!i)continue;let s=i[1];r.push({line:n+1,marker:s,text:o})}return r}function Zo(e){return jk(e)[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]="2789e87f-0706-52e8-8f4c-3855c65c618c")}catch{}})();var Pa=new Set(["schema","tracker","auto","none"]),Dm=new Set(["source","isolated","snapshot"]),Fk=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),zk=new Set(["passed","failed","stopped","canceled"]),Uk=new Set(sd);function br(e){return e.replaceAll("\\","/")}function Pm(e){for(let t of e)if(t!==0)return t;return 0}function ei(e){for(let[t,r]of Object.entries(e))r===void 0&&delete e[t]}var Mm=["id","title","description","created_at","updated_at"],Hk=new Set(we);function $m(e){if(e?.schema)return{statusRegistry:wm(e.schema),fieldRegistry:vm(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function qk(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(r=>r.toLowerCase()).includes(t.trim().toLowerCase()):!1}function nt(e){let t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new g(`Invalid item metadata: ${e}`,h.GENERIC_FAILURE,{code:"item_document_invalid",reason:e.includes("required")?"missing_required_field":"schema_validation_error",...t?{field:t}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:e})}function On(e,t){throw new g(t,h.GENERIC_FAILURE,{code:"item_document_invalid",reason:"syntax_error",format:e,required:`Provide a syntactically valid ${e==="toon"?"TOON":"JSON Markdown"} item document.`,why:"The document could not be decoded far enough to validate item metadata."})}function jm(e,t){if(!t||typeof e!="object"||e===null)return;let r=Ca(e);if(!(r<=Ta))throw new g(`Stored item uses format version ${r}; this runtime supports up to ${Ta}. Upgrade pm before reading or changing this item.`,h.CONFLICT,{code:"item_format_version_unsupported",format_version:r,required:"Upgrade to a pm runtime supporting the stored item format.",nextSteps:["Preserve the original item and history; do not lower pm_format_version to bypass compatibility checks."]})}function Lm(e){let t=new Set(Hk);for(let r of e.fieldRegistry?.definitions??[])t.add(r.metadata_key);for(let r of e.extensionFieldNames)t.add(r);return t}function O(e,t){e||nt(t)}function An(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&nt(t),e}function xa(e,t){let r=e[t];O(typeof r=="string",`${t} must be a string`),O(je(r),`${t} must be a valid ISO timestamp`)}function Cm(e,t,r){let n=e[t];n!==void 0&&O(typeof n=="number"&&Number.isInteger(n)&&n>=1,`${r} must be an integer >= 1`)}function Ma(e,t,r){let n=e[t];n!==void 0&&(O(typeof n=="string",`${r} must be a string`),O(je(n),`${r} must be a valid ISO timestamp`))}function Vk(e){if(e!==void 0){O(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){O(typeof t=="string","event.recurrence.by_weekday entries must be strings");let r=t.trim().toLowerCase();O(Pr.includes(r),`event.recurrence.by_weekday entries must be one of: ${Pr.join(", ")}`)}}}function Bk(e){if(e!==void 0){O(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)O(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function Wk(e){if(e!==void 0){O(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)O(typeof t=="string","event.recurrence.exdates entries must be strings"),O(je(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function Gk(e){let t=An(e,"event.recurrence must be an object");O(typeof t.freq=="string","event.recurrence.freq must be a string");let r=t.freq.trim().toLowerCase();O(Zn.includes(r),`event.recurrence.freq must be one of: ${Zn.join(", ")}`),Cm(t,"interval","event.recurrence.interval"),Cm(t,"count","event.recurrence.count"),Ma(t,"until","event.recurrence.until"),Vk(t.by_weekday),Bk(t.by_month_day),Wk(t.exdates)}function Kk(e){for(let n of Mm)O(typeof e[n]=="string",`${n} is required and must be a string`);let t=e.type;O(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let r=e.pm_format_version;return r!==void 0&&O(typeof r=="number"&&Number.isInteger(r)&&r>=Ia,`pm_format_version must be an integer >= ${Ia}`),t}function Yk(e,t){let r=e.status;O(typeof r=="string"&&r.trim().length>0,"status must be a non-empty string");let n=t?.statusRegistry,o=Jo(r,n),i=n?n.definitions.map(s=>s.id):[...Wt];O(o!==void 0,`status must be one of: ${i.join(", ")}`)}function Xk(e){let t=e.priority;O(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let r=e.tags;O(Array.isArray(r),"tags must be an array");for(let n of r)O(typeof n=="string","tags entries must be strings")}function Jk(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){O(Number.isInteger(t)&&t>=0&&t<=100,"confidence number value must be an integer 0..100");return}if(typeof t=="string"){let r=t.trim().toLowerCase(),n=r==="med"||Jn.includes(r);O(n,`confidence string value must be one of: ${[...Jn,"med"].join(", ")}`);return}O(!1,"confidence must be a number or string")}}function Zk(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&nt("severity must be a string");let r=t.trim().toLowerCase(),n=r==="med"||Xn.includes(r);O(n,`severity value must be one of: ${[...Xn,"med"].join(", ")}`)}function Qk(e){e.regression!==void 0&&typeof e.regression!="boolean"&&nt("regression must be a boolean")}function eS(e){let t=e.reminders;if(t!==void 0){O(Array.isArray(t),"reminders must be an array");for(let r of t){let n=An(r,"reminders entries must be objects");O(typeof n.at=="string","reminder.at must be a string"),O(je(n.at),"reminder.at must be a valid ISO timestamp"),O(typeof n.text=="string","reminder.text must be a string"),O(n.text.trim().length>0,"reminder.text must not be empty")}}}function tS(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(O(typeof e[t]=="string",`event.${t} must be a string`),O(e[t].trim().length>0,`event.${t} must not be empty`))}function rS(e){e.recurrence!==void 0&&(Gk(e.recurrence),e.recurrence.until!==void 0&&O(ne(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function nS(e){let t=An(e,"events entries must be objects");O(typeof t.start_at=="string","event.start_at must be a string"),O(je(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(O(typeof t.end_at=="string","event.end_at must be a string"),O(je(t.end_at),"event.end_at must be a valid ISO timestamp"),O(ne(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),tS(t),t.all_day!==void 0&&O(typeof t.all_day=="boolean","event.all_day must be a boolean"),rS(t)}function oS(e){let t=e.events;if(t!==void 0){O(Array.isArray(t),"events must be an array");for(let r of t)nS(r)}}function iS(e){for(let t of["source_type","source_owner","design","external_ref"]){let r=e[t];r!==void 0&&O(typeof r=="string",`${t} must be a string`)}}function sS(e){let t=e.type_options;if(t===void 0)return;let r=An(t,"type_options must be an object");for(let[n,o]of Object.entries(r))O(n.trim().length>0,"type_options keys must be non-empty"),O(typeof o=="string","type_options values must be strings"),O(o.trim().length>0,"type_options values must be non-empty strings")}function aS(e,t,r){if(r?.fieldRegistry)for(let n of r.fieldRegistry.definitions){let o=e[n.metadata_key];if(o===void 0){qk(n,t)&&nt(`missing required schema field: ${n.metadata_key}`);continue}try{e[n.metadata_key]=En(n,o,`metadata field "${n.metadata_key}"`,"metadata")}catch(i){nt(String(i?.message).replace(/^Invalid\s+/u,""))}}}function cS(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let r=Lm(t),n=Object.keys(e).filter(o=>!r.has(o)).sort((o,i)=>o.localeCompare(i));n.length!==0&&(t.unknownFieldPolicy==="reject"?nt(`unknown schema fields are not allowed: ${n.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${n.join(",")}`))}function $a(e,t){let r=An(e,"item metadata must be an object"),n=Kk(r);Yk(r,t),Xk(r),Jk(r),Zk(r),Qk(r),xa(r,"created_at"),xa(r,"updated_at"),r.deadline!==void 0&&xa(r,"deadline"),eS(r),oS(r),Ma(r,"closed_at","closed_at"),Ma(r,"completed_at","completed_at"),iS(r),sS(r),aS(r,n,t),cS(r,t)}function dS(e){if(!(!e||e.length===0))return[...e].map((t,r)=>(O(t.created_at===void 0||typeof t.created_at=="string"&&pn(t.created_at),`dependencies.${r}.created_at requires a valid timestamp; restore the dependency timestamp from its source record`),{id:t.id.trim(),kind:t.kind,created_at:t.created_at,author:t.author?.trim()||void 0,source_kind:t.source_kind?.trim()||void 0,author_source:t.author_source})).sort((t,r)=>{let n=ne(t.created_at??"",r.created_at??"");if(n!==0)return n;let o=t.id.localeCompare(r.id);if(o!==0)return o;let i=t.kind.localeCompare(r.kind);return i!==0?i:(t.source_kind??"").localeCompare(r.source_kind??"")})}function Na(e){if(!(!e||e.length===0))return[...e].sort((t,r)=>{let n=ne(t.created_at,r.created_at);if(n!==0)return n;let o=t.text.localeCompare(r.text);return o!==0?o:t.author.localeCompare(r.author)})}function lS(e){if(!e||e.length===0)return;let t=[...e].map(r=>({at:r.at,text:r.text.trim()})).filter(r=>r.text.length>0).sort((r,n)=>{let o=ne(r.at,n.at);return o!==0?o:r.text.localeCompare(n.text)});return t.length===0?void 0:t}function uS(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!Zn.includes(t))return;let r=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>Pr.includes(s)))).sort((s,a)=>qi(s)-qi(a)),n=Array.from(new Set((e.by_month_day??[]).filter(s=>Number.isInteger(s)&&s>=1&&s<=31).map(s=>s))).sort((s,a)=>s-a),o=Array.from(new Set((e.exdates??[]).map(s=>s.trim()).filter(s=>je(s)))).sort((s,a)=>ne(s,a)),i={freq:t,interval:e.interval!==void 0&&e.interval>1?e.interval:void 0,count:e.count,until:e.until?.trim()||void 0,by_weekday:r.length>0?r:void 0,by_month_day:n.length>0?n:void 0,exdates:o.length>0?o:void 0};for(let[s,a]of Object.entries(i))a===void 0&&delete i[s];return i}function fS(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(mS).sort(pS)}function mS(e){let t={start_at:e.start_at,end_at:e.end_at||void 0,title:e.title?.trim()||void 0,description:e.description?.trim()||void 0,location:e.location?.trim()||void 0,all_day:e.all_day,timezone:e.timezone?.trim()||void 0,recurrence:uS(e.recurrence)};return ei(t),t}function pS(e,t){return Pm([ne(e.start_at,t.start_at),(e.end_at??"").localeCompare(t.end_at??""),(e.title??"").localeCompare(t.title??""),+!!e.all_day-+!!t.all_day,(e.timezone??"").localeCompare(t.timezone??""),(e.location??"").localeCompare(t.location??""),(e.description??"").localeCompare(t.description??""),JSON.stringify(e.recurrence??{}).localeCompare(JSON.stringify(t.recurrence??{}))])}function _S(e){if(!(!e||e.length===0))return e.map(t=>({path:br(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function yS(e){if(!e||e.length===0)return;let t=e.map(wS).filter(r=>r.run_id.length>0&&r.started_at.length>0&&r.finished_at.length>0&&r.recorded_at.length>0).sort((r,n)=>Pm([ne(r.recorded_at,n.recorded_at),r.run_id.localeCompare(n.run_id),r.kind.localeCompare(n.kind)]));return t.length>0?t:void 0}function hr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function hS(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function Da(e){return typeof e=="string"?e:""}function gS(e){if(!Array.isArray(e))return;let t=e.filter(n=>n!==null&&typeof n=="object"&&typeof n.name=="string"&&n.name.trim().length>0&&typeof n.value=="number"&&Number.isFinite(n.value)&&typeof n.recorded_at=="string"&&n.recorded_at.trim().length>0).map(n=>({name:n.name.trim(),value:n.value,unit:typeof n.unit=="string"&&n.unit.trim()||void 0,threshold:typeof n.threshold=="number"&&Number.isFinite(n.threshold)?n.threshold:void 0,recorded_at:n.recorded_at.trim()})),r=[...new Map(t.map(n=>[n.name,n])).values()].sort((n,o)=>n.name.localeCompare(o.name)).slice(0,32);return r.length>0?r:void 0}function Qo(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function bS(e){if(!Array.isArray(e))return;let t=e.filter(r=>r&&typeof r.command=="string"&&r.command.trim().length>0).slice(0,32).map(r=>({command:r.command.trim(),requested_pm_context_mode:Qo(r.requested_pm_context_mode,Pa),pm_context_mode:Qo(r.pm_context_mode,Pa),workspace_context_mode:Qo(r.workspace_context_mode,Dm),trust_reason:Qo(r.trust_reason,Fk)}));return t.length>0?t:void 0}function wS(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",r=e.kind==="test"||e.kind==="test-all"?e.kind:"test",n=zk.has(e.status)?e.status:"failed",o={run_id:t,kind:r,status:n,started_at:Da(e.started_at),finished_at:Da(e.finished_at),recorded_at:Da(e.recorded_at),attempt:hS(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:hr(e.passed)??0,failed:hr(e.failed)??0,skipped:hr(e.skipped)??0,items:hr(e.items),linked_tests:hr(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:gS(e.measurements),executions:bS(e.executions)};return ei(o),o}function vS(e){if(!(!Array.isArray(e)||e.length===0))return e.map(AS)}function kn(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0))].sort((r,n)=>r.localeCompare(n));return t.length>0?t:void 0}function za(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ua(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function Rm(e){if(!za(e))return;let t=Object.entries(e).map(([r,n])=>[r.trim(),String(n).trim()]).filter(([r,n])=>r.length>0&&!Ua(r)&&n.length>0).sort(([r],[n])=>r.localeCompare(n));return t.length>0?Object.fromEntries(t):void 0}function ES(e){if(!za(e))return;let t=Object.entries(e).map(([r,n])=>[r.trim(),Number(n)]).filter(([r,n])=>r.length>0&&!Ua(r)&&Number.isFinite(n)).sort(([r],[n])=>r.localeCompare(n));return t.length>0?Object.fromEntries(t):void 0}function kS(e){let t=e?.trim().toLowerCase();if(!(!t||!Pa.has(t)))return t}function SS(e){let t=e?.trim().toLowerCase();if(!(!t||!Dm.has(t)))return t}function OS(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!za(e))return{provenance_invalid:!0};let r=E(e.author),n=E(e.created_at),o=e.source_kind;return!r||!n||!je(n)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:r,created_at:n,source_kind:o,source_ref:E(e.source_ref)}}}function AS(e){let t={command:e.command?.trim()||void 0,path:e.path?br(e.path):void 0,scope:e.scope,timeout_seconds:typeof e.timeout_seconds=="number"&&Number.isFinite(e.timeout_seconds)&&e.timeout_seconds>0?e.timeout_seconds:void 0,pm_context_mode:kS(e.pm_context_mode),workspace_context_mode:SS(e.workspace_context_mode),...OS(e.provenance,e.provenance_invalid),updated_by:E(e.updated_by),updated_at:E(e.updated_at),env_set:Rm(e.env_set),env_clear:kn(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:kn(e.assert_stdout_contains),assert_stdout_regex:kn(e.assert_stdout_regex),assert_stderr_contains:kn(e.assert_stderr_contains),assert_stderr_regex:kn(e.assert_stderr_regex),assert_stdout_min_lines:hr(e.assert_stdout_min_lines),assert_json_field_equals:Rm(e.assert_json_field_equals),assert_json_field_gte:ES(e.assert_json_field_gte),note:e.note?.trim()||void 0};return ei(t),t}function IS(e){if(!(!e||e.length===0))return[...e].map(t=>({path:br(t.path),scope:t.scope,note:t.note?.trim()||void 0})).sort((t,r)=>{let n=t.scope.localeCompare(r.scope);if(n!==0)return n;let o=t.path.localeCompare(r.path);return o!==0?o:(t.note??"").localeCompare(r.note??"")})}function E(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function TS(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=E(n.id),i=E(n.kind);if(!o||!i)continue;let s={id:o,kind:i},a=E(n.note);a&&(s.note=a),n.required_before_step===!0&&(s.required_before_step=!0),t.push(s)}return t.length>0?t:void 0}function CS(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=E(n.path);if(!o)continue;let i={path:br(o)};(n.scope==="project"||n.scope==="global")&&(i.scope=n.scope);let s=E(n.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function RS(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=E(n.command),i=E(n.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=br(i));let a=E(n.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function xS(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=E(n.path);if(!o)continue;let i={path:br(o)};(n.scope==="project"||n.scope==="global")&&(i.scope=n.scope);let s=E(n.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function NS(e){if(e===null||typeof e!="object")return;let t=e,r=E(t.id),n=E(t.title),o=E(t.status),i=o&&Uk.has(o)?o:void 0,s=Wn(t.order)??Number.NaN,a=typeof t.created_at=="string"?t.created_at:"",c=typeof t.updated_at=="string"?t.updated_at:"";if(!r||!n||!i||!Number.isFinite(s)||!a||!c)return;let d={id:r,order:s,title:n,status:i,created_at:a,updated_at:c};return DS(d,t),d}function DS(e,t){let r=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(let[i,s]of r){let a=E(t[s]);a&&(e[i]=a)}let n=typeof t.completed_at=="string"?t.completed_at:void 0;n&&n.length>0&&(e.completed_at=n);let o=[["linked_items","linked_items",TS],["files","files",CS],["tests","tests",RS],["docs","docs",xS]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function PS(e){if(!Array.isArray(e))return;let t=e.flatMap(r=>{let n=NS(r);return n?[n]:[]});return t.sort((r,n)=>r.order-n.order),t.length>0?t:void 0}function MS(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=typeof n.ts=="string"?n.ts:"",i=typeof n.author=="string"?n.author:"",s=E(n.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=E(n.rationale);c&&(a.rationale=c);let d=E(n.evidence);d&&(a.evidence=d);let l=E(n.step_id);l&&(a.step_id=l),t.push(a)}return t.length>0?t:void 0}function $S(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=typeof n.ts=="string"?n.ts:"",i=typeof n.author=="string"?n.author:"",s=E(n.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=E(n.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function jS(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=E(n.text);if(!o)continue;let i={text:o},s=E(n.command);s&&(i.command=s);let a=E(n.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function LS(e){if(!e)return;let t=Object.entries(e).map(([r,n])=>[r.trim(),n.trim()]).filter(([r,n])=>r.length>0&&n.length>0).sort((r,n)=>r[0].localeCompare(n[0]));if(t.length!==0)return Object.fromEntries(t)}function gr(e){let t=0;for(;t<e.length&&e[t]===`
36
- `;)t+=1;return e.slice(t).trimEnd()}function FS(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Jn.includes(t))return t}function zS(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Xn.includes(t))return t}function Sn(e){return e||void 0}function US(e,t){let r=e,n=t;for(let[o,i]of Object.entries(n))Ua(o)||Object.prototype.hasOwnProperty.call(r,o)||i===void 0||(r[o]=i)}function HS(e,t){if(!t?.fieldRegistry)return;let r=e;for(let n of t.fieldRegistry.definitions){let o=r[n.metadata_key];o!==void 0&&(r[n.metadata_key]=En(n,o,`metadata field "${n.metadata_key}"`,"metadata"))}}function qS(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let r=Lm(t),n=Object.keys(e).filter(o=>!r.has(o)).sort((o,i)=>o.localeCompare(i));n.length>0&&t.unknownFieldPolicy==="reject"&&nt(`unknown schema fields are not allowed: ${n.join(", ")}`),n.length>0&&t.onWarning?.(`item_unknown_schema_fields:${n.join(",")}`)}function ti(e,t={}){let r=$m(t),n=Jo(e.status,r?.statusRegistry)??e.status,o=Array.from(new Set((Array.isArray(e.tags)?e.tags:[]).filter(s=>typeof s=="string").map(s=>s.trim().toLowerCase()).filter(Boolean))).sort((s,a)=>s.localeCompare(a)),i={id:e.id,title:e.title,description:e.description,type:e.type,pm_format_version:Im(e.pm_format_version),source_type:E(e.source_type),type_options:LS(e.type_options),status:n,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:dS(e.dependencies),comments:Na(e.comments),notes:Na(e.notes),learnings:Na(e.learnings),files:_S(e.files),tests:vS(e.tests),test_runs:yS(e.test_runs),docs:IS(e.docs),deadline:Sn(e.deadline),reminders:lS(e.reminders),events:fS(e.events),closed_at:Sn(e.closed_at),completed_at:Sn(e.completed_at),assignee:E(e.assignee),claim_principal:E(e.claim_principal),source_owner:E(e.source_owner),author:Sn(e.author),estimated_minutes:e.estimated_minutes,acceptance_criteria:e.acceptance_criteria??void 0,design:e.design??void 0,external_ref:e.external_ref??void 0,definition_of_ready:E(e.definition_of_ready),order:e.order,goal:E(e.goal),objective:E(e.objective),value:E(e.value),impact:E(e.impact),outcome:E(e.outcome),why_now:E(e.why_now),parent:E(e.parent),reviewer:E(e.reviewer),risk:e.risk??void 0,confidence:FS(e.confidence),sprint:E(e.sprint),release:E(e.release),blocked_by:E(e.blocked_by),blocked_reason:E(e.blocked_reason),unblock_note:E(e.unblock_note),reporter:E(e.reporter),severity:zS(e.severity),environment:E(e.environment),repro_steps:E(e.repro_steps),resolution:E(e.resolution),expected_result:E(e.expected_result),actual_result:E(e.actual_result),affected_version:E(e.affected_version),fixed_version:E(e.fixed_version),component:E(e.component),regression:e.regression,customer_impact:E(e.customer_impact),close_reason:Sn(e.close_reason),plan_mode:E(e.plan_mode),plan_scope:E(e.plan_scope),plan_harness:E(e.plan_harness),plan_resume_context:E(e.plan_resume_context),plan_steps:PS(e.plan_steps),plan_decisions:MS(e.plan_decisions),plan_discoveries:$S(e.plan_discoveries),plan_validation:jS(e.plan_validation)};return US(i,e),HS(i,r),qS(i,r),ei(i),i}function Fm(e){return A(e,we)}function VS(e){let t=0,r=!1,n=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(r){if(n){n=!1;continue}if(i==="\\"){n=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="{"){t+=1;continue}if(i==="}"&&(t-=1,t===0))return o}return-1}function BS(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=VS(e);if(t<0)return{frontMatter:"",body:e};let r=e.slice(0,t+1),n=e.slice(t+1).replace(/^\r?\n+/,"");return{frontMatter:r,body:n}}function WS(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,r=t.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!r)return{content:t,stripped:!1};let n=r[0].length;for(;n<t.length;){let o=t.indexOf(`
37
- `,n),i=o===-1?t.length:o,s=t.slice(n,i).replace(/\r$/,""),a=o===-1?i:i+1;if(s.trim()==="---")return{content:t.slice(a).replace(/^\s+/,""),stripped:!0};n=a}return{content:t,stripped:!1}}function ja(e,t){return ti(e,{...t,onWarning:void 0})}function GS(e,t,r={}){let n=WS(e);n.stripped&&r.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=BS(n.content);o||(e.trimStart().startsWith("{")&&On("json_markdown","JSON front matter is not valid JSON"),On("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{On("json_markdown","JSON front matter is not valid JSON")}return jm(s,r.requireSupportedFormat),$a(s,t),{metadata:ja(s,r),body:gr(i)}}function KS(e,t,r={}){let n;try{n=Ra(e).value}catch{On("toon","TOON item document is not valid TOON")}O(typeof n=="object"&&n!==null&&!Array.isArray(n),"TOON item document must be an object");let o=n;if(jm(Object.prototype.hasOwnProperty.call(o,"front_matter")?o.front_matter:o,r.requireSupportedFormat),!Mm.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&On("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return $a(o.front_matter,t),O(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:ja(o.front_matter,r),body:gr(typeof o.body=="string"?o.body:"")};let{body:i,...s}=o;return O(i===void 0||typeof i=="string","TOON item document body must be a string"),$a(s,t),{metadata:ja(s,r),body:gr(typeof i=="string"?i:"")}}function YS(e,t={}){let r=ti(e.metadata,t),n=Fm(r),o=gr(e.body??"");Fa(JSON.parse(JSON.stringify(n))),Fa({body:o});let i=JSON.stringify(n,null,2);return o?`${i}
38
-
39
- ${o}
40
- `:`${i}
41
- `}var XS=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function La(e,t){return typeof e=="string"?xm(e,t):e===null||typeof e!="object"?null:Array.isArray(e)?Nm(e.map((r,n)=>()=>La(r,`${t}[${n}]`))):Nm(Object.entries(e).map(([r,n])=>()=>{let o=t?`${t}.${r}`:r;return xm(r,`${o} (key)`)??La(n,o)}))}function xm(e,t){let r=e.search(XS);return r<0?null:{path:t,index:r}}function Nm(e){for(let t of e){let r=t();if(r!==null)return r}return null}function Fa(e){let t=La(e,"");if(t!==null)throw new g(`Item field ${t.path} contains an unpaired surrogate code unit at index ${t.index}; persisted item text requires well-formed Unicode.`,h.USAGE,{code:"text_unpaired_surrogate",field:t.path,required:"Provide well-formed UTF-16 text: keep emoji and other astral characters whole and avoid lone \\uD800-\\uDFFF JSON escapes.",why:"Persisted item text must remain well-formed in every supported format; a lone surrogate can cause an unclassified encoder fault.",nextSteps:[`Repair the ${t.path} value (for example String.prototype.toWellFormed() or re-truncate on a character boundary) and retry.`,"Run pm <command> --help --json to review the text fields the command accepts."]})}function JS(e,t={}){let r=ti(e.metadata,t),n=Fm(r),o=gr(e.body??""),i={...n,body:o},s=JSON.parse(JSON.stringify(i));Fa(s);let a=Lk(s),c;try{c=Ra(a).value}catch(d){throw new g("Refusing to persist a TOON item document that the configured decoder cannot read back.",h.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_error",format:"toon",required:"Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",why:d instanceof Error?d.message:String(d)})}if(!Tm(c,s)){let d=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},l=Object.keys(s).find(u=>!Tm(s[u],d[u]))??"document";throw new g(`Refusing to persist a lossy TOON item document; round-trip mismatch at field "${l}".`,h.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_mismatch",format:"toon",field:l,required:"Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",why:"The encoded document decoded to a value different from the canonical item payload."})}return`${a}
42
- `}function BM(e,t={}){let r=Zo(e);if(r)throw new g(`Merge conflict markers detected in item document at line ${r.line} (${r.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,h.GENERIC_FAILURE,{code:"merge_conflict_markers_detected",reason:"merge_conflict",required:"Resolve merge-conflict markers in the item file before parsing or mutation commands.",why:"Partially merged documents can corrupt item metadata and history integrity.",examples:["git status","git add <resolved-file> && git commit"],nextSteps:["Resolve conflicts, save the file, then rerun the pm command."]});let n=t.format??"toon",o=$m(t);return n==="toon"?KS(e,o,t):GS(e,o,t)}function WM(e,t={}){return(t.format??"toon")==="toon"?JS(e,t):YS(e,t)}function wr(e,t={}){return{metadata:ti(e.metadata,t),body:gr(e.body??"")}}(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]="82c79093-2a40-5b4c-8d41-637b0ae03c4f")}catch{}})();function zm(e){return e}import{AsyncLocalStorage as ZS}from"node:async_hooks";(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]="1fbb183b-c6d8-5834-b4cb-e4fb515572b9")}catch{}})();var Ha=new ZS,Um=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function ri(e,t){let r=typeof e=="string"?e.trim():"";return r.length>0?r.slice(0,t):void 0}function Rt(e,t){if(e===void 0)return;let r=typeof e=="object"&&e!==null?e:{},n=ri(r.id,128),o=ri(r.parent_id,128);if(n===void 0||!Um.test(n)||o!==void 0&&!Um.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=ri(r.label,256);return{id:n,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function vr(e){let t={};for(let[r,n]of Object.entries(e??{}).slice(0,32)){let o=r.trim().toLowerCase().slice(0,64),i=ri(n,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function QS(e,t,r){let n=Ha.getStore(),o=vr({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=Rt(t.PM_AGENT_EPISODE_ID===void 0?void 0:{id:t.PM_AGENT_EPISODE_ID,label:t.PM_AGENT_EPISODE_LABEL,parent_id:t.PM_AGENT_EPISODE_PARENT_ID},!1),s={...vr(n?.provenance),...o,...vr(e?.provenance)},a=Rt(e?.episode,!1)??Rt(r,!1)??i??Rt(n?.episode,!1);return Object.keys(s).length===0&&a===void 0?void 0:{...Object.keys(s).length===0?{}:{provenance:s},...a===void 0?{}:{episode:a}}}function qa(e,t){return QS(e.session_context,t,e.client_info?.episode)??{}}function XM(e,t){let r=Ha.getStore(),n=Rt(e.episode,!0),o=Rt(r?.episode,!1),i=n!==void 0&&n.parent_id===void 0&&o!==void 0?{...n,parent_id:o.id}:n,s={...vr(r?.provenance),...vr(e.provenance)};return Ha.run({...Object.keys(s).length===0?{}:{provenance:s},...i===void 0?o===void 0?{}:{episode:o}:{episode:i}},t)}function JM(e){let t=vr(e.provenance),r=Rt(e.episode,!0);return{...r===void 0?{}:{PM_AGENT_EPISODE_ID:r.id,...r.label===void 0?{}:{PM_AGENT_EPISODE_LABEL:r.label},...r.parent_id===void 0?{}:{PM_AGENT_EPISODE_PARENT_ID:r.parent_id}},...t.role===void 0?{}:{PM_AGENT_SESSION_ROLE:t.role},...t.topic===void 0?{}:{PM_AGENT_SESSION_TOPIC:t.topic}}}import{createHash as Hm}from"node:crypto";import{existsSync as Va,promises as qm,readFileSync as eO}from"node:fs";import Ce 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]="06c9f6f4-c2f0-549c-9a0f-4f4269cc5f49")}catch{}})();var tO="session.json";function Ba(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function Vm(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,r=["implementer","planner","release-operator"].includes(String(t.role)),n=["high","medium"].includes(String(t.confidence)),o=Ba(t.topic,256),i=Array.isArray(t.evidence)&&t.evidence.length<=32&&t.evidence.every(c=>typeof c=="string"&&c.length<=128),s=Array.isArray(t.active_item_ids)&&t.active_item_ids.length<=64&&t.active_item_ids.every(c=>Ba(c,128)),a=t.focused_item_id===void 0||Ba(t.focused_item_id,128);if([r,n,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function rO(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=Object.entries(e).slice(0,128).flatMap(([r,n])=>{let o=Vm(n);return o&&r.length<=128?[[r,o]]:[]});return t.length>0?Object.fromEntries(t):void 0}function Wa(e){return Ce.join(Yi(e),tO)}async function Bm(e){try{let t=await qm.readFile(Wa(e),"utf8"),r=JSON.parse(t);if(r===null||typeof r!="object"||Array.isArray(r))return{};let n=r,o=n.focused_item,i=rO(n.semantic_attribution);return typeof o=="string"&&o.trim().length>0?{focused_item:o,...i?{semantic_attribution:i}:{}}:i?{semantic_attribution:i}:{}}catch{return{}}}async function Ga(e,t){let r=await ce(e,"session-state",S.locks.ttl_seconds,"session-state",!1,!0,S.locks.wait_ms);try{let n=await Bm(e);t(n);let o=Wa(e);await qm.mkdir(Ce.dirname(o),{recursive:!0}),await pt(o,JSON.stringify(n))}finally{await r()}}function Ka(e){return/#([a-f0-9]{24})$/u.exec(e.trim())?.[1]??`author-${Hm("sha256").update(e).digest("hex").slice(0,24)}`}function Ya(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].slice(0,32).map(t=>t.slice(0,128))}function Xa(e){let t=[...new Set(e)].sort((n,o)=>n.localeCompare(o));if(t.length===1)return t[0];let r=`workset:${t.join("+")}`;return r.length<=256?r:`workset:${t.join("+").slice(0,230)}+${Hm("sha256").update(t.join("\0")).digest("hex").slice(0,12)}`}async function Ja(e,t,r){await Ga(e,n=>{let o={...n.semantic_attribution},i=r(o[t]);i===void 0?delete o[t]:o[t]=i,Object.keys(o).length===0?delete n.semantic_attribution:n.semantic_attribution=o})}async function s$(e){let t=Ka(e.principal);await Ja(e.pmRoot,t,r=>{let n=[...new Set([...r?.active_item_ids??[],e.itemId])].slice(-64).sort((i,s)=>i.localeCompare(s)),o=r?.focused_item_id;return{role:"implementer",topic:o??Xa(n),confidence:o?"high":"medium",rule_version:"v2",evidence:Ya([...n.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:n,...o?{focused_item_id:o}:{}}})}async function a$(e){let t=Ka(e.principal);await Ja(e.pmRoot,t,r=>{if(!r)return;let n=r.active_item_ids.filter(i=>i!==e.itemId);if(n.length===0&&!r.focused_item_id)return;let o=r.focused_item_id;return{...r,role:"release-operator",topic:o??Xa(n),confidence:o?"high":"medium",evidence:Ya([...n.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],`release:${e.itemId}`]),active_item_ids:n}})}async function c$(e){let t=Ka(e.principal);await Ja(e.pmRoot,t,r=>{let n=r?.active_item_ids??[];if(!e.itemId&&n.length===0)return;let o=e.itemId;return{role:o?"planner":r.role,topic:o??Xa(n),confidence:o?"high":"medium",rule_version:"v2",evidence:Ya([...n.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:n,...o?{focused_item_id:o}:{}}})}function nO(e,t){let r=t.PM_PATH?.trim();if(r){let o=Ce.resolve(e,r);if(Va(Ce.join(o,"settings.json")))return o;let i=Ce.join(o,".agents","pm");if(Va(Ce.join(i,"settings.json")))return i}let n=Ce.resolve(e);for(let o=0;o<32;o+=1){let i=Ce.join(n,".agents","pm");if(Va(Ce.join(i,"settings.json")))return i;let s=Ce.dirname(n);if(s===n)break;n=s}}function Wm(e){if(!e.key)return;let t=nO(e.cwd,e.env);if(t)try{let r=JSON.parse(eO(Wa(t),"utf8"));return Vm(r.semantic_attribution?.[e.key])}catch{return}}async function d$(e){return(await Bm(e)).focused_item}async function l$(e,t){await Ga(e,r=>{r.focused_item=t})}async function u$(e){await Ga(e,t=>{delete t.focused_item})}import{AsyncLocalStorage as rc}from"node:async_hooks";import{createHash as oO}from"node:crypto";import le from"node:fs";import Xm from"node:os";import Dt 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]="a69b86e2-6633-5abc-81b7-6a54a592d36c")}catch{}})();var nc=["model","effort","role","topic","version"],ii=new rc,Jm=new rc,si=new rc,oc=[{harness:"claude-code",environment_keys:["CLAUDE_CODE","CLAUDECODE"],model_environment_keys:["ANTHROPIC_MODEL","CLAUDE_MODEL"],session_environment_keys:["CLAUDE_CODE_SESSION_ID"],provenance_environment_keys:{effort:["CLAUDE_EFFORT"]},provenance_resolvers:{model:"claude_session_file",version:"claude_session_file"},provenance_unavailable_dimensions:["role","topic"],argv_markers:["claude","claude-code"],client_names:["claude","claude-code","claude code"]},{harness:"codex",environment_keys:["CODEX_HOME","CODEX_CI","CODEX_THREAD_ID"],model_environment_keys:["CODEX_MODEL"],session_environment_keys:["CODEX_THREAD_ID"],provenance_environment_keys:{effort:["CODEX_REASONING_EFFORT","CODEX_EFFORT"],role:["CODEX_SESSION_ROLE"]},provenance_resolvers:{model:"codex_session_file",effort:"codex_session_file",version:"ai_agent_version"},provenance_unavailable_dimensions:["topic"],argv_markers:["codex"],client_names:["codex"]},{harness:"pi",environment_keys:["PI_AGENT","PI_CODING_AGENT"],model_environment_keys:["PI_MODEL"],session_environment_keys:["PI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["pi"],client_names:["pi"]},{harness:"opencode",environment_keys:["OPENCODE","OPENCODE_SESSION_ID"],model_environment_keys:["OPENCODE_MODEL"],session_environment_keys:["OPENCODE_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["opencode"],client_names:["opencode"]},{harness:"cursor",environment_keys:["CURSOR_AGENT","CURSOR_TRACE_ID"],model_environment_keys:["CURSOR_MODEL"],session_environment_keys:["CURSOR_TRACE_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["cursor"],client_names:["cursor"]},{harness:"aider",environment_keys:["AIDER","AIDER_MODEL"],model_environment_keys:["AIDER_MODEL"],session_environment_keys:["AIDER_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["aider"],client_names:["aider"]},{harness:"gemini-cli",environment_keys:["GEMINI_CLI","GEMINI_CLI_HOME"],model_environment_keys:["GEMINI_MODEL"],session_environment_keys:["GEMINI_CLI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["gemini","gemini-cli"],client_names:["gemini","gemini-cli","gemini cli"]},{harness:"ci",environment_keys:["CI","GITHUB_ACTIONS","BUILDKITE","GITLAB_CI"],provenance_unavailable_dimensions:["model","effort","role","topic"],argv_markers:[],client_names:[]}],Zm=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),iO=Object.freeze({...Zm,max_bytes:4194304}),Za=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function sO(e){let t=it(e).provenance_unavailable_dimensions,r=new Set(["model","version",...Object.keys(e.provenance_environment_keys??{}),...Object.keys(e.provenance_resolvers??{})]);return Object.freeze({contract_version:1,adapter_version:"v1",priority:0,harness:e.harness,descriptor:e,supported_dimensions:Object.freeze([...r].sort()),native_sources:Object.freeze(["environment","argv","mcp_client",...Object.values(e.provenance_resolvers??{}).some(n=>n?.endsWith("session_file"))?["session_file"]:[]]),probe_policy:e.harness==="codex"?iO:Zm,normalization:Object.freeze({model_family:"v1",effort:"v1",preserve_raw:!0}),confidence:"high",waivers:Object.freeze(Object.fromEntries(t.map(n=>[n,"Harness does not expose this dimension."])))})}var Qm=Object.freeze(oc.filter(e=>e.harness!=="ci").map(sO).sort((e,t)=>e.harness.localeCompare(t.harness))),Nt=new Map,Er=new Map;function H(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function ot(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function it(e){let t=e.harness.trim().toLowerCase();if(!Za.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:ot(e.environment_keys),model_environment_keys:ot(e.model_environment_keys),session_environment_keys:ot(e.session_environment_keys),provenance_environment_keys:Object.fromEntries(Object.entries(e.provenance_environment_keys??{}).slice(0,32).map(([r,n])=>[r.trim().toLowerCase().slice(0,64),ot(n)]).filter(([r])=>Za.test(r))),provenance_resolvers:Object.fromEntries(Object.entries(e.provenance_resolvers??{}).slice(0,32).map(([r,n])=>[r.trim().toLowerCase().slice(0,64),n]).filter(r=>typeof r[0]=="string"&&Za.test(r[0])&&(r[1]==="ai_agent_version"||r[1]==="claude_session_file"||r[1]==="codex_session_file"))),provenance_unavailable_dimensions:ot(e.provenance_unavailable_dimensions).map(r=>r.toLowerCase()),argv_markers:ot(e.argv_markers).map(r=>r.toLowerCase()),client_names:ot(e.client_names).map(r=>r.toLowerCase())}}var ep=oc.map(it);function aO(e,t){return JSON.stringify(e)===JSON.stringify(t)}function oi(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(r=>r.length>0).includes(t)||e.trim().toLowerCase()===t}function ic(e=[]){let t=new Map(oc.filter(o=>o.harness!=="ci").map(o=>[o.harness,it(o)]));for(let{adapter:o}of Nt.values())t.set(o.harness,it(o.descriptor));let r=[...t.values(),...ep.filter(o=>o.harness==="ci"),...[...Er.values()].map(o=>o.descriptor),...si.getStore()?.descriptors??[],...e.map(it)],n=new Set;for(let o of r){if(n.has(o.harness))throw new Error(`Harness signal descriptor collision for "${o.harness}"`);n.add(o.harness)}return r}function sc(e,t){for(let r of t??[]){let n=H(e[r]);if(n)return n.slice(0,256)}}function cO(e,t){if(t==="role"){let r=e.slice(0,8).map(n=>n.trim().toLowerCase()).find(n=>["claim","create","update","close","release","review"].includes(n));if(r==="review")return"reviewer";if(r)return"implementer"}}function tp(e,t){let r=t==="model"?["--model","--agent-model"]:[`--agent-${t}`],n=e.slice(0,8);for(let o=0;o<n.length;o+=1){let i=n[o].slice(0,512);if(r.includes(i))return H(n[o+1])?.slice(0,256);let s=r.find(a=>i.startsWith(`${a}=`));if(s)return H(i.slice(s.length+1))?.slice(0,256)}}var dO=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function xt(e,t){if(e!=="role"||t===void 0)return t;let r=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return dO.has(r)?r:void 0}function Qa(e,t){return H(e?.[t])?.slice(0,256)}var lO=1048576,tc=4194304,ni=new Map,Gm=Object.freeze({}),ec=new Map,Km=Object.freeze({});function Ym(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function uO(e){let t;try{t=JSON.parse(e)}catch{return Km}let r=Ym(t);if(!r)return Km;let n=[{value:r,depth:0}],o=0,i,s;for(;n.length>0&&o<64;){let a=n.shift();if(o+=1,i??=H(a.value.model)?.slice(0,256),s??=H(a.value.version)?.slice(0,256),i&&s)break;if(!(a.depth>=4))for(let c of Object.values(a.value)){let d=Ym(c);d&&n.push({value:d,depth:a.depth+1})}}return Object.freeze({model:i,version:s})}function rp(e){try{return le.lstatSync(e).isFile()?"available":"missing"}catch(t){return Se(t)?"missing":"failed"}}function fO(e,t){let r;try{r=le.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).sort((o,i)=>o.name.localeCompare(i.name)).slice(0,512).map(o=>{let i=Dt.join(e,o.name,`${t}.jsonl`);return{candidate:i,status:rp(i)}})}catch(o){return{status:Se(o)?"missing":"failed"}}let n=r.filter(({status:o})=>o==="available").map(({candidate:o})=>o);return n.length===0?{status:r.some(({status:o})=>o==="failed")?"failed":"missing"}:n.length>1?{status:"ambiguous"}:{status:"available",path:n[0]}}function np(e,t){let r=H(t.CLAUDE_CODE_SESSION_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return{status:"unavailable"};let n=Dt.resolve(e.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),o=Dt.join(e.home_dir??Xm.homedir(),".claude","projects"),i=Dt.join(o,n,`${r}.jsonl`),s=H(e.session_file),a=s&&Dt.basename(s)===`${r}.jsonl`?s:void 0;for(let c of[a,i]){if(!c)continue;let d=rp(c);if(d==="available")return{status:d,path:c};if(d==="failed")return{status:d}}return fO(o,r)}function mO(e,t,r){let n=np(t,r);if(n.status==="available")try{let o=le.openSync(n.path,le.constants.O_RDONLY|le.constants.O_NOFOLLOW);try{let i=le.fstatSync(o),s=`${n.path}\0${i.size}\0${i.mtimeMs}`,a=ec.get(s);if(a)return a[e];let c=Math.min(i.size,lO),d=Math.min(c,Math.ceil(c/2)),l=Math.min(c-d,i.size-d),u=Buffer.alloc(d);le.readSync(o,u,0,d,0);let f=Buffer.alloc(l);l>0&&le.readSync(o,f,0,l,i.size-l);let m={},_=i.size<=c?Buffer.concat([u,f]).toString("utf8").split(`
43
- `):[...u.toString("utf8").split(`
44
- `).slice(0,4096),...f.toString("utf8").split(`
45
- `).slice(-4096)];for(let w of _){if(w.length===0||w.length>262144)continue;let v=uO(w);if(m.model??=v.model,m.version??=v.version,m.model&&m.version)break}let y=Object.freeze(m);return ec.clear(),ec.set(s,y),y[e]}finally{le.closeSync(o)}}catch{return}}function pO(e,t){let r=0,n=(o,i)=>{if(i>4||r>=512)return;let s;try{s=le.readdirSync(o,{withFileTypes:!0}).sort((a,c)=>c.name.localeCompare(a.name))}catch{return}for(let a of s){if(r+=1,r>512)return;let c=Dt.join(o,a.name);if(a.isFile()&&a.name.endsWith(`-${t}.jsonl`))return c;if(a.isDirectory()){let d=n(c,i+1);if(d)return d}}};return n(e,0)}function _O(e){if(e<=tc)return[{offset:0,length:e}];let t=Math.floor(tc/2);return[{offset:e-t,length:t},{offset:0,length:t}]}function yO(e,t){if(t.length===0||t.length>262144)return;let r;try{r=JSON.parse(t)}catch{return}if(typeof r!="object"||r===null||Array.isArray(r))return;let n=r;if(n.type!=="turn_context")return;let o=typeof n.payload=="object"&&n.payload!==null?n.payload:void 0;e.model??=H(o?.model)?.slice(0,256),e.effort??=H(o?.effort)?.slice(0,256)}function hO(e,t){let r={},n=4096;for(let o of _O(t)){let i=Buffer.alloc(o.length);le.readSync(e,i,0,o.length,o.offset);let s=i.toString("utf8").split(`
46
- `).reverse().slice(0,n);n-=s.length;for(let a of s)if(yO(r,a),r.model&&r.effort)break;if(r.model&&r.effort||n<=0)break}return r}function gO(e,t,r){let n=H(r.CODEX_THREAD_ID);if(!n||!/^[A-Za-z0-9_-]{1,128}$/u.test(n))return;let o=Dt.join(t.home_dir??Xm.homedir(),".codex","sessions"),i=`${o}\0${n}`,s=ni.get(i);if(s)return s[e];let a=pO(o,n);if(!a){ni.set(i,Gm);return}try{let c=le.openSync(a,"r");try{let d=le.fstatSync(c).size,l=hO(c,d);return ni.set(i,l),l[e]}finally{le.closeSync(c)}}catch{ni.set(i,Gm);return}}function bO(e,t,r,n){let o=si.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(H(r.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let i=n?.provenance_resolvers[e];if(i==="claude_session_file")return mO(e,t,r);if(i==="codex_session_file")return gO(e,t,r);if(i==="ai_agent_version"){let s=H(r.AI_AGENT);return!s||!n||!oi(s,n.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(s)?.[1]?.slice(0,256)}}function wO(e,t,r,n){if(e==="ai_agent_version"){let o=H(n.AI_AGENT);return o!==void 0&&oi(o,t.harness)?"available":"unavailable"}return e==="codex_session_file"?H(n.CODEX_THREAD_ID)!==void 0?"available":"unavailable":np(r,n).status}function ac(e){return e||(Jm.getStore()??{env:process.env,argv:process.argv})}function vO(e,t,r,n){let o=e.environment_keys.some(a=>H(t[a])!==void 0),i=e.argv_markers.some(a=>r.some(c=>{let d=c.replaceAll("\\","/");return oi(d.slice(d.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>n===a||oi(n,a));return o||i||s}function EO(e,t){if(!t)return;let r;if(e==="topic"&&(r=t.topic),e==="role"&&(r=t.role),!!r)return{value:r,source:"inferred",confidence:t.confidence,rule_version:t.rule_version,evidence:t.evidence}}function kO(e){let t=e.find(([r])=>r!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function SO(e,t,r,n,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...nc,...Object.keys(n?.provenance_environment_keys??{})]),c,d,l;a.has(e)&&(c=xt(e,H(r[s])?.slice(0,256)),l=xt(e,tp(t.argv??[],e)),d=xt(e,cO(t.argv??[],e)));let u={...n?.provenance_environment_keys,model:n?.model_environment_keys},f={...t.client_info?.provenance,model:t.client_info?.model},m=Qa(o?.provenance,e),_=xt(e,sc(r,u[e])),y=xt(e,Qa(f,e)),w=xt(e,Qa(t.provenance,e)),v=bO(e,t,r,n);return kO([[c,"override"],[m,"session"],[l,"argv"],[_,"environment"],[y,"mcp_client"],[w,"host"],[v,"probe"]])??EO(e,i)??(d?{value:d,source:"argv"}:void 0)}function OO(e,t){if(!(!e||!t))return oO("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function AO(e,t,r,n,o){let i=Object.keys(r?.provenance_environment_keys??{}),s=new Set([...nc,...i,...Object.keys(r?.provenance_resolvers??{}),...Object.keys(e.provenance??{}),...Object.keys(e.client_info?.provenance??{}),...Object.keys(n?.provenance??{})]),a={};for(let c of s){let d=SO(c,e,t,r,n,o);d?a[c]=d:r&&(c!=="version"||r.provenance_unavailable_dimensions.includes(c))&&(a[c]=null)}return a}function v$(e){let t=e.map(it),r=new Map(ep.map(i=>[i.harness,i])),n=new Set;for(let i of t){if(n.has(i.harness)||r.has(i.harness))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);let s=Er.get(i.harness);if(s&&!aO(s.descriptor,i))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);n.add(i.harness)}for(let i of t){let s=Er.get(i.harness);Er.set(i.harness,{descriptor:i,registrations:(s?.registrations??0)+1})}let o=!0;return()=>{if(o){o=!1;for(let i of t){let s=Er.get(i.harness);!s||s.registrations<=1?Er.delete(i.harness):s.registrations-=1}}}}function IO(e){let t=it(e.descriptor),r=e.harness.trim().toLowerCase();if(e.contract_version!==1)throw new Error(`Unsupported provenance adapter contract for "${r}": ${e.contract_version}`);if(t.harness!==r)throw new Error(`Provenance adapter harness "${r}" does not match descriptor "${t.harness}".`);let n=H(e.adapter_version)?.slice(0,64);if(!n)throw new Error(`Provenance adapter "${r}" requires a version.`);if(!Number.isSafeInteger(e.priority))throw new Error(`Provenance adapter "${r}" requires an integer priority.`);if(e.probe_policy.network_access!==!1||e.probe_policy.subprocess_access!==!1||e.probe_policy.max_bytes>tc||e.probe_policy.max_lines>4096)throw new Error(`Provenance adapter "${r}" exceeds the bounded local probe policy.`);return Object.freeze({...e,adapter_version:n,harness:r,descriptor:t,supported_dimensions:Object.freeze(ot(e.supported_dimensions).map(o=>o.toLowerCase()).sort()),native_sources:Object.freeze([...new Set(e.native_sources)]),probe_policy:Object.freeze({...e.probe_policy}),normalization:Object.freeze({...e.normalization}),...e.waivers?{waivers:Object.freeze(Object.fromEntries(Object.entries(e.waivers).slice(0,32).map(([o,i])=>[o.slice(0,64),i.slice(0,256)])))}:{}})}function E$(){let e=new Map(Qm.map(t=>[t.harness,t]));for(let{adapter:t}of Nt.values())e.set(t.harness,t);return Object.freeze([...e.values()].sort((t,r)=>t.harness.localeCompare(r.harness)))}function k$(e){let t=e.map(IO),r=new Map(Qm.map(i=>[i.harness,i])),n=new Set;for(let i of t){if(n.has(i.harness))throw new Error(`Provenance adapter collision for "${i.harness}".`);let s=r.get(i.harness);if(s&&i.priority<=s.priority)throw new Error(`Provenance adapter override for "${i.harness}" requires priority greater than ${s.priority}.`);let a=Nt.get(i.harness);if(a&&JSON.stringify(a.adapter)!==JSON.stringify(i))throw new Error(`Provenance adapter collision for "${i.harness}".`);n.add(i.harness)}for(let i of t){let s=Nt.get(i.harness);Nt.set(i.harness,{adapter:i,registrations:(s?.registrations??0)+1})}let o=!0;return()=>{if(o){o=!1;for(let i of t){let s=Nt.get(i.harness);!s||s.registrations<=1?Nt.delete(i.harness):s.registrations-=1}}}}function S$(e,t){let r=t.trim().slice(0,256),n=r.toLowerCase();if(e==="model"){let o=/^(gpt-\d+(?:\.\d+)?)/u.exec(n)?.[1];o&&(n=o)}else n=n.replaceAll(/[_\s-]+/gu,""),n={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max",ultra:"ultra"}[n]??n;return{raw:r,normalized:n,vocabulary:"v1"}}function O$(e,t){return Jm.run(e,t)}function A$(e,t,r={}){let n=e.map(it);return ic(n),si.run({descriptors:n,probesEnabled:r.probesEnabled!==!1},t)}function cc(e){let t=ac(e),r=t.env??{},n=ic(t.descriptors),o=[...(t.argv??[]).slice(0,3),...t.process_labels??[]].slice(0,64).map(_=>_.slice(0,512)),i=t.client_info?.name.trim().toLowerCase()??"",s=n.find(_=>vO(_,r,o,i)),a=qa(t,r),c=[sc(r,s?.session_environment_keys),H(t.client_info?.session)?.slice(0,256)].find(_=>_!==void 0),d=OO(s?.harness,c),l=Wm({cwd:t.cwd??process.cwd(),env:r,key:d}),u=AO(t,r,s,a,l),f=u.model,m=[["harness",s?.harness],["model",f?.value],["model_source",f?.source],["session",c],["instance",d],["provenance",Object.keys(u).length>0?u:void 0],["episode",a.episode]];return Object.fromEntries(m.filter(_=>_[1]!==void 0))}function TO(e){return e==="unavailable"?{status:"unavailable",reason:"harness_unavailable"}:e==="missing"?{status:"unavailable",reason:"resolver_input_missing"}:{status:"failed",reason:"resolver_failed"}}function CO(e,t,r,n,o,i,s){let a=r?.provenance_resolvers[e];if(t.provenance?.[e])return{status:"resolved",...a?{resolver:a}:{},rule_version:"v1"};if(s)return{status:"unavailable",reason:"invalid_value",rule_version:"v1"};if(a){if(!i)return{status:"unavailable",reason:"probes_disabled",resolver:a,rule_version:"v1"};let c=wO(a,r,n,o);return{...TO(c),resolver:a,rule_version:"v1"}}return{status:r?.provenance_unavailable_dimensions.includes(e)?"unavailable":"not_configured",reason:r?.provenance_unavailable_dimensions.includes(e)?"harness_unavailable":"resolver_not_configured",rule_version:"v1"}}function op(e){let t=ac(e),r=cc(t),n=ic(t.descriptors).find(d=>d.harness===r.harness),o=t.env??{},i=t.probes_enabled!==!1&&si.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(H(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=qa(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,sc(o,n?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,tp(t.argv??[],"role")].some(d=>{let l=H(d)?.slice(0,256);return l!==void 0&&xt("role",l)===void 0}),c=Object.fromEntries(nc.map(d=>[d,CO(d,r,n,t,o,i,d==="role"&&a)]));return{...r,provenance_outcomes:c}}function I$(){return process.env.PM_AUTHOR}function T$(e){e===void 0?delete process.env.PM_AUTHOR:process.env.PM_AUTHOR=e}function C$(e){return cc(e).harness}function RO(e,t,r){let n=ac(r),o=cc(n);if(e!==void 0){let s=H(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(n.env?.PM_AUTHOR!==void 0){let s=H(n.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=H(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function ip(e){let t=ii.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function sp(e){let t=ii.getStore();return t?.author!==e?e.startsWith("harness:")?{harness:e.slice(8)}:{}:{...t.harness?{harness:t.harness}:{},...t.model?{model:t.model}:{},...t.model_source?{model_source:t.model_source}:{},...t.session?{session:t.session}:{},...t.instance?{instance:t.instance}:{},...t.provenance?{provenance:t.provenance}:{},...t.episode?{episode:t.episode}:{}}}function R$(e){let t=ii.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function ap(e,t){let r=RO(e,t);return ii.enterWith(r),r.author}(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]="cfedb84f-0525-5e02-af0a-d0e5691b5e0a")}catch{}})();async function xO(e,t){let r=await ge(e);if(r===null)return{raw:r,entries:[]};if(await rr({path:e,scope:"project"}),r.trim()==="")return{raw:r,entries:[]};let n=Zo(r);if(n)throw new g(`History for ${t} contains merge conflict markers at line ${n.line} (${n.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,h.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${t}`,`pm restore ${t} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});let o=[];for(let[i,s]of r.split(/\r?\n/).entries()){let a=s.trim();if(a)try{o.push(JSON.parse(a))}catch{throw new g(`History for ${t} contains invalid JSON at line ${i+1}. Repair or restore the history stream and retry.`,h.GENERIC_FAILURE,{code:"history_json_invalid",nextSteps:[`Run pm history-repair ${t} --salvage-tail --dry-run to check whether only an invalid suffix is damaged.`]})}}return{raw:r,entries:o}}async function Fe(e,t){return(await xO(e,t)).entries}(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]="3c2c29c0-0034-54d4-9dbd-2e9af047784e")}catch{}})();var L$=1,NO=["docs_add","files_add","history:author-acknowledge","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","normalize","release","test_run_track","tests_add","tests_remove","tests_update","update_audit","update_ownership_bypass"],DO=["append","cancel","claim","close","comment_add","create","learning_add","note_add","reopen"],PO=new Set(NO),MO=new Set(DO),$O=new Set(["actual_result","affected_version","assignee","blocked_by","blocked_reason","close_reason","confidence","customer_impact","definition_of_ready","dependencies","docs","environment","expected_result","files","fixed_version","goal","impact","learnings","notes","objective","order","outcome","parent","release","reminders","reporter","repro_steps","resolution","reviewer","severity","sprint","tests","test_runs","unblock_note","updated_at","value","why_now"]);function jO(e){let t=e.path.split("/").filter(Boolean);return t[0]==="metadata"||t[0]==="front_matter"?t[1]:t[0]==="body"?"body":void 0}function kr(e){return e.event_class==="substantive"||e.event_class==="maintenance"?e.event_class:PO.has(e.op)?"maintenance":MO.has(e.op)||e.op!=="update"?"substantive":Array.isArray(e.patch)&&e.patch.length>0&&e.patch.every(t=>{let r=jO(t);return r!==void 0&&$O.has(r)})?"maintenance":"substantive"}import $p from"fast-json-patch";import Np from"node:fs/promises";import lA from"node:path";import j from"node:fs/promises";import V from"node:path";import{randomUUID as mc}from"node:crypto";import{createRequire as LO}from"node:module";import{setImmediate as lp}from"node:timers/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]="812b558d-59f3-58d6-b04e-6a4f8689e866")}catch{}})();function cp(e){let t=process.emitWarning;process.emitWarning=(r,...n)=>{r==="SQLite is an experimental feature and might change at any time"&&n[0]==="ExperimentalWarning"||Reflect.apply(t,process,[r,...n])};try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}finally{process.emitWarning=t}}function dp(e,t){let r=Number.parseInt(e,10);return Number.isFinite(r)&&r>=22?cp(t):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]="f0373f8f-7396-57df-9c8d-9a3315168b5a")}catch{}})();var FO="history-event-index.sqlite",pc="6",zO=8,hp="history-event-index",UO="history-event-index:append:",HO=5e3,_c=300,gp=3e4,qO="history-event-index-invalidation",VO="history-event-index-invalidations",BO=_c*2*1e3,st=Symbol("history-index-changed"),Pt=new Map;function $t(e){return V.join(e,"runtime",FO)}function bp(e){return V.join(e,"runtime","history-event-index-repair-deferred")}async function wp(e){try{let t=Number(await j.readFile(bp(e),"utf8")),r=Date.now()-t;return r>=0&&r<HO}catch{return!1}}async function up(e){try{await j.writeFile(bp(e),`${Date.now()}
47
- `)}catch{}}function In(e){return V.join(e,"runtime",VO)}async function di(e){let t=await j.readdir(In(e)).catch(r=>{if(ue(r))return[];throw r});return{pending:t.filter(r=>r.endsWith(".pending")).sort(),committed:t.filter(r=>r.endsWith(".committed")).sort()}}async function fp(e){let t=await di(e);return{pending:(await Promise.all(t.pending.map(async r=>{let n=/^(\d+)-(unknown|\d+)-(\d+)-.+\.pending$/u.exec(r);if(n!==null){let o=n[2];if(await yn({pid:Number(n[1]),...o==="unknown"?{}:{process_start_identity:o}},Math.max(0,Date.now()-Number(n[3])),BO))return r}return await j.rm(V.join(In(e),r),{force:!0}),null}))).filter(r=>r!==null),committed:t.committed}}async function uc(e,t,r=gp){let n=await ce(e,qO,_c,`history-event-index-invalidation:${process.pid}`,!1,!1,r,r===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await n()}}async function WO(e){let t=In(e);await j.mkdir(t,{recursive:!0});let r=mc(),n=await _n(),o=V.join(t,`${n.pid}-${n.process_start_identity??"unknown"}-${Date.now()}-${r}.pending`);return await j.writeFile(o,`pending
48
- `,{flag:"wx"}),{pendingPath:o,committedPath:V.join(t,`${r}.committed`)}}function GO(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}async function li(e){try{await j.rm($t(e),{force:!0})}catch{}}async function dc(e,t){let r=In(e);await j.mkdir(r,{recursive:!0}),await j.writeFile(V.join(r,`${mc()}${t?".contended":""}.committed`),`committed
49
- `,{flag:"wx"}),t||await li(e)}function ui(e){return e.committed.some(t=>t.endsWith(".contended.committed"))}function fc(e,t){let r;try{return r=new t($t(e)),r.exec("PRAGMA busy_timeout = 0"),r.exec("BEGIN EXCLUSIVE"),!1}catch(n){return Mt(n)}finally{r?.close()}}async function mp(e,t){return t.pending.length>0||await Ef(e,hp,UO)}async function vp(e,t,r=gp,n="rebuild"){let o=await ce(e,hp,_c,`history-event-index:${n}:${process.pid}`,!1,!1,r,r===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await o()}}async function Ep(e){let t=V.join(e,"history"),r=await j.readdir(t,{withFileTypes:!0}).catch(s=>{if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")return[];throw s}),n=Pt.get(e)??{streams:new Map,ordered_events:[]},o=new Set,i=!Pt.has(e);for(let s of r.filter(a=>a.isFile()&&a.name.endsWith(".jsonl")).sort((a,c)=>a.name.localeCompare(c.name))){let a=s.name.slice(0,-6);o.add(a);let c=V.join(t,s.name),d=await j.stat(c,{bigint:!0}),l=[d.dev,d.ino,d.size,d.mtimeNs,d.ctimeNs].join(":");if(n.streams.get(a)?.signature===l)continue;let u=await kp(c,a);n.streams.set(a,{signature:l,byte_size:Number(d.size),events:u.map((f,m)=>({stream_id:a,stream_offset:m,entry:f}))}),i=!0}for(let s of n.streams.keys())o.has(s)||(n.streams.delete(s),i=!0);if(i&&(n.ordered_events=[...n.streams.values()].flatMap(s=>s.events).sort(yc)),Pt.delete(e),Pt.set(e,n),Pt.size>zO){let s=Pt.keys().next().value;Pt.delete(s)}return{events:n.ordered_events,stream_byte_sizes:new Map([...n.streams].map(([s,a])=>[s,a.byte_size]))}}async function kp(e,t){let r=await Fe(e,t);for(let[n,o]of r.entries())if(typeof o.ts!="string"||!lr(o.ts.trim()))throw new g(`History for ${t} contains an invalid or sub-millisecond timestamp at line ${n+1}. Repair or restore the history stream and retry.`,h.GENERIC_FAILURE,{code:"history_timestamp_invalid"});return r.map(n=>({...n,ts:new Date(n.ts.trim()).toISOString()}))}async function KO(e){return(await Ep(e)).events}var lc;function mi(){return lc!==void 0||(lc=dp(process.versions.node,LO(import.meta.url))),lc}function YO(e){e.exec(`
50
- PRAGMA journal_mode = OFF;
51
- PRAGMA synchronous = OFF;
52
- CREATE TABLE metadata (
53
- key TEXT PRIMARY KEY,
54
- value TEXT NOT NULL
55
- ) STRICT;
56
- CREATE TABLE events (
57
- stream_id TEXT NOT NULL,
58
- stream_offset INTEGER NOT NULL,
59
- ts TEXT NOT NULL,
60
- author TEXT NOT NULL,
61
- agent_harness TEXT,
62
- agent_instance TEXT,
63
- op TEXT NOT NULL,
64
- event_class TEXT NOT NULL CHECK(event_class IN ('substantive', 'maintenance')),
65
- entry_json TEXT NOT NULL,
66
- PRIMARY KEY(stream_id, stream_offset)
67
- ) STRICT;
68
- CREATE TABLE streams (
69
- stream_id TEXT PRIMARY KEY,
70
- byte_size INTEGER NOT NULL CHECK(byte_size >= 0)
71
- ) STRICT;
72
- CREATE INDEX events_order
73
- ON events(ts, stream_id, stream_offset);
74
- CREATE INDEX events_op_order
75
- ON events(op, ts, stream_id, stream_offset);
76
- CREATE INDEX events_class_stream_order
77
- ON events(event_class, stream_id, ts, stream_offset);
78
- CREATE INDEX events_author_order
79
- ON events(author, ts, stream_id, stream_offset);
80
- CREATE INDEX events_harness_order
81
- ON events(agent_harness, ts, stream_id, stream_offset);
82
- CREATE INDEX events_instance_order
83
- ON events(agent_instance, ts, stream_id, stream_offset);
84
- `),e.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(pc)}function Sp(e,t){let r={...t.entry,ts:new Date(t.entry.ts.trim()).toISOString()};e.prepare(`INSERT INTO events(
85
- stream_id, stream_offset, ts, author, agent_harness,
86
- agent_instance, op, event_class, entry_json
87
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.stream_id,t.stream_offset,r.ts,r.author,r.agent_harness??null,r.agent_instance??null,r.op,kr(r),JSON.stringify(r))}function Op(e){let t=JSON.parse(String(e.entry_json));return typeof t.ts!="string"||!lr(t.ts.trim())?null:{stream_id:String(e.stream_id),stream_offset:Number(e.stream_offset),entry:{...t,ts:new Date(t.ts.trim()).toISOString()}}}function Ap(e,t,r){e.prepare(`INSERT INTO streams(stream_id, byte_size) VALUES (?, ?)
88
- ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size`).run(t,r)}async function XO(e,t={}){let r=mi();return r?vp(e,async()=>{let n;try{n=await uc(e,()=>fp(e),t.lockWaitMs)}catch(a){if(a instanceof g&&a.code==="lock_conflict")return!1;throw a}if(n.pending.length>0||ui(n)&&fc(e,r))return!1;let o=$t(e);await j.mkdir(V.dirname(o),{recursive:!0});let i=`${o}.${mc()}.tmp`,s;try{s=new r(i),YO(s),s.exec("BEGIN IMMEDIATE");let a=await Ep(e);await JO(s,a),s.exec("COMMIT"),s.close(),s=void 0;let c=await uc(e,async()=>{let d=await fp(e);return d.pending.length>0||!GO(n.committed,d.committed)||ui(d)&&fc(e,r)?!1:(await j.rm(o,{force:!0}),await j.rename(i,o),!0)},t.lockWaitMs);return c&&await Promise.all(n.committed.map(d=>j.rm(V.join(In(e),d),{force:!0}))),c||(await up(e),await j.rm(i,{force:!0})),c}catch(a){throw await up(e),s?.close(),await j.rm(i,{force:!0}),a}},t.lockWaitMs):!1}async function JO(e,t){let r=0;for(let n of t.events)Sp(e,n),++r%500===0&&await lp();for(let[n,o]of t.stream_byte_sizes)Ap(e,n,o),++r%500===0&&await lp()}function ai(e,t){return!t||t.length===0||t.includes(e)}function yc(e,t){return e.entry.ts.localeCompare(t.entry.ts)||e.stream_id.localeCompare(t.stream_id)||e.stream_offset-t.stream_offset}function fi(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():e}function ZO(e,t){if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){if(yc(e,{stream_id:t.after_stream_id,stream_offset:t.after_stream_offset,entry:{...e.entry,ts:fi(t.after_ts)}})<=0)return!1}else if(t.since_ts!==void 0&&e.entry.ts<fi(t.since_ts))return!1;return!0}function QO(e,t){return!t.harnesses||t.harnesses.length===0||t.harnesses.includes(e.entry.agent_harness??"")?!0:e.entry.agent_harness===void 0&&(t.harness_alias_authors??[]).includes(e.entry.author)}function eA(e,t){return!ZO(e,t)||!ai(e.entry.op,t.ops)||!ai(e.entry.author,t.authors)||!ai(e.entry.agent_instance??"",t.agent_instances)||!ai(e.stream_id,t.stream_ids)||!QO(e,t)?!1:(t.provenance??[]).every(r=>{let n=e.entry.agent_provenance?.[r.dimension]?.value;return n!==void 0&&r.values.includes(n)})}async function ej(e,t){let r=Math.max(0,Math.floor(t.limit)),n=(await KO(e)).filter(o=>eA(o,t)).slice(0,r+1);return{events:n.slice(0,t.limit),has_more:n.length>t.limit}}async function tA(e,t){let r=e.prepare("SELECT byte_size FROM streams WHERE stream_id = ?").get(V.basename(t,".jsonl")),n=0;try{n=(await j.stat(t)).size}catch(o){if(!ue(o))throw o}return Number(r?.byte_size??0)===n}async function Ip(e,t,r){let n=V.dirname(V.dirname(e)),o=mi(),i=!1,s=async()=>{await r(),i=!0};if(!o){await pp(n,s);return}try{await vp(n,async()=>{let a=$t(n);try{await j.access(a)}catch{await s();return}let c;try{if(c=new o(a),c.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==pc)throw new TypeError("Unsupported history event index version");if(!await tA(c,e))throw new TypeError("Stale history event index append base")}catch(l){if(c?.close(),Mt(l))throw l;await dc(n,!0),await s();return}try{c.exec("PRAGMA busy_timeout = 0"),c.exec("BEGIN IMMEDIATE")}catch(l){if(c.close(),Mt(l)||!(l instanceof Error)||l.code!=="ERR_SQLITE_ERROR")throw l;await dc(n,!1),await s();return}let d=!1;try{await s(),d=!0;let l=V.basename(e,".jsonl"),u=c.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(l);Sp(c,{stream_id:l,stream_offset:Number(u.value),entry:t}),Ap(c,l,(await j.stat(e)).size),c.exec("COMMIT"),c.close()}catch(l){if(c?.close(),!d)throw l;await dc(n,Mt(l))}},0,"append")}catch(a){if(i){await li(n);return}if(!nA(a))throw a;await pp(n,s,Mt(a))}}async function pp(e,t,r=!1){let n=!1,o;try{await uc(e,async()=>{let i=r||ui(await di(e)),s=await WO(e);o=s.pendingPath;try{await t(),n=!0}catch(a){throw await j.rm(s.pendingPath,{force:!0}),a}await j.rename(s.pendingPath,i?s.committedPath.replace(/\.committed$/u,".contended.committed"):s.committedPath),i||await li(e)})}catch(i){if(n){await li(e);try{await j.rm(o,{force:!0})}catch{}return}throw i}}async function hc(e){await j.rm($t(V.dirname(V.dirname(e))),{force:!0})}function ci(e,t,r,n){!n||n.length===0||(e.push(`${r} IN (${n.map(()=>"?").join(", ")})`),t.push(...n))}function rA(e,t,r,n){if(!r||r.length===0)return;let o=r.map(()=>"?").join(", "),i=n??[];if(i.length>0){e.push(`(agent_harness IN (${o}) OR (agent_harness IS NULL AND author IN (${i.map(()=>"?").join(", ")})))`),t.push(...r,...i);return}e.push(`agent_harness IN (${o})`),t.push(...r)}async function Tp(e,t,r,n){let o;try{let i=await di(e);if(await mp(e,i))return st;let s=await _p(e);if(i.committed.length>0)return ui(i)&&fc(e,t)?st:null;if(o=new t($t(e),{readOnly:!0}),o.exec("BEGIN"),o.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==pc)return null;let a=n(o);if(a===null)return null;let c=oA(o,r),d=o;o=void 0,d.close();let l=await aA([...c.keys()],e,r),u=await sA(c,e,l),f=await di(e);return f.committed.length>0||await mp(e,f)||s!==await _p(e)?st:u?a:null}catch(i){return Mt(i)?st:null}finally{o?.close()}}function Mt(e){return typeof e=="object"&&e!==null&&"errcode"in e&&[5,6].includes(e.errcode)}function nA(e){return Mt(e)||e instanceof g&&e.code==="lock_conflict"}function oA(e,t){let r=new Map,n=t&&t.length>0?[...new Set(t)]:void 0;if(n===void 0)for(let o of e.prepare("SELECT stream_id, byte_size FROM streams").all())r.set(String(o.stream_id),Number(o.byte_size));else for(let o=0;o<n.length;o+=500){let i=n.slice(o,o+500);for(let s of e.prepare(`SELECT stream_id, byte_size FROM streams WHERE stream_id IN (${i.map(()=>"?").join(", ")})`).all(...i))r.set(String(s.stream_id),Number(s.byte_size))}return r}async function _p(e){let t=await j.stat($t(e),{bigint:!0});return[t.dev,t.ino,t.size,t.mtimeNs,t.ctimeNs].join(":")}async function tj(e,t){let r=mi();if(!r)return{result:null,repair_needed:!1};let n=[],o=[];if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){n.push("(ts > ? OR (ts = ? AND stream_id > ?) OR (ts = ? AND stream_id = ? AND stream_offset > ?))");let a=fi(t.after_ts);o.push(a,a,t.after_stream_id,a,t.after_stream_id,t.after_stream_offset)}else t.since_ts!==void 0&&(n.push("ts >= ?"),o.push(fi(t.since_ts)));ci(n,o,"op",t.ops),ci(n,o,"author",t.authors),rA(n,o,t.harnesses,t.harness_alias_authors),ci(n,o,"agent_instance",t.agent_instances);for(let a of t.provenance??[])n.push(`json_extract(entry_json, '$.agent_provenance.${a.dimension}.value') IN (${a.values.map(()=>"?").join(", ")})`),o.push(...a.values);ci(n,o,"stream_id",t.stream_ids);let i=n.length===0?"":` WHERE ${n.join(" AND ")}`,s=await Tp(e,r,t.stream_ids,a=>{let c=a.prepare(`SELECT stream_id, stream_offset, entry_json
89
- FROM events${i}
90
- ORDER BY ts, stream_id, stream_offset
91
- LIMIT ?`).all(...o,Math.max(0,Math.floor(t.limit))+1),d=c.slice(0,t.limit).map(Op);return d.includes(null)?null:{events:d,has_more:c.length>t.limit}});return{result:s===st?null:s,repair_needed:s===null&&!await wp(e)}}function Cp(e,t){let r=Object.create(null);for(let n of e){if(!t.has(n.stream_id)||kr(n.entry)!=="substantive")continue;let o=r[n.stream_id];(o===void 0||yc(o,n)<0)&&(r[n.stream_id]=n)}return r}async function iA(e,t){if(V.basename(t)!==t)return null;try{return(await j.stat(V.join(e,"history",`${t}.jsonl`))).size}catch(r){if(ue(r))return 0;throw r}}async function sA(e,t,r){for(let n=0;n<r.length;n+=500){let o=r.slice(n,n+500),i=await Promise.all(o.map(s=>iA(t,s)));for(let[s,a]of i.entries()){if(a===null)return!1;let c=o[s],d=e.get(c);if(!(a===0&&d===void 0)&&a!==d)return!1}}return!0}async function aA(e,t,r){if(r&&r.length>0)return[...new Set(r.filter(o=>o.trim().length>0))];let n=await j.readdir(V.join(t,"history"),{withFileTypes:!0}).then(o=>o.filter(i=>i.isFile()&&i.name.endsWith(".jsonl")).map(i=>i.name.slice(0,-6))).catch(o=>{if(ue(o))return[];throw o});return[...new Set([...e,...n])]}async function yp(e,t,r,n){return e?Tp(t,e,r,o=>{let i=[];for(let s=0;s<r.length;s+=500){let a=r.slice(s,s+500),c=o.prepare(`SELECT stream_id, stream_offset, entry_json
92
- FROM (
93
- SELECT stream_id, stream_offset, entry_json,
94
- ROW_NUMBER() OVER (
95
- PARTITION BY stream_id
96
- ORDER BY ts DESC, stream_offset DESC
97
- ) AS recency_rank
98
- FROM events
99
- WHERE event_class = 'substantive'
100
- AND stream_id IN (${a.map(()=>"?").join(", ")})
101
- )
102
- WHERE recency_rank = 1`).all(...a).map(Op);if(c.includes(null))return null;i.push(...c)}return Cp(i,n)}):null}async function rj(e,t){let r=[...new Set(t.filter(a=>a.trim().length>0&&V.basename(a)===a))];if(r.length===0)return{};let n=new Set(r),o=mi(),i=await yp(o,e,r,n);if(i!==null&&i!==st)return i;if(o&&i!==st&&!await wp(e))try{if(await XO(e,{lockWaitMs:0})){let a=await yp(o,e,r,n);if(a!==null&&a!==st)return a}}catch{}let s=[];return await Promise.all(r.map(async a=>{let c=V.join(e,"history",`${a}.jsonl`);(await kp(c,a).catch(d=>{if(d instanceof g&&d.code==="history_timestamp_invalid")return[];throw d})).forEach((d,l)=>{s.push({stream_id:a,stream_offset:l,entry:d})})})),Cp(s,n)}import gc from"node:fs/promises";import Sr 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]="687cbe24-6d5c-5322-962d-455048eb84b5")}catch{}})();var cA=Sr.join("runtime","history-drift-cache.json"),Rp={EINVAL:"invalid_cache_path",EISDIR:"cache_path_is_directory",ENOENT:"invalid_cache_path",ENOTDIR:"invalid_cache_path",ERR_FS_EISDIR:"cache_path_is_directory"};function xp(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function dA(e){let t=Sr.join(e,cA),r=!1,n="invalid_cache_path";try{r=(await gc.stat(await gc.realpath(e))).isDirectory()}catch(o){let i=xp(o);n=i===void 0?"unknown":Rp[i]??"filesystem_error"}if(!r){bn(`[pm] warning: history_drift_cache_invalidation_failed:${n}
103
- `);return}try{await gc.rm(t,{force:!0})}catch(o){let i=xp(o);if(ue(o))return;let s=i===void 0?"unknown":Rp[i]??"filesystem_error";bn(`[pm] warning: history_drift_cache_invalidation_failed:${s}
104
- `)}}async function pi(e){let t=Sr.dirname(Sr.resolve(e));Sr.basename(t)==="history"&&await dA(Sr.dirname(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]="4a3c3c82-0398-549c-8910-fdc69d971cb2")}catch{}})();var uA={front_matter:{},body:""},jt=3,Tn=[1,2,3],fA=1,mA=[1];function jp(e){return tt(R(e),e.hash_algorithm)}function Or(e){return ro(R(e))}function Aj(e){return ro(R(e))}function Ec(e){let t={...e,record_hash_version:fA},{record_hash:r,...n}=t;return{...t,record_hash:jp(n)}}function hi(e){try{Tt(e.hash_algorithm)}catch{return{ok:!1,error:"unsupported_history_hash_algorithm"}}if(e.record_hash_version===void 0&&e.record_hash===void 0)return{ok:!0,coverage:"item_state_only"};if(e.record_hash_version===void 0||e.record_hash===void 0)return{ok:!1,error:"incomplete_record_hash_envelope"};if(!mA.includes(e.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};let{record_hash:t,...r}=e;return jp(r)===e.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function pA(e,t){let r={before_hash:e.before_hash,after_hash:e.after_hash,patch_hash:Or(e.patch)};return e.hash_algorithm!==void 0&&(r.hash_algorithm=e.hash_algorithm),e.item_hash_version!==void 0&&(r.item_hash_version=e.item_hash_version),t.retainOriginalPatch&&(r.patch=structuredClone(e.patch)),t.retainPriorRecordHash!==!1&&e.record_hash_version!==void 0&&e.record_hash!==void 0&&(r.record_hash_version=e.record_hash_version,r.record_hash=e.record_hash,r.record=structuredClone(e)),r}function Lp(e,t,r={}){let n=hi(e);if(!n.ok)throw new TypeError(n.error);let o=Or(e.patch),i=r.retainPriorRecord===!0||e.before_hash!==t.before_hash||e.after_hash!==t.after_hash||e.item_hash_version!==t.item_hash_version||e.hash_algorithm!==t.hash_algorithm||o!==Or(t.patch),s=Ec({...t,...i?{reanchor_evidence:[...t.reanchor_evidence??[],pA(e,r)]}:{}}),a=kc(s);if(!a.ok)throw new TypeError(a.error);return s}function Fp(e){return!Array.isArray(e)||Object.keys(e).length!==e.length?!1:e.every(t=>!Lt(t)||typeof t.path!="string"?!1:t.op==="move"||t.op==="copy"?typeof t.from=="string":["add","replace","test"].includes(t.op)?Object.hasOwn(t,"value"):t.op==="remove")}function _A(e){return Lt(e)&&typeof e.ts=="string"&&typeof e.author=="string"&&typeof e.op=="string"&&typeof e.before_hash=="string"&&typeof e.after_hash=="string"&&Fp(e.patch)}function yA(e){let t=e.record_hash_version!==void 0,r=e.record_hash!==void 0;return t===r}function hA(e){return!Lt(e)||!yA(e)||typeof e.before_hash!="string"||typeof e.after_hash!="string"||typeof e.patch_hash!="string"||!/^[a-f0-9]{64}$/u.test(e.patch_hash)||e.patch!==void 0&&!Fp(e.patch)||e.record_hash_version!==void 0&&typeof e.record_hash_version!="number"||e.record_hash!==void 0&&(typeof e.record_hash!="string"||!/^(?:[a-f0-9]{64}|[a-f0-9]{128})$/u.test(e.record_hash))?!1:e.record===void 0||_A(e.record)}function gA(e){try{for(let t of e){if(!hA(t))return!1;Tt(t.hash_algorithm)}return!0}catch{return!1}}function bA(e){let t=e.record;return t!==void 0&&t.before_hash===e.before_hash&&t.after_hash===e.after_hash&&t.item_hash_version===e.item_hash_version&&t.hash_algorithm===e.hash_algorithm&&t.record_hash_version===e.record_hash_version&&t.record_hash===e.record_hash&&Or(t.patch)===e.patch_hash}function wA(e,t,r){if(t.patch&&Or(t.patch)!==t.patch_hash)return{kind:"patch_hash_mismatch"};if(t.record)return bA(t)?{kind:"record",entry:t.record}:{kind:"record_hash_mismatch"};let n=t.patch??e.patch;if(Or(n)!==t.patch_hash)return{kind:"digest_only"};let o={...e,before_hash:t.before_hash,after_hash:t.after_hash,patch:n,hash_algorithm:t.hash_algorithm,...t.item_hash_version===void 0?{}:{item_hash_version:t.item_hash_version},...t.record_hash_version===void 0?{}:{record_hash_version:t.record_hash_version},...t.record_hash===void 0?{}:{record_hash:t.record_hash},...r.length===0?{}:{reanchor_evidence:r}};return t.hash_algorithm===void 0&&delete o.hash_algorithm,r.length===0&&delete o.reanchor_evidence,t.item_hash_version===void 0&&delete o.item_hash_version,t.record_hash_version===void 0||t.record_hash===void 0?{kind:"legacy",entry:o}:{kind:"record",entry:o}}function kc(e){let t=e.reanchor_evidence;if(t===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(t)||!gA(t))return{ok:!1,error:"rewrite_evidence_invalid"};if(t.length===0)return{ok:!0,coverage:"none"};let r=e;for(let n=t.length-1;n>=0;n-=1){let o=t[n],i=wA(r,o,t.slice(0,n));if(i.kind==="patch_hash_mismatch")return{ok:!1,error:"rewrite_evidence_patch_hash_mismatch"};if(i.kind==="record_hash_mismatch")return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};if(i.kind==="digest_only")return{ok:!0,coverage:"digest_only"};if(i.kind==="legacy")return{ok:!0,coverage:"legacy_anchor_only"};if(!hi(i.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};r=i.entry}return{ok:!0,coverage:"complete"}}function _i(e,t){return(e??"").localeCompare(t??"")}function Dp(e,t){return(e??0)-(t??0)}function at(e,t,r){return JSON.stringify(e??r).localeCompare(JSON.stringify(t??r))}function vA(e,t){return[e.scope.localeCompare(t.scope),_i(e.path,t.path),_i(e.command,t.command),Dp(e.timeout_seconds,t.timeout_seconds),_i(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,at(e.env_clear,t.env_clear,[]),at(e.env_set,t.env_set,{}),at(e.assert_stdout_contains,t.assert_stdout_contains,[]),at(e.assert_stdout_regex,t.assert_stdout_regex,[]),at(e.assert_stderr_contains,t.assert_stderr_contains,[]),at(e.assert_stderr_regex,t.assert_stderr_regex,[]),Dp(e.assert_stdout_min_lines,t.assert_stdout_min_lines),at(e.assert_json_field_equals,t.assert_json_field_equals,{}),at(e.assert_json_field_gte,t.assert_json_field_gte,{}),_i(e.note,t.note)].find(r=>r!==0)??0}function EA(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function kA(e,t){let r=EA(t);if(r.length===0)return!0;let n=e;for(let o of r){let i=/^(0|[1-9]\d*)$/.test(o)?Number(o):-1,s=Array.isArray(n)?i>=0&&i<n.length?n[i]:void 0:Lt(n)&&Object.prototype.hasOwnProperty.call(n,o)?n[o]:void 0;if(s===void 0)return!1;n=s}return!0}function SA(e,t){let r=[],n=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!kA(n,o.path)?{...o,op:"add"}:o;r.push(i),n=$p.applyPatch(n,[i],!0,!0).newDocument}return r}function yi(e,t,r=!1){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let n=wr(e),o=t===1||t===2&&r?{...n.metadata,...n.metadata.dependencies===void 0?{}:{dependencies:n.metadata.dependencies.map(s=>({...s,id:s.id.toLowerCase()}))},...n.metadata.tests===void 0?{}:{tests:n.metadata.tests.map(({workspace_context_mode:s,provenance:a,provenance_invalid:c,...d})=>d)},...n.metadata.test_runs===void 0?{}:{test_runs:n.metadata.test_runs.map(({executions:s,...a})=>a)}}:n.metadata,i=t===1&&o.tests?{...o,tests:[...o.tests].sort(vA)}:o;return{front_matter:A(i,we),body:n.body}}function Pp(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let t=wr(e);return{metadata:A(t.metadata,we),body:t.body}}function Ij(e){return zp(e,jt)}function zp(e,t,r){if(!Tn.some(n=>n===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return tt(R(yi(e,t)),r)}function Up(e,t,r){let n=zp(e,t,r);return t===2?[n,tt(R(yi(e,t,!0)),r)]:[n]}function Tj(){return ro(R(uA))}function Cn(e){let t=am(e.op),r=yi(e.before,jt),n=yi(e.after,jt),o=Pp(e.before),i=Pp(e.after),s=$p.compare(o,i),a=SA(o,s),c=sp(e.author),d=c.harness?Object.fromEntries(Object.entries(op().provenance_outcomes).filter(([m,_])=>_.resolver!==void 0&&(_.status!=="resolved"||c.provenance?.[m]?.source==="probe"))):void 0,l=d===void 0||Object.keys(d).length===0?e.context:{...e.context,agent_provenance_outcomes:d},u=e.hashAlgorithm??cm,f={hash_algorithm:u,ts:e.nowIso,author:e.author,author_source:e.authorSource??ip(e.author),...c.harness?{agent_harness:c.harness}:{},...c.model?{agent_model:c.model}:{},...c.model_source?{agent_model_source:c.model_source}:{},...c.instance?{agent_instance:c.instance}:{},...c.provenance?{agent_provenance:c.provenance}:{},...c.episode?{agent_episode:c.episode}:{},op:t,patch:a,before_hash:tt(R(r),u),after_hash:tt(R(n),u),item_hash_version:jt,message:e.message===void 0?void 0:e.message,...l===void 0?{}:{context:l}};return Ec({...f,event_class:kr(f)})}function Lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bc(e){return new g(e,h.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function Hp(e){let t=e.ts.trim();if(t.length===0)return Ie();if(!lr(t))throw bc("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(t!==e.ts)throw bc("History timestamp must not contain surrounding whitespace");return e.ts}function Mp(e,t){let r=e.ts;if(typeof r=="string"&&r.trim().length>0){if(!lr(r))throw bc("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return e}return{...e,ts:t}}function wc(e,t){let r=Hp(t);if(typeof e=="string"){let n;try{n=JSON.parse(e)}catch{return e}return Lt(n)?JSON.stringify(Mp(n,r)):e}return Lt(e)?JSON.stringify(Mp(e,r)):JSON.stringify(e)}async function OA(e,t,r){if(r===!1)return!0;if(typeof r=="string"){let s=wc(r,t);return await vc(e,s),await pi(e),await hc(e),!0}if(typeof r!="object"||r===null)return!1;let n=r;if(n.skip===!0)return!0;let o=typeof n.history_path=="string"?n.history_path:e,i=wc(typeof n.line=="string"?n.line:n.entry??t,t);return await vc(o,i),await pi(o),await hc(o),!0}async function vc(e,t){let r;try{r=JSON.parse(t)}catch{r=null}if(!Lt(r)||r.op!=="create"){await Zc(e,t);return}await Np.mkdir(lA.dirname(e),{recursive:!0});try{await Np.writeFile(e,`${t}
105
- `,{encoding:"utf8",flag:"wx"})}catch(n){throw n.code!=="EEXIST"?n:new g("This item identity is reserved by an existing history stream.",h.CONFLICT,{code:"item_identity_reserved",required:"Choose a new item ID or restore the original item from its history.",nextSteps:["Run pm history <id> --full, then pm restore <id> <version> to recover the original item."]})}}async function Rn(e,t){let r=await nr("history_append",{history_path:e,entry:t});if(r.handled&&await OA(e,t,r.result))return;let n=t.ts.trim().length>0?t:{...t,ts:Hp(t)},o=Ec({...n,hash_algorithm:Tt(n.hash_algorithm),event_class:kr(n)});await Ip(e,o,async()=>{await vc(e,wc(o,o))}),await pi(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]="3bfeb8d2-52c2-587a-9611-c4d5817cb47e")}catch{}})();function qp(e){let t=[],r=e[0]?.op==="history_compact_baseline",n=r?1:void 0,o=!1;for(let[i,s]of e.entries())s.op==="delete"&&(o=!0),s.op==="create"&&(n!==void 0&&t.push({prior_genesis_index:n,repeated_create_index:i+1,sequence:o?"delete_then_create":r?"checkpoint_then_create":"multiple_creates"}),n??=i+1,o=!1);return t}import Oc 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]="0c0cb8c7-4d7d-53f8-8ec2-d6dc98fc6dc5")}catch{}})();var AA={metadata:{},body:""};function gi(){return structuredClone(AA)}function Fj(e,t=jt,r){return Sc(e,t,r)[0]}function Sc(e,t,r){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return Up(bi(e),t,r)}catch{}let n=tt(R({replay_fallback:!0,metadata:e.metadata,body:e.body}),r);return t===2?[n,n]:[n]}function Wp(e,t,r,n,o){let i=Tt(n.hash_algorithm),s=`${r}:${i}`,a=o?.before.get(s)??Sc(e,r,i),c=Sc(t,r,i);return o?.after.set(s,c),{beforeHashes:a,afterHashes:c,pairIndex:a.findIndex((d,l)=>d===n.before_hash&&c[l]===n.after_hash),beforeIndex:a.indexOf(n.before_hash),afterIndex:c.indexOf(n.after_hash)}}function bi(e){return{metadata:e.metadata,body:e.body}}function zj(e,t={}){return wr(bi(e),t)}function Uj(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=wr(e);return{metadata:A(t.metadata,we),body:t.body}}function Vp(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function IA(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function Gp(e){return Array.isArray(e)?e.filter(IA).map(t=>({...t,path:Vp(t.path),from:typeof t.from=="string"?Vp(t.from):void 0})):[]}function TA(e){return typeof e=="object"&&e!==null&&"metadata"in e&&"body"in e&&typeof e.body=="string"&&typeof e.metadata=="object"&&e.metadata!==null}function wi(e,t){try{let r=Gp(t),n=Oc.applyPatch(structuredClone(e),r,!0,!0).newDocument;return TA(n)?{ok:!0,document:{metadata:n.metadata,body:n.body}}:{ok:!1,error:new Error("history_replay_invalid_document_shape")}}catch(r){return{ok:!1,error:r}}}function CA(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&Tn.includes(t)))]}function Kp(e){return e!==void 0&&!Tn.includes(e)}function RA(e,t){return e!==void 0?[e]:t===void 0?[...Tn]:[t]}function Yp(e){let t=hi(e);if(!t.ok)return t.error;let r=kc(e);return r.ok?void 0:r.error}function xA(e,t){let r=Yp(e);if(r)return{ok:!1,error:r};let n=wi(t,e.patch);return n.ok?{ok:!0,document:n.document}:{ok:!1,error:"patch_apply_failed"}}function NA(e,t){let r=Yp(e);if(r)throw new TypeError(`${r}:entry_${t+1}`)}function DA(e,t,r,n,o){let i=[];for(let s of r){let a=Wp(e,t,s,n,o);if(i.push({version:s,match:a}),a.pairIndex>=0)break}return i}function Xp(e){let t=gi(),r=new Map,n,o,i=qp(e).map(s=>`verify_failed:duplicate_create:entry_${s.repeated_create_index}:prior_${s.prior_genesis_index}`);for(let s=0;s<e.length;s+=1){let a=e[s],c=a.item_hash_version,d=Kp(c);d&&i.push(`verify_failed:unsupported_item_hash_version:${String(c)}:entry_${s+1}`);let l=xA(a,t);if(!l.ok)return{ok:!1,errors:[...i,`verify_failed:${l.error}:entry_${s+1}`]};if(d){t=l.document,r=new Map,n=void 0,o=void 0;continue}let u=RA(c,o),f={before:r,after:new Map},m=DA(t,l.document,u,a,f),_=m.find(({match:w})=>w.pairIndex>=0);if(_===void 0){let w=m.some(({match:v})=>v.beforeIndex>=0);return{ok:!1,errors:[...i,`verify_failed:${w?"after":"before"}_hash_mismatch:entry_${s+1}`]}}let y=_.version;t=l.document,r=f.after,n=y,o=c??o}return i.length>0?{ok:!1,errors:i,...n===void 0?{}:{item_hash_version:n}}:{ok:!0,errors:[],...n===void 0?{}:{item_hash_version:n}}}function Ft(e){let t=Xp(e);return{ok:t.ok,errors:t.errors}}function Bp(e,t){try{return{ok:!0,document:Oc.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function PA(e,t){let r=structuredClone(e),n=0,o=0;for(let s of Gp(t)){let a=Bp(r,s);if(a.ok){r=a.document;continue}if(s.op==="replace"){let c=Bp(r,{...s,op:"add"});if(c.ok){r=c.document,n+=1;continue}}o+=1}let i=r;return{document:{metadata:typeof i.metadata=="object"&&i.metadata!==null?i.metadata:{},body:typeof i.body=="string"?i.body:e.body},convertedReplaceToAdd:n,skippedOps:o}}function MA(e){let t=CA(e);if(t.length===1)return t[0];let r=Xp(e);return r.ok&&r.item_hash_version!==void 0?r.item_hash_version:t.length===0?1:jt}function $A(e,t,r=t.patch){let n=wi(e,r);if(n.ok)return{next:n.document,patch:r,repaired:R(r)!==R(t.patch),converted:0,skipped:0};let o=PA(e,r);return{next:o.document,patch:Oc.compare(e,o.document),repaired:!0,converted:o.convertedReplaceToAdd,skipped:o.skippedOps}}function jA(e,t,r){return $A(e,t,r.projectPatch?.(t,e))}function Hj(e,t=MA(e),r={}){let n=e.findIndex(m=>Kp(m.item_hash_version));if(n>=0)throw new TypeError(`unsupported_item_hash_version:${String(e[n]?.item_hash_version)}:entry_${n+1}`);let o=gi(),i=[],s=[],a=0,c=0,d=0,l=0,u,f=t!==1||e.some(m=>m.item_hash_version!==void 0);for(let m=0;m<e.length;m+=1){let _=e[m];NA(_,m);let y=jA(o,_,r),{next:w,patch:v,repaired:C,converted:K,skipped:Ee}=y;d+=K,l+=Ee,c+=Number(C);let ke=Wp(o,w,t,_);u===void 0||r.continuousHashSurface!==!0?u=[ke.pairIndex,ke.beforeIndex,ke.afterIndex,Math.min(u??0,ke.beforeHashes.length-1)].find(L_=>L_>=0):u=Math.min(u,ke.beforeHashes.length-1);let qc=ke.beforeHashes[u],Vc=ke.afterHashes[u],Di=qc!==_.before_hash||Vc!==_.after_hash;Di&&(a+=1);let qt={..._,patch:v,before_hash:qc,after_hash:Vc};f?qt.item_hash_version=t:delete qt.item_hash_version;let j_=qt.item_hash_version!==_.item_hash_version;(Di||C||j_)&&(qt=Lp(_,qt,{retainOriginalPatch:C})),i.push(qt),s.push({index:m+1,rehashed:Di,patch_repaired:C,converted_replace_to_add:K,skipped_ops:Ee}),o=w}return{entries:i,finalDocument:o,entriesRehashed:a,entriesPatchRepaired:c,convertedReplaceToAdd:d,skippedOps:l,details:s,itemHashVersion:t,explicitItemHashVersion:f}}function qj(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
106
- `)}
107
- `}import Jp from"node:fs/promises";import Ar 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]="af606b47-d071-5724-b1e7-de4e1e5d7385")}catch{}})();var ct="_workspace";function zt(e){return Ar.join(e,"history",`${ct}.jsonl`)}function Ac(e,t){return{metadata:{id:ct,title:"Workspace state",description:"Audited singleton workspace document state.",type:"Chore",status:"open",priority:2,tags:["workspace-history"],created_at:t,updated_at:t,documents:e},body:""}}function Ut(e,t=e.length){let r=gi();for(let n of e.slice(0,t))r=wi(r,n.patch).document;return bi(r)}function Ir(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function Tr(e){throw new g(`Workspace history verification failed: ${e.join(", ")}`,h.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...e],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function vi(e,t){let r=Ar.resolve(t),n=Ar.relative(e,r).replaceAll("\\","/");if(n.length===0||n===".."||n.startsWith("../")||Ar.isAbsolute(n))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:n,absolutePath:r}}async function rL(e){let t=await Fe(zt(e),ct),r=Ft(t);r.ok||Tr(r.errors);let n=Ir(t.length===0?xr:Ut(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(n).sort()){let d;try{let l=vi(e,Ar.resolve(e,c));if(d=await ge(l.absolutePath),d===null){s.push(c);continue}let u=JSON.parse(d);(R(u)===R(n[c])?o:i).push(c)}catch{a.push(c)}}return{ok:i.length===0&&s.length===0&&a.length===0,document_count:Object.keys(n).length,matching_documents:o,mismatched_documents:i,missing_documents:s,unreadable_documents:a}}async function Zp(e){let t=zt(e.pmRoot),r=await Fe(t,ct),n=Ft(r);n.ok||Tr(n.errors);let o=e.idempotencyKey===void 0?void 0:r.find(u=>u.op===`${e.op}:${e.idempotencyKey}`);if(o)return{entry:o,historyPath:t};let i=Ie(),s=r.length===0?xr:Ut(r),a=Ir(s),c=a[e.documentPath];if(c!==void 0&&R(c)!==R(e.before))throw new g(`Workspace history state for "${e.documentPath}" changed outside the audited mutation path.`,h.CONFLICT,{code:"workspace_history_state_conflict",reason:"out_of_band_workspace_state",required:"Reconcile the singleton document with its matching _workspace history state before retrying the mutation.",why:"Accepting the write would make the append-only audit stream describe a state that was not actually observed.",examples:["pm history _workspace --verify","pm validate --check-history-drift --fix-hints"],nextSteps:["Review the version-control change that altered the singleton and preserve the intended document plus its matching workspace history.","Rerun the original mutation only after the on-disk singleton agrees with the latest audited workspace state."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify"}});let d=Ac({...a,[e.documentPath]:e.after},r.length===0?i:s.metadata.created_at),l=Cn({nowIso:i,author:e.author,op:e.idempotencyKey===void 0?e.op:`${e.op}:${e.idempotencyKey}`,before:s,after:d,message:e.message});return await Rn(t,l),{entry:l,historyPath:t}}async function nL(e){let t=await ce(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await Zp(e)}finally{await t()}}async function oL(e){let t=await ce(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let r=zt(e.pmRoot),n=await Fe(r,ct),o=Ft(n);o.ok||Tr(o.errors);let i=n.length===0?xr:Ut(n),s=Cn({nowIso:Ie(),author:e.author,op:e.op,before:i,after:i,message:e.message,context:e.context});return await Rn(r,s),{entry:s,historyPath:r}}finally{await t()}}async function Qp(e,t){if(t===e.raw)return!1;let r=t===null?null:JSON.parse(t),n=JSON.parse(e.raw);await pt(e.filePath,e.raw);try{(t!==null||e.recordCreation!==!1)&&await Zp({pmRoot:e.pmRoot,documentPath:Ar.relative(e.pmRoot,e.filePath).replaceAll("\\","/"),before:r,after:n,op:e.op,idempotencyKey:e.idempotencyKey,author:e.author,lockTtlSeconds:e.lockTtlSeconds,lockWaitMs:e.lockWaitMs,message:e.message})}catch(o){throw t===null?await Jp.rm(e.filePath,{force:!0}):await pt(e.filePath,t),o}return!0}async function e_(e){let{documentPath:t}=vi(e.pmRoot,e.filePath),r=await ce(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=await ge(e.filePath);if(e.dryRun===!0||e.idempotencyKey!==void 0){let i=await Fe(zt(e.pmRoot),ct),s=Ft(i);s.ok||Tr(s.errors);let a=Ir(i.length===0?xr:Ut(i))[t];if(a!==void 0&&R(a)!==R(n===null?null:JSON.parse(n)))throw new g(`Workspace history state for "${t}" changed outside the audited mutation path.`,h.CONFLICT,{code:"workspace_history_state_conflict"});if(e.idempotencyKey!==void 0&&i.some(c=>c.op===`${e.op}:${e.idempotencyKey}`))return{changed:!1,result:void 0,replayed:!0}}let o=await e.mutate(n);return JSON.parse(o.raw),e.dryRun===!0?{changed:n!==o.raw,result:o.result}:{changed:await Qp({...e,raw:o.raw},n),result:o.result}}finally{await r()}}async function iL(e){let t=await ce(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await Qp(e,await ge(e.filePath))}finally{await t()}}async function sL(e){let t=e.authorizationDecision.trim();if(!t)throw new TypeError("Workspace history reconciliation requires an authorization decision");let r=await ce(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:n,absolutePath:o}=vi(e.pmRoot,e.filePath),i=zt(e.pmRoot),s=await Fe(i,ct),a=Ft(s);a.ok||Tr(a.errors);let c=Ut(s),d=Ir(c);if(!Object.hasOwn(d,n))throw new TypeError(`Workspace history does not govern document ${n}`);let l=await ge(o);if(l===null)throw new TypeError(`Workspace history document is missing: ${n}`);let u=JSON.parse(l);if(R(d[n])===R(u))return{changed:!1,historyPath:i};let f=Ie(),m=Cn({nowIso:f,author:e.author,op:e.op,before:c,after:Ac({...d,[n]:u},c.metadata.created_at),message:e.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:n,authorization_decision:t}});return await Rn(i,m),{changed:!0,entry:m,historyPath:i}}finally{await r()}}async function aL(e){let t=await ce(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:r,absolutePath:n}=vi(e.pmRoot,e.filePath),o=await Fe(zt(e.pmRoot),ct),i=Ft(o);if(i.ok||Tr(i.errors),!Number.isInteger(e.targetVersion)||e.targetVersion<1||e.targetVersion>o.length)throw new TypeError(`Invalid workspace history target version: ${String(e.targetVersion)}`);let s=Ir(Ut(o,e.targetVersion))[r];if(s===void 0)throw new TypeError(`Workspace history version ${e.targetVersion} does not contain ${r}`);let a=await ge(n),c=`${JSON.stringify(s,null,2)}
108
- `;if(a===c)return{document_path:r,restored_from_version:e.targetVersion,changed:!1};let d=Ut(o),l=Ie(),u=Cn({nowIso:l,author:e.author,op:e.op,before:d,after:Ac({...Ir(d),[r]:s},d.metadata.created_at),message:e.message,context:{reason:"workspace_state_restore",document_path:r,restored_from_version:e.targetVersion,replaced_out_of_band_state:!0}});await pt(n,c);try{await Rn(zt(e.pmRoot),u)}catch(f){throw a===null?await Jp.rm(n,{force:!0}):await pt(n,a),f}return{document_path:r,restored_from_version:e.targetVersion,changed:!0}}finally{await t()}}import{AsyncLocalStorage as nI}from"node:async_hooks";import{lstat as oI,realpath as l_}from"node:fs/promises";import u_ 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]="f4ae942c-f11f-5d24-95bf-a2abf3c226da")}catch{}})();var _e={ok:!1},b=e=>typeof e=="string"?{ok:!0,value:e}:_e,x=e=>typeof e=="boolean"?{ok:!0,value:e}:_e;function L(e={}){return t=>typeof t!="number"||!Number.isFinite(t)||e.int&&(!Number.isInteger(t)||!Number.isSafeInteger(t))||e.positive&&t<=0||typeof e.min=="number"&&t<e.min||typeof e.max=="number"&&t>e.max?_e:{ok:!0,value:t}}function N(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:_e}function k(e,t){return r=>{if(!Array.isArray(r)||t!==void 0&&r.length>t)return _e;let n=[];for(let o of r){let i=e(o);if(!i.ok)return _e;n.push(i.value)}return{ok:!0,value:n}}}function Tc(e,t){return r=>typeof r=="string"&&r.length>0&&r.length<=e&&r===r.trim()&&(t===void 0||t.test(r))?{ok:!0,value:r}:_e}function p(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function Ei(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return _e;let r={};for(let[n,o]of Object.entries(t)){let i=e(o);if(!i.ok)return _e;r[n]=i.value}return{ok:!0,value:r}}}function I(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return _e;let r=t,n={};for(let[o,i]of Object.entries(e)){let s=i(r[o]);if(!s.ok)return _e;s.value!==void 0&&(n[o]=s.value)}return{ok:!0,value:n}}}var LA=I({key:b,values:k(b),required:p(x),aliases:p(k(b)),description:p(b)}),FA=I({command:N("create","update"),option:b,required:p(x),visible:p(x),enabled:p(x)}),zA=I({name:b,description:p(b),default_status:p(b),execution_role:p(N("agent","human","gate")),folder:p(b),aliases:p(k(b)),required_create_fields:p(k(b)),required_create_repeatables:p(k(b)),options:p(k(LA)),command_option_policies:p(k(FA))}),UA=I({id:b,aliases:p(k(b)),roles:p(k(N(...Gn))),description:p(b),order:p(L())}),HA=I({key:b,metadata_key:p(b),front_matter_key:p(b),cli_flag:p(b),cli_aliases:p(k(b)),description:p(b),type:p(N(...Gt)),commands:p(k(N(...Kn))),repeatable:p(x),required:p(x),required_on_create:p(x),required_types:p(k(b)),allow_unset:p(x)}),qA=e=>{if(!Array.isArray(e)||e.length!==2)return _e;let[t,r]=e;return typeof t!="string"||typeof r!="string"?_e:{ok:!0,value:[t,r]}},VA=I({type:b,allowed_transitions:k(qA)}),BA=p(I({version:p(L({int:!0})),files:p(I({types:p(b),statuses:p(b),fields:p(b),workflows:p(b)})),statuses:p(k(UA)),fields:p(k(HA)),workflow:p(I({draft_status:p(b),open_status:p(b),in_progress_status:p(b),blocked_status:p(b),close_status:p(b),canceled_status:p(b)})),type_workflows:p(k(VA)),unknown_field_policy:p(N(...Yn))})),WA=p(I({preset:p(N(...id)),ownership_enforcement:p(N("none","warn","strict")),create_mode_default:p(N("progressive","strict")),close_validation_default:p(N("off","warn","strict")),require_close_reason:p(x),parent_reference:p(N("warn","strict_error")),metadata_profile:p(N("core","strict","custom")),force_required_for_stale_lock:p(x),create_default_type:p(b),workflow_enforcement:p(N("off","warn","strict")),duplicate_detection_mode:p(N("off","advisory","strict")),duplicate_detection_threshold:p(L({min:0,max:1})),duplicate_detection_limit:p(L({int:!0,min:0,max:20}))})),GA=I({name:b,disabled:p(x),require_trusted:p(x),require_provenance:p(x),sandbox_profile:p(N("none","restricted","strict")),allowed_capabilities:p(k(b)),blocked_capabilities:p(k(b)),allowed_surfaces:p(k(b)),blocked_surfaces:p(k(b)),allowed_commands:p(k(b)),blocked_commands:p(k(b)),allowed_actions:p(k(b)),blocked_actions:p(k(b)),allowed_services:p(k(b)),blocked_services:p(k(b))}),Ic=N("block","warn"),KA=e=>typeof e=="string"?Ic(e):I({global:p(Ic),project:p(Ic)})(e),YA=p(I({mode:p(N("off","warn","enforce")),trust_mode:p(N("off","warn","enforce")),pm_max_version_exceeded_mode:p(KA),require_provenance:p(x),trusted_extensions:p(k(b)),default_sandbox_profile:p(N("none","restricted","strict")),allowed_extensions:p(k(b)),blocked_extensions:p(k(b)),allowed_capabilities:p(k(b)),blocked_capabilities:p(k(b)),allowed_surfaces:p(k(b)),blocked_surfaces:p(k(b)),allowed_commands:p(k(b)),blocked_commands:p(k(b)),allowed_actions:p(k(b)),blocked_actions:p(k(b)),allowed_services:p(k(b)),blocked_services:p(k(b)),extension_overrides:p(k(GA))})),Ht=Tc(128),XA=I({harness:Tc(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:p(k(Ht,64)),model_environment_keys:p(k(Ht,64)),session_environment_keys:p(k(Ht,64)),provenance_environment_keys:p(Ei(k(Ht,64))),provenance_resolvers:p(Ei(N("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:p(k(Ht,64)),argv_markers:p(k(Ht,64)),client_names:p(k(Ht,64))}),JA=I({version:L({int:!0}),id_prefix:b,ids:p(I({token_length:p(L({int:!0,min:4,max:12}))})),author_default:b,agent_identity:p(I({probes_enabled:p(x),identity_vocabulary:p(I({version:L({int:!0,positive:!0}),aliases:Ei(Tc(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:k(XA)})),mutation_guard:p(I({require_attributed_author:p(x),secret_guard:p(N("off","advise","block")),stale_in_progress_hours:p(L({int:!0,positive:!0}))})),item_format:p(N("toon","json_markdown")),locks:I({ttl_seconds:L({int:!0}),wait_ms:p(L({int:!0,min:0}))}),checkpoints:p(I({retention_days:p(L({int:!0,positive:!0}))})),output:I({default_format:N("toon","json")}),ux:p(I({deprecation_hints:p(x)})),history:p(I({missing_stream:N("auto_create","strict_error"),compact_policy:p(I({enabled:p(x),max_entries:p(L({int:!0,positive:!0})),trigger:p(N("health_warn","auto"))}))})),validation:p(I({sprint_release_format:N("warn","strict_error"),parent_reference:p(N("warn","strict_error")),metadata_profile:p(N("core","strict","custom")),metadata_required_fields:p(k(b)),lifecycle_stale_blocker_reason_patterns:p(k(b)),lifecycle_closure_like_blocked_reason_patterns:p(k(b)),lifecycle_closure_like_resolution_patterns:p(k(b)),lifecycle_closure_like_actual_result_patterns:p(k(b)),estimate_defaults_by_type:p(Ei(L({int:!0,positive:!0})))})),governance:WA,workflow:p(I({definition_of_done:k(b)})),testing:p(I({record_results_to_items:x,allow_untrusted_linked_tests:p(x)})),telemetry:p(I({enabled:x,first_run_prompt_completed:p(x),capture_level:p(N("minimal","redacted","max")),endpoint:p(b),installation_id:p(b),retention_days:p(L({int:!0,positive:!0}))})),agent_guidance:p(I({prompt_completed:p(x),declined:p(x),declined_at:p(b),template_version:p(L({int:!0,positive:!0})),last_checked_files:p(k(b))})),item_types:p(I({definitions:k(zA)})),schema:BA,context:p(I({default_depth:p(N("brief","standard","deep")),activity_limit:p(L({int:!0,positive:!0})),stale_threshold_days:p(L({int:!0,positive:!0})),sections:p(I({hierarchy:p(x),activity:p(x),progress:p(x),recently_created:p(x),unparented:p(x),blockers:p(x),files:p(x),workload:p(x),staleness:p(x),tests:p(x)}))})),extensions:I({enabled:k(b),disabled:k(b),policy:YA}),search:I({score_threshold:L(),hybrid_semantic_weight:p(L()),max_results:L({int:!0}),embedding_model:b,embedding_corpus_max_characters:p(L()),embedding_batch_size:L({int:!0}),embedding_timeout_ms:p(L({int:!0})),scanner_max_batch_retries:L({int:!0}),provider:p(b),default_mode:p(N("auto","keyword","semantic","hybrid")),corpus_fields:p(k(b)),mutation_refresh_policy:p(N("cache_only","semantic_configured","semantic_auto")),query_expansion:p(I({enabled:p(x),provider:p(b)})),rerank:p(I({enabled:p(x),model:p(b),top_k:p(L({int:!0,positive:!0}))})),bm25:p(I({k1:p(L()),b:p(L())}))}),providers:I({openai:I({base_url:b,api_key:b,model:b}),ollama:I({base_url:b,model:b})}),vector_store:I({adapter:p(b),collection_name:p(b),qdrant:I({url:b,api_key:b}),lancedb:I({path:b})})});function Cc(e){let t=JA(e);return t.ok?{success:!0,data:t.value}:{success:!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]="a0ca9902-540c-50fe-a4e2-9c234c4a01f3")}catch{}})();function ki(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rc(e,t,r,n=[]){if(B(e,t)&&(n.length>0||ki(r)))return r;if(B(e,r)||B(t,r))return t;if((e===void 0||ki(e))&&ki(t)&&ki(r)){let o=e??{},i=new Set([...Object.keys(o),...Object.keys(t),...Object.keys(r)]);return Object.fromEntries([...i].flatMap(s=>{let a=Rc(Object.hasOwn(o,s)?o[s]:void 0,Object.hasOwn(t,s)?t[s]:void 0,Object.hasOwn(r,s)?r[s]:void 0,[...n,s]);return a===void 0?[]:[[s,a]]}))}throw new g(`Settings changed concurrently at ${n.join(".")||"<root>"}; read the latest settings and reapply the intended change.`,h.CONFLICT,{reason:"stale_settings_snapshot",required:"Read a fresh settings snapshot and reapply the intended change.",why:"Another writer changed the same setting after this snapshot was read.",examples:["pm config project export --json"],nextSteps:["Read the current settings, then retry the original config operation."]})}(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]="de43e8e6-d7ef-53cc-94b0-ccdf1c4f94a3")}catch{}})();var ZA={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},t_=120;function xc(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function n_(e){let t=new Map;for(let[r,n]of Object.entries(e))t.set(r.toLowerCase(),n);return t}var QA=n_(ZA),r_=new WeakMap;function eI(e){let t=r_.get(e);if(t)return t;let r=n_(e);return r_.set(e,r),r}function _L(e,t){let r=(e??"").trim().toLowerCase();if(r.length===0)return t_;if(t){let o=eI(t).get(r);if(xc(o))return Math.floor(o)}let n=QA.get(r);return xc(n)?Math.floor(n):t_}function Nc(e){let t={};if(e===null||typeof e!="object"||Array.isArray(e))return t;for(let[r,n]of Object.entries(e)){let o=r.trim();o.length===0||!xc(n)||(t[o]=Math.floor(n))}return t}import{stat as tI}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]="78c79deb-5cf0-54fe-b98c-a0d5b3671ab2")}catch{}})();var Si=new Map;function o_(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}async function rI(e){try{let t=await tI(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function dt(e){let t=o_(e),r=await Promise.all(t.map(n=>rI(n)));return r.sort((n,o)=>n.path.localeCompare(o.path)),r}function xn(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){let n=e[r],o=t[r];if(n.path!==o.path||n.mtime_ms!==o.mtime_ms||n.size!==o.size)return!1}return!0}function i_(e){return Si.get(e)}function Oi(e,t){let r=o_(t.tracked_paths),n=[...t.signatures].map(o=>({path:o.path,mtime_ms:o.mtime_ms,size:o.size})).sort((o,i)=>o.path.localeCompare(i.path));Si.set(e,{tracked_paths:r,signatures:n,value:t.value})}function lt(e){if(e){Si.delete(e);return}Si.clear()}(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]="0caecc9d-687a-5b36-b19c-2f2a9c7a1a8a")}catch{}})();var $c=new nI;async function $L(e,t,r=()=>!0){let n=new Set([u_.resolve(e)]);try{n.add(await l_(e))}catch{}return $c.run([...$c.getStore()??[],[n,r]],t)}function iI(e){let t=u_.resolve(e);return $c.getStore()?.some(([r,n])=>r.has(t)&&n())??!1}var sI="settings:write",f_=Symbol("pm.settings.persist_source"),aI=128,cI=new Set(["off","advisory","strict"]);function s_(e){return structuredClone(Xc[e])}function dI(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:S.governance.preset}function a_(e,t){let r=typeof t.create_default_type=="string"?t.create_default_type.trim():void 0;return r&&r.length>0&&(e.create_default_type=r),(t.workflow_enforcement==="off"||t.workflow_enforcement==="warn"||t.workflow_enforcement==="strict")&&(e.workflow_enforcement=t.workflow_enforcement),t.require_close_reason===!1&&(e.require_close_reason=!1),e.duplicate_detection_mode=t.duplicate_detection_mode,e.duplicate_detection_threshold=t.duplicate_detection_threshold,e.duplicate_detection_limit=t.duplicate_detection_limit,e}function lI(e){return e.preset==="custom"?a_({preset:"custom",ownership_enforcement:e.ownership_enforcement,create_mode_default:e.create_mode_default,close_validation_default:e.close_validation_default,parent_reference:e.parent_reference,metadata_profile:e.metadata_profile,force_required_for_stale_lock:e.force_required_for_stale_lock},e):a_({preset:e.preset},e)}function uI(e){let t=typeof e.create_default_type=="string"?e.create_default_type.trim():void 0,r={};t&&t.length>0&&(r.create_default_type=t),(e.workflow_enforcement==="off"||e.workflow_enforcement==="warn"||e.workflow_enforcement==="strict")&&(r.workflow_enforcement=e.workflow_enforcement),typeof e.require_close_reason=="boolean"&&(r.require_close_reason=e.require_close_reason),cI.has(String(e.duplicate_detection_mode))&&(r.duplicate_detection_mode=e.duplicate_detection_mode);let n=e.duplicate_detection_threshold;[typeof n=="number",Number.isFinite(n),Number(n)>=0,Number(n)<=1].every(Boolean)&&(r.duplicate_detection_threshold=n);let o=e.duplicate_detection_limit;return[typeof o=="number",Number.isSafeInteger(o),Number(o)>=0,Number(o)<=20].every(Boolean)&&(r.duplicate_detection_limit=o),r}function m_(e){let t=e.governance??{},r=dI(t.preset),n=uI(t);if(r==="custom"){let s=s_("default"),a=n.require_close_reason??s.require_close_reason;return{preset:r,ownership_enforcement:t.ownership_enforcement??s.ownership_enforcement,create_mode_default:t.create_mode_default??s.create_mode_default,close_validation_default:t.close_validation_default??s.close_validation_default,parent_reference:t.parent_reference??s.parent_reference,metadata_profile:t.metadata_profile??s.metadata_profile,force_required_for_stale_lock:t.force_required_for_stale_lock??s.force_required_for_stale_lock,...n,require_close_reason:a,duplicate_detection_mode:n.duplicate_detection_mode??s.duplicate_detection_mode,duplicate_detection_threshold:n.duplicate_detection_threshold??s.duplicate_detection_threshold,duplicate_detection_limit:n.duplicate_detection_limit??s.duplicate_detection_limit}}let o=s_(r),i=n.require_close_reason??o.require_close_reason;return{preset:r,...o,...n,require_close_reason:i}}function p_(){return structuredClone(S)}function __(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:S.search.mutation_refresh_policy}function y_(e){return e==="auto"||e==="keyword"||e==="semantic"||e==="hybrid"?e:"auto"}function h_(e){return typeof e=="boolean"?e:S.search.query_expansion.enabled}function g_(e){return typeof e!="string"?S.search.query_expansion.provider:e.trim()}function b_(e){return typeof e=="boolean"?e:S.search.rerank.enabled}function w_(e){return typeof e!="string"?S.search.rerank.model:e.trim()}function v_(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:S.search.rerank.top_k}function E_(e){if(typeof e!="string")return S.vector_store.collection_name;let t=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,aI);return t.length>0?t:S.vector_store.collection_name}function Dc(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function k_(e,t){let r=e.schema,n=Dc(r?.statuses),o=Dc(r?.fields),i=Dc(r?.type_workflows);return{persisted_settings:structuredClone(e),source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:Cr(e.item_types?.definitions),has_source_schema_statuses:n.present,source_schema_statuses:n.values,has_source_schema_fields:o.present,source_schema_fields:o.values,has_source_schema_type_workflows:i.present,source_schema_type_workflows:i.values,runtime_item_type_definitions:Cr(t.item_types?.definitions),runtime_schema_statuses:structuredClone(t.schema.statuses),runtime_schema_fields:structuredClone(t.schema.fields),runtime_schema_type_workflows:structuredClone(t.schema.type_workflows??[])}}function Ti(e,t){Object.defineProperty(e,f_,{value:t,writable:!0,configurable:!0,enumerable:!1})}function Fc(e){let t=e[f_];if(!(!t||typeof t!="object"))return t}function jL(e){let t=Fc(e);if(t){let r=structuredClone(t);r.source_settings.item_format=e.item_format,Ti(e,r)}}function Ai(e){let t=structuredClone(e.settings),r=Fc(e.settings);return r&&Ti(t,r),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function fI(e,t,r){let n=Te(t);return[r,de(e,n.files.types,oe.types),de(e,n.files.statuses,oe.statuses),de(e,n.files.fields,oe.fields),de(e,n.files.workflows,oe.workflows)]}async function mI(e,t,r){let n=await dt(t);Oi(e,{tracked_paths:t,signatures:n,value:Ai(r)})}async function pI(e,t,r){try{await mI(e,t,r)}catch{lt(e)}}function c_(e,t){return e.find(r=>r.path===t)}function _I(e,t,r){for(let n of r){let o=c_(e,n),i=c_(t,n);if(!o||!i||!xn([o],[i]))return!1}return!0}async function Pc(e,t,r,n,o){try{let i=await dt(t);if(!_I(n,i,o)){lt(e);return}Oi(e,{tracked_paths:t,signatures:i,value:Ai(r)})}catch{lt(e)}}function yI(e,t){let r=Te(e.schema),n=Cr(e.item_types?.definitions);if(!t)return{item_type_definitions:n,schema_statuses:r.statuses,schema_fields:r.fields,schema_type_workflows:r.type_workflows};let o=r.type_workflows??[],i=B(n,t.runtime_item_type_definitions),s=B(r.statuses,t.runtime_schema_statuses),a=B(r.fields,t.runtime_schema_fields),c=B(o,t.runtime_schema_type_workflows);return{item_type_definitions:i?t.has_source_item_type_definitions?Cr(t.source_item_type_definitions):[]:n,schema_statuses:s?t.has_source_schema_statuses?structuredClone(t.source_schema_statuses):[]:r.statuses,schema_fields:a?t.has_source_schema_fields?structuredClone(t.source_schema_fields):[]:r.fields,schema_type_workflows:c?t.has_source_schema_type_workflows?structuredClone(t.source_schema_type_workflows):void 0:r.type_workflows}}function Re(e){return{settings:p_(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function S_(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function jc(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function O_(e){let t=S.agent_guidance,r=e?.template_version;return{prompt_completed:e?.prompt_completed===!0,declined:e?.declined===!0,declined_at:typeof e?.declined_at=="string"?e.declined_at:t.declined_at,template_version:typeof r=="number"&&Number.isInteger(r)&&r>0?r:t.template_version,last_checked_files:jc(e?.last_checked_files??t.last_checked_files)}}function ve(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function hI(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.mode}function gI(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.trust_mode}function A_(e){return e==="none"||e==="restricted"||e==="strict"?e:S.extensions.policy.default_sandbox_profile}function bI(e){let t=e.name.trim().toLowerCase();if(t.length===0)return null;let r={name:t};e.disabled===!0&&(r.disabled=!0),e.require_trusted===!0&&(r.require_trusted=!0),e.require_provenance===!0&&(r.require_provenance=!0),e.sandbox_profile!==void 0&&(r.sandbox_profile=A_(e.sandbox_profile));let n=ve(e.allowed_capabilities),o=ve(e.blocked_capabilities),i=ve(e.allowed_surfaces),s=ve(e.blocked_surfaces),a=ve(e.allowed_commands),c=ve(e.blocked_commands),d=ve(e.allowed_actions),l=ve(e.blocked_actions),u=ve(e.allowed_services),f=ve(e.blocked_services);return n.length>0&&(r.allowed_capabilities=n),o.length>0&&(r.blocked_capabilities=o),i.length>0&&(r.allowed_surfaces=i),s.length>0&&(r.blocked_surfaces=s),a.length>0&&(r.allowed_commands=a),c.length>0&&(r.blocked_commands=c),d.length>0&&(r.allowed_actions=d),l.length>0&&(r.blocked_actions=l),u.length>0&&(r.allowed_services=u),f.length>0&&(r.blocked_services=f),r}function wI(e){let t=new Map;for(let r of e??[]){let n=bI(r);n&&t.set(n.name,n)}return[...t.values()].sort((r,n)=>r.name.localeCompare(n.name))}function Mc(e){return e==="block"||e==="warn"?e:void 0}function vI(e){if(typeof e=="string")return Mc(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=Mc(e.global),r=Mc(e.project);return t===void 0&&r===void 0?void 0:{...t!==void 0?{global:t}:{},...r!==void 0?{project:r}:{}}}}function ye(e,t){return ve(e?.[t]??S.extensions.policy[t])}function I_(e){let t=vI(e?.pm_max_version_exceeded_mode);return{mode:hI(e?.mode),trust_mode:gI(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:ye(e,"trusted_extensions"),default_sandbox_profile:A_(e?.default_sandbox_profile),allowed_extensions:ye(e,"allowed_extensions"),blocked_extensions:ye(e,"blocked_extensions"),allowed_capabilities:ye(e,"allowed_capabilities"),blocked_capabilities:ye(e,"blocked_capabilities"),allowed_surfaces:ye(e,"allowed_surfaces"),blocked_surfaces:ye(e,"blocked_surfaces"),allowed_commands:ye(e,"allowed_commands"),blocked_commands:ye(e,"blocked_commands"),allowed_actions:ye(e,"allowed_actions"),blocked_actions:ye(e,"blocked_actions"),allowed_services:ye(e,"allowed_services"),blocked_services:ye(e,"blocked_services"),extension_overrides:wI(e?.extension_overrides??S.extensions.policy.extension_overrides)}}function T_(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].filter(t=>t.length>0).sort((t,r)=>t.localeCompare(r)).filter(t=>["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"].includes(t))}function ut(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function W(e,t){return e===void 0?t:e}function he(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function Lc(e){return Array.isArray(e)?e:[]}function EI(e,t,r){return{...t.validation,...e.validation,parent_reference:r.parent_reference,metadata_profile:r.metadata_profile,metadata_required_fields:T_(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:ut(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:ut(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:ut(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:ut(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Nc(e.validation?.estimate_defaults_by_type)}}function kI(e,t){return{enabled:e.telemetry?.enabled??t.telemetry.enabled,first_run_prompt_completed:e.telemetry?.first_run_prompt_completed??t.telemetry.first_run_prompt_completed,capture_level:e.telemetry?.capture_level??t.telemetry.capture_level,endpoint:e.telemetry?.endpoint??t.telemetry.endpoint,installation_id:e.telemetry?.installation_id??t.telemetry.installation_id,retention_days:e.telemetry?.retention_days??t.telemetry.retention_days}}function SI(e,t){return{...t.search,...e.search,default_mode:y_(e.search?.default_mode),mutation_refresh_policy:__(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:h_(e.search?.query_expansion?.enabled),provider:g_(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:b_(e.search?.rerank?.enabled),model:w_(e.search?.rerank?.model),top_k:v_(e.search?.rerank?.top_k)}}}function OI(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:E_(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function AI(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function II(e,t){return{default_depth:e.context?.default_depth??t.context.default_depth,activity_limit:e.context?.activity_limit??t.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??t.context.stale_threshold_days,sections:{...t.context.sections,...e.context?.sections}}}function TI(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function Cr(e){let t=(e??[]).map(n=>Qn(n)).filter(n=>n!==null),r=new Map;for(let n of t)r.set(n.name.toLowerCase(),n);return[...r.values()].sort((n,o)=>n.name.localeCompare(o.name))}function Ii(e){let t=p_(),r=m_({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:AI(e,t),locks:{...t.locks,...e.locks},ids:{...t.ids,...e.ids},agent_identity:structuredClone(e.agent_identity??t.agent_identity),mutation_guard:{...t.mutation_guard,...e.mutation_guard},checkpoints:{...t.checkpoints,...e.checkpoints},output:{...t.output,...e.output},ux:{...t.ux,...e.ux},history:{...t.history,...e.history,compact_policy:{...t.history.compact_policy,...e.history?.compact_policy}},validation:EI(e,t,r),governance:r,workflow:{definition_of_done:[...e.workflow?.definition_of_done??t.workflow.definition_of_done]},testing:{record_results_to_items:e.testing?.record_results_to_items??t.testing.record_results_to_items,allow_untrusted_linked_tests:e.testing?.allow_untrusted_linked_tests??t.testing.allow_untrusted_linked_tests},telemetry:kI(e,t),agent_guidance:O_(e.agent_guidance??t.agent_guidance),item_types:{definitions:Cr(e.item_types?.definitions)},schema:Te(e.schema??t.schema),context:II(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:I_(e.extensions.policy??t.extensions.policy)},search:SI(e,t),providers:TI(e,t),vector_store:OI(e,t)}}function CI(e){e.agent_identity=A(e.agent_identity,["probes_enabled","identity_vocabulary","harness_signals"]);let t=e.agent_identity;Object.hasOwn(t,"identity_vocabulary")&&(t.identity_vocabulary=A(he(t.identity_vocabulary),["version","aliases"])),e.agent_identity.harness_signals=Lc(e.agent_identity.harness_signals).map(r=>A(he(r),["harness","environment_keys","model_environment_keys","session_environment_keys","provenance_environment_keys","provenance_resolvers","provenance_unavailable_dimensions","argv_markers","client_names"])),e.locks=A(e.locks,["ttl_seconds","wait_ms"]),e.ids=A(e.ids,["token_length"]),e.mutation_guard=A(e.mutation_guard,["require_attributed_author","secret_guard","stale_in_progress_hours"]),e.checkpoints=A(e.checkpoints,["retention_days"]),e.output=A(e.output,["default_format"]),e.ux=A(e.ux,["deprecation_hints"]),e.history=A(e.history,["missing_stream","compact_policy"]),e.validation=A(e.validation,["sprint_release_format","parent_reference","metadata_profile","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns","estimate_defaults_by_type"]),e.governance=A(e.governance,["preset","ownership_enforcement","create_mode_default","close_validation_default","require_close_reason","parent_reference","metadata_profile","force_required_for_stale_lock","create_default_type","workflow_enforcement","duplicate_detection_mode","duplicate_detection_threshold","duplicate_detection_limit"]),e.workflow=A(e.workflow,["definition_of_done"]),e.testing=A(e.testing,["record_results_to_items","allow_untrusted_linked_tests"]),e.telemetry=A(e.telemetry,["enabled","first_run_prompt_completed","capture_level","endpoint","installation_id","retention_days"]),e.agent_guidance=A(e.agent_guidance,["prompt_completed","declined","declined_at","template_version","last_checked_files"]),e.item_types=A(e.item_types,["definitions"]),e.schema=A(e.schema,["version","files","statuses","fields","workflow","type_workflows","unknown_field_policy"]),e.schema.files=A(he(e.schema.files),["types","statuses","fields","workflows"]),e.schema.workflow=A(he(e.schema.workflow),["draft_status","open_status","in_progress_status","blocked_status","close_status","canceled_status"]),e.context=A(e.context,["default_depth","activity_limit","stale_threshold_days","sections"]),e.context.sections=A(he(e.context.sections),["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]),e.extensions=A(e.extensions,["enabled","disabled","policy"]),e.extensions.policy=A(he(e.extensions.policy),["mode","trust_mode","pm_max_version_exceeded_mode","require_provenance","trusted_extensions","default_sandbox_profile","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"]),e.extensions.policy.extension_overrides=Lc(e.extensions.policy.extension_overrides).map(r=>A(he(r),["name","disabled","require_trusted","require_provenance","sandbox_profile","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"])),e.search=A(e.search,["score_threshold","hybrid_semantic_weight","max_results","embedding_model","embedding_corpus_max_characters","embedding_batch_size","embedding_timeout_ms","scanner_max_batch_retries","provider","default_mode","mutation_refresh_policy","query_expansion","rerank"]),e.search.query_expansion=A(he(e.search.query_expansion),["enabled","provider"]),e.search.rerank=A(he(e.search.rerank),["enabled","model","top_k"]),e.providers=A(e.providers,["openai","ollama"]),e.providers.openai=A(he(e.providers.openai),["base_url","api_key","model"]),e.providers.ollama=A(he(e.providers.ollama),["base_url","model"]),e.vector_store=A(e.vector_store,["adapter","collection_name","qdrant","lancedb"]),e.vector_store.qdrant=A(he(e.vector_store.qdrant),["url","api_key"]),e.vector_store.lancedb=A(he(e.vector_store.lancedb),["path"])}function RI(e){return{...e,locks:W(e.locks,S.locks),ids:W(e.ids,S.ids),agent_identity:W(e.agent_identity,S.agent_identity),mutation_guard:W(e.mutation_guard,S.mutation_guard),checkpoints:W(e.checkpoints,S.checkpoints),output:W(e.output,S.output),ux:W(e.ux,S.ux),history:W(e.history,S.history),validation:W(e.validation,S.validation),workflow:W(e.workflow,S.workflow),testing:W(e.testing,S.testing),telemetry:W(e.telemetry,S.telemetry),agent_guidance:W(e.agent_guidance,S.agent_guidance),item_types:W(e.item_types,S.item_types),schema:W(e.schema,S.schema),context:W(e.context,S.context),extensions:W(e.extensions,S.extensions),search:W(e.search,S.search),providers:W(e.providers,S.providers),vector_store:W(e.vector_store,S.vector_store)}}function xI(e,t){return{...e.validation,parent_reference:t.parent_reference,metadata_profile:t.metadata_profile,metadata_required_fields:T_(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:ut(e.validation?.lifecycle_stale_blocker_reason_patterns??S.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:ut(e.validation?.lifecycle_closure_like_blocked_reason_patterns??S.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:ut(e.validation?.lifecycle_closure_like_resolution_patterns??S.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:ut(e.validation?.lifecycle_closure_like_actual_result_patterns??S.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Nc(e.validation?.estimate_defaults_by_type)}}function NI(e){return{...S.search,...e.search,default_mode:y_(e.search?.default_mode),mutation_refresh_policy:__(e.search?.mutation_refresh_policy),query_expansion:{...S.search.query_expansion,...e.search?.query_expansion,enabled:h_(e.search?.query_expansion?.enabled),provider:g_(e.search?.query_expansion?.provider)},rerank:{...S.search.rerank,...e.search?.rerank,enabled:b_(e.search?.rerank?.enabled),model:w_(e.search?.rerank?.model),top_k:v_(e.search?.rerank?.top_k)}}}function DI(e){return{default_depth:e.context?.default_depth??S.context.default_depth,activity_limit:e.context?.activity_limit??S.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??S.context.stale_threshold_days,sections:{...S.context.sections,...e.context?.sections}}}function PI(e){return{...e.vector_store,adapter:e.vector_store?.adapter??S.vector_store.adapter,collection_name:E_(e.vector_store?.collection_name),qdrant:{...e.vector_store?.qdrant},lancedb:{...e.vector_store?.lancedb}}}function MI(e,t,r,n){return{...e,item_format:"toon",validation:xI(e,t),governance:t,agent_guidance:O_(e.agent_guidance),item_types:{definitions:n.item_type_definitions},schema:{...r,statuses:n.schema_statuses,fields:n.schema_fields,type_workflows:n.schema_type_workflows},search:NI(e),context:DI(e),extensions:{enabled:jc(e.extensions?.enabled),disabled:jc(e.extensions?.disabled),policy:I_(e.extensions?.policy)},vector_store:PI(e)}}function C_(e,t){for(let r of Object.keys(t)){let n=Reflect.get(t,r),o=e[r];typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof o=="object"&&o!==null&&!Array.isArray(o)?C_(o,n):e[r]=structuredClone(n)}}function R_(e,t,r){let n=new Set([...Object.keys(t),...Object.keys(r)]);for(let o of n){let i=t[o],s=r[o];if(!B(i,s)){if(s===void 0){delete e[o];continue}if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=e[o],c=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{};R_(c,i,s),Object.keys(c).length>0?e[o]=c:delete e[o];continue}e[o]=structuredClone(s)}}}var zc=["version","id_prefix","ids","author_default","agent_identity","mutation_guard","item_format","locks","checkpoints","output","ux","history","validation","governance","workflow","testing","telemetry","agent_guidance","item_types","schema","context","extensions","search","providers","vector_store"];function d_(e,t){let r=RI(e),n=m_(r),o=Te(r.schema),i=yI(r,t),s=MI(r,n,o,i),a=A({...s,governance:lI(n)},zc);return CI(a),a}function $I(e,t={}){let r=t.source===void 0?t.persist_source:k_(t.source.validated,Ii(t.source.validated)),n=d_(e,r);if(r){let o=Ii(r.source_settings);o.item_types={definitions:structuredClone(r.runtime_item_type_definitions)},o.schema={...o.schema,statuses:structuredClone(r.runtime_schema_statuses),fields:structuredClone(r.runtime_schema_fields),type_workflows:structuredClone(r.runtime_schema_type_workflows)};let i=d_(o,r);t.source!==void 0&&C_(i,t.source.validated);let s=structuredClone(t.source===void 0?r.source_settings:t.source.raw);return R_(s,i,n),`${JSON.stringify(A(s,zc),null,2)}
109
- `}return`${JSON.stringify(n,null,2)}
110
- `}async function jI(e){let t;try{t=await l_(e)}catch(a){if(Se(a))return Re();throw a}let r=Oe(t),n;try{n=await oI(r)}catch(a){if(Se(a))return Re();throw a}if(!n.isFile())throw Mi("settings.json");let o;try{o=await Jc(r,Mi("settings.json"))}catch(a){if(Se(a))return Re();throw a}let i;try{i=JSON.parse(o)}catch{return Re("settings_read_invalid_json")}let s=Cc(i);return s.success?{settings:Ii(s.data),metadata:{has_explicit_item_format:S_(i)},warnings:s.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[]}:Re("settings_read_invalid_schema")}async function x_(e){if(iI(e))return jI(e);let t=Oe(e),r=[t];await rr({path:t,scope:"project"});let n=i_(e);if(n){let d=await dt(n.tracked_paths);if(xn(d,n.signatures))return Ai(n.value)}let o=await dt([t]),i;try{i=await ge(t)}catch{return Re("settings_read_fs_error")}if(i===null){let d=Re();return await Pc(e,[t],d,o,[t]),d}let s=await dt([t]);if(!xn(o,s))return lt(e),x_(e);let a;try{a=JSON.parse(i)}catch{let d=Re("settings_read_invalid_json");return await Pc(e,[t],d,s,[t]),d}let c=Cc(a);if(!c.success){let d=Re("settings_read_invalid_schema");return await Pc(e,[t],d,s,[t]),d}try{let d=Ii(c.data),l=fI(e,d.schema,t);r=l;let u=await dt(l),f=await gm(e,d.schema),m=await bm(e,d.schema),_=await dt(l),y={...d,item_types:{definitions:Cr([...d.item_types.definitions,...Lc(m.type_definitions_from_file)])},schema:m.schema};Ti(y,k_(c.data,y));let w={settings:y,metadata:{has_explicit_item_format:S_(a)},warnings:[...c.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...f.created_paths.map(v=>`runtime_schema_bootstrap_created:${v}`),...m.warnings]};return f.created_paths.length===0?xn(u,_)?Oi(e,{tracked_paths:l,signatures:_,value:Ai(w)}):lt(e):lt(e),w}catch{let d=Re("settings_read_merge_failed");return await pI(e,r,d),d}}async function LL(e){return(await x_(e)).settings}async function FL(e,t,r=sI){let n=Oe(e),o=Fc(t),i=$I(t,{persist_source:o}),s=JSON.parse(i);try{await e_({pmRoot:e,filePath:n,mutate:a=>{let c=null;if(a!==null)try{c=JSON.parse(a)}catch{throw new g("Existing settings.json is malformed; the settings write was refused.",h.USAGE,{code:"settings_write_invalid_existing_json",reason:"existing_settings_json_malformed",why:"Writing defaults over malformed settings could destroy intended project configuration.",nextSteps:["Repair the syntax in .agents/pm/settings.json, then retry the original command.","Run pm health to confirm the settings warning has cleared."]})}return{raw:o?`${JSON.stringify(A(Rc(o.persisted_settings,s,c),zc),null,2)}
111
- `:i,result:void 0}},op:r,author:ap(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms,recordCreation:!1}),o&&Ti(t,{...o,persisted_settings:structuredClone(s)}),await vo({path:n,scope:"project",op:r})}finally{lt(e)}}import N_ from"node:fs";import Nn from"node:path";import{createRequire as LI}from"node:module";(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]="19d9b802-1efa-5716-8176-ecbf5b153ff0")}catch{}})();var Dn="@unbrained/pm-cli",FI=new Set(["append","claim","changelog","close","close-many","close-task","comments","config","copy","create","dedupe-merge","delete","deps","docs","extension","event","events","files","focus","gc","history-author-acknowledge","history-compact","history-redact","history-repair","init","install","item","learnings","meet","merge","normalize","notes","package","packages","pause-task","plan","profile","reindex","release","remind","restore","schema","start-task","test","test-all","test-runs","test-runs-worker","telemetry","templates","twin","update","update-many","upgrade","vcs","workspace"]),D_=new Set(["--author","--output-budget","--output-format","--output-include","--output-limit","--output-session","--path","--pm-path"]),Hc=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,Ni="2026.8.31";function ie(e,t){return e.some(r=>t.includes(r.split("=",1)[0]))}function Uc(e,t){return["activate","adopt","adopt-all","deactivate","init","install","migrate","reload","uninstall"].includes(t[0]??"")||ie(e,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}var zI={changelog:(e,t)=>{if(t[0]==="generate")return!ie(e,["--check"]);let r=e.indexOf("export");return t[0]==="export"&&(ie(e,["--output"])||r>=0&&e[r+1]!==void 0&&!e[r+1].startsWith("-"))},comments:e=>ie(e,["--add","--delete","--edit","--file","--stdin"]),config:(e,t)=>(t[0]==="project"||t[0]==="global"?t[1]:t[0])==="set",deps:()=>!1,docs:e=>ie(e,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>!1,events:()=>!1,extension:Uc,files:(e,t)=>ie(e,["--add","--add-glob","--migrate","--remove"])||t[0]==="discover"&&ie(e,["--apply"]),health:e=>!ie(e,["--check-only","--no-refresh","--skip-vectors"]),learnings:e=>ie(e,["--add","--delete","--edit","--file","--stdin"]),merge:(e,t)=>t[0]!=="report",notes:e=>ie(e,["--add","--delete","--edit","--file","--stdin"]),package:Uc,packages:Uc,profile:(e,t)=>t[0]==="apply",schema:(e,t)=>["add-field","add-status","add-type","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type"].includes(t[0]??"")&&!(ie(e,["--infer"])&&!ie(e,["--apply"])),telemetry:(e,t)=>t.slice(0,2).some(r=>["clear","flush"].includes(r)),templates:(e,t)=>t[0]==="save",test:e=>ie(e,["--update","--update-index","--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:e=>ie(e,["--auto-fix","--prune-missing"]),vcs:(e,t)=>["abandon","create","merge","propose","ref-create"].includes(t[0]??""),workspace:(e,t)=>t[0]==="snapshot"&&["create","delete","restore"].includes(t[1]??"")};function Ri(e){let t=e.match(Hc);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function ft(e,t){let r=Ri(e),n=Ri(t);if(!r||!n)return null;for(let o=0;o<r.length;o+=1){let i=r[o]-n[o];if(i!==0)return Math.sign(i)}return 0}function Ci(e){return ft(e,Ni)!==-1?3:2}function UI(e,t){if(t===3)return e.filter(r=>r.history_epoch_compatible===!1).map(r=>({...r,declaration:r.declaration??r.version})).sort((r,n)=>ft(r.version,n.version))[0]}function xi(e){try{let t=JSON.parse(N_.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function HI(e){let t=[...e.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(n=>({inclusive:n[1]==="<=",version:n[2]})),r=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 r?[...t,{inclusive:!0,version:r[1]}]:t}function qI(e){let t=e.split("||").map(r=>HI(r));return{bounded:t.some(r=>r.length>0),compatible:t.some(r=>r.every(n=>{let o=ft(Ni,n.version);return o!==null&&(n.inclusive?o!==1:o===-1)}))}}function P_(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let r=e[t];if(typeof r!="object"||r===null)return[];let n=r[Dn];return typeof n=="string"?[n.trim()]:[]})}function VI(e){return P_(e).flatMap(t=>{let r=/^[<!]/u.test(t)?void 0:t.match(Hc)?.[0];if(!r)return[];let n=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(t),o=qI(t);return[{version:r,constraint:n?"exact":o.bounded?"range":"minimum",...n?{}:{declaration:t},history_epoch_compatible:n?ft(r,Ni)!==-1:o.compatible}]})}function BI(e){let t=xi(Nn.join(e,"package-lock.json"))?.packages;if(typeof t!="object"||t===null)return;let r=t["node_modules/@unbrained/pm-cli"];if(typeof r!="object"||r===null)return;let n=r.version;return typeof n=="string"?n:void 0}function WI(e,t){try{let r=N_.readFileSync(Nn.join(e,t),"utf8").split(/\r?\n/u),n=r.findIndex(s=>s.includes(Dn));if(n<0)return;let o=r[n].match(/^\s*/u)[0].length,i=[r[n]];for(let s=n+1;s<r.length;s+=1){let a=r[s],c=a.trim(),d=a.match(/^\s*/u)[0].length;if(c.length>0&&d<=o)break;i.push(a)}return i.join(`
112
- `).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??i[0].match(Hc)?.[0]}catch{return}}function M_(e){let t=[],r=xi(Nn.join(e,"package.json"));r&&t.push(...VI(r).map(i=>({...i,source:"package.json"})));let n=xi(Nn.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof n=="string"&&Ri(n)&&t.push({version:n,source:"installed-package",constraint:"exact",history_epoch_compatible:Ci(n)===3});let o=BI(e);o&&Ri(o)&&t.push({version:o,source:"package-lock.json",constraint:"exact",history_epoch_compatible:Ci(o)===3});for(let i of["pnpm-lock.yaml","yarn.lock"]){let s=WI(e,i);s&&t.push({version:s,source:i,constraint:"exact",history_epoch_compatible:Ci(s)===3})}return t}function WL(e,t){if(t<=1)return;let{minVersion:r,lt:n}=LI(import.meta.url)("semver"),o=P_(xi(Nn.join(e,"package.json"))??{}).find(s=>{try{let a=r(s);return a!==null&&n(a,"2026.10.10")}catch{return!1}}),i=o===void 0?M_(e).find(s=>ft(s.version,"2026.10.10")===-1):{version:o,source:"package.json"};if(i)throw new g(`The project selects pm ${i.version}, which cannot safely refuse item format ${t}.`,h.CONFLICT,{code:"project_runtime_item_format_incompatible",reason:i.source,required:"Upgrade project pins, installed SDKs, CI hosts and Git merge drivers before writing guarded item formats.",nextSteps:["Use a pm runtime supporting the required item format throughout the project; preserve original item and history bytes, and never re-anchor history to satisfy an older host."]})}function $_(e){for(let t=0;t<e.length;t+=1){let r=e[t];if(D_.has(r)){t+=1;continue}if(!r.startsWith("-"))return{command:r.toLowerCase(),index:t}}}function GI(e){let t=$_(e);if(!t||ie(e,["--help","-h","--dry-run"]))return!1;let{command:r,index:n}=t,o=[];for(let s=n+1;s<e.length;s+=1){let a=e[s];if(D_.has(a)){s+=1;continue}a.startsWith("-")||o.push(a.toLowerCase())}let i=zI[r];return i?i(e,o):FI.has(r)}function KI(e){let t=$_(e.argv)?.command,r=GI(e.argv),n=M_(e.projectRoot).filter(l=>ft(l.version,e.executingVersion)!==null).sort((l,u)=>ft(u.version,l.version)),o=n[0],i=o!==void 0&&ft(e.executingVersion,o.version)===-1,s=Ci(e.executingVersion),a=UI(n,s),c=r&&a!==void 0,d=i&&!r?{code:"project_runtime_stale_read",executing_version:e.executingVersion,project_version:o.version,source:o.source,message:"This read is using an older pm runtime than the project requires.",next_steps:[`Run the command through the project's installed ${Dn} ${o.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!r||!i&&!c||e.allowStale===!0,executing_version:e.executingVersion,...o?{project_version:o.version,source:o.source}:{},...t?{command:t}:{},mutating:r,stale:i,history_epoch_incompatible:c,writer_item_hash_version:s,...a?{incompatible_project_version:a.declaration,incompatible_source:a.source}:{},...d?{warning:d}:{},override_applied:r&&(i||c)&&e.allowStale===!0}}function GL(e){let t=KI(e);if(t.compatible)return t;throw t.history_epoch_incompatible?new g(`pm ${t.executing_version} cannot write item-hash epoch ${t.writer_item_hash_version} into a project pinned to pm ${t.incompatible_project_version}.`,h.CONFLICT,{code:"project_runtime_history_epoch_incompatible",reason:t.incompatible_source,why:`The pinned runtime cannot read item_hash_version ${t.writer_item_hash_version}; allowing the write would break its health and validation gates.`,nextSteps:[`Upgrade the project's ${Dn} pin to ${Ni} or newer before mutating tracker history.`,"For an intentional coordinated migration only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]}):new g(`pm ${t.executing_version} cannot mutate a project pinned to newer pm ${t.project_version}.`,h.CONFLICT,{code:"project_runtime_stale_mutation",reason:t.source,why:"An older runtime can write storage, history, and merge contracts it does not understand.",nextSteps:[`Run this command through the project's installed ${Dn} ${t.project_version}.`,"For an intentional recovery only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]})}export{F_ as a,z_ as b,U_ as c,H_ as d,$i as e,YI as f,q_ as g,Nr as h,zn as i,XI as j,JI as k,ZI as l,ji as m,zi as n,Ui as o,nT as p,oT as q,iT as r,Z_ as s,Qc as t,sT as u,hs as v,Hi as w,ed as x,Vn as y,Bn as z,fT as A,mT as B,sy as C,_T as D,yT as E,hT as F,rd as G,gT as H,bT as I,wT as J,td as K,nd as L,vT as M,ay as N,od as O,Wt as P,Gn as Q,Gt as R,Kn as S,kT as T,ST as U,OT as V,Xn as W,Jn as X,AT as Y,IT as Z,TT as _,CT as $,Zn as aa,Pr as ba,qi as ca,RT as da,sd as ea,xT as fa,NT as ga,DT as ha,PT as ia,my as ja,ld as ka,_d as la,qT as ma,Gi as na,Oy as oa,VT as pa,Fy as qa,zy as ra,BT as sa,WT as ta,tC as ua,rh as va,rC as wa,nC as xa,oC as ya,bd as za,Oe as Aa,iC as Ba,sC as Ca,aC as Da,Ki as Ea,Yi as Fa,eo as Ga,oh as Ha,cC as Ia,ih as Ja,sh as Ka,dC as La,lC as Ma,ah as Na,uC as Oa,R as Pa,B as Qa,ro as Ra,gh as Sa,vd as Ta,Xi as Ua,vh as Va,Eh as Wa,no as Xa,kd as Ya,Sh as Za,Ih as _a,bC as $a,wC as ab,xh as bb,Nh as cb,Dh as db,OC as eb,AC as fb,Ph as gb,oo as hb,IC as ib,TC as jb,Mh as kb,$h as lb,jh as mb,Od as nb,Kt as ob,Lh as pb,CC as qb,RC as rb,xC as sb,NC as tb,DC as ub,PC as vb,MC as wb,io as xb,so as yb,Yt as zb,F as Ab,ao as Bb,zC as Cb,co as Db,Ad as Eb,Ji as Fb,Wh as Gb,Gh as Hb,Fr as Ib,Zi as Jb,Qi as Kb,es as Lb,ts as Mb,rs as Nb,ns as Ob,ks as Pb,Yh as Qb,Xh as Rb,eg as Sb,tg as Tb,Dd as Ub,rg as Vb,is as Wb,eR as Xb,Md as Yb,$d as Zb,lo as _b,nR as $b,Ld as ac,oR as bc,yl as cc,Dl as dc,Pl as ec,ag as fc,ss as gc,dg as hc,as as ic,cs as jc,ds as kc,ls as lc,us as mc,fs as nc,ps as oc,_s as pc,ys as qc,Jg as rc,Qg as sc,eb as tc,cb as uc,Lx as vc,Fx as wc,zx as xc,Vx as yc,Wx as zc,Ib as Ac,Tb as Bc,Rs as Cc,xb as Dc,Nb as Ec,eN as Fc,bo as Gc,tN as Hc,rN as Ic,nN as Jc,oN as Kc,iN as Lc,sN as Mc,aN as Nc,Jl as Oc,cN as Pc,dN as Qc,Zl as Rc,lN as Sc,wo as Tc,uN as Uc,fN as Vc,mN as Wc,pN as Xc,_N as Yc,vo as Zc,yN as _c,rr as $c,hN as ad,gN as bd,bN as cd,wN as dd,vN as ed,nr as fd,IN as gd,TN as hd,on as id,NN as jd,Eo as kd,jb as ld,Lb as md,DN as nd,Ae as od,PN as pd,qb as qd,Wb as rd,Qb as sd,iu as td,cu as ud,ew as vd,tw as wd,rw as xd,ko as yd,jN as zd,su as Ad,au as Bd,or as Cd,UN as Dd,lu as Ed,Oo as Fd,sw as Gd,Ge as Hd,ir as Id,tn as Jd,Ao as Kd,rn as Ld,uu as Md,qN as Nd,nn as Od,Fs as Pd,sn as Qd,Ew as Rd,nD as Sd,vu as Td,kw as Ud,Nw as Vd,Pw as Wd,Eu as Xd,Mw as Yd,$w as Zd,ku as _d,kt as $d,Su as ae,oD as be,iD as ce,$s as de,js as ee,Ro as fe,Tu as ge,Ls as he,Cu as ie,an as je,fD as ke,St as le,CD as me,RD as ne,Jw as oe,dr as pe,xD as qe,Uu as re,ov as se,ND as te,Bu as ue,Bs as ve,Zu as we,Qu as xe,ef as ye,tf as ze,No as Ae,Ws as Be,ln as Ce,GD as De,KD as Ee,un as Fe,Gs as Ge,Xs as He,YD as Ie,Nv as Je,XD as Ke,JD as Le,Do as Me,Mv as Ne,$v as Oe,rP as Pe,nP as Qe,Ie as Re,je as Se,pn as Te,lr as Ue,ne as Ve,dP as We,lP as Xe,ra as Ye,aa as Ze,wE as _e,ce as $e,Le as af,Y as bf,FP as cf,mr as df,NE as ef,zP as ff,UP as gf,DE as hf,HP as if,qP as jf,VP as kf,Lf as lf,jE as mf,r1 as nf,FE as of,zf as pf,n1 as qf,Hf as rf,UE as sf,BE as tf,qf as uf,Wf as vf,Gf as wf,a1 as xf,l1 as yf,Ho as zf,u1 as Af,f1 as Bf,m1 as Cf,p1 as Df,_1 as Ef,y1 as Ff,Yf as Gf,b0 as Hf,bn as If,qo as Jf,x1 as Kf,N1 as Lf,rm as Mf,z0 as Nf,B1 as Of,nm as Pf,om as Qf,va as Rf,im as Sf,G1 as Tf,sm as Uf,K1 as Vf,am as Wf,J1 as Xf,V0 as Yf,cm as Zf,Tt as _f,tt as $f,dm as ag,rt as bg,oe as cg,Sa as dg,Te as eg,de as fg,lM as gg,gm as hg,bm as ig,wm as jg,Oa as kg,vm as lg,Em as mg,uM as ng,Om as og,En as pg,gM as qg,bM as rg,Ia as sg,Ta as tg,vM as ug,Ca as vg,Im as wg,Nk as xg,EM as yg,Jo as zg,Pk as Ag,AM as Bg,Zo as Cg,AS as Dg,ti as Eg,BS as Fg,BM as Gg,WM as Hg,wr as Ig,zm as Jg,Rt as Kg,qa as Lg,XM as Mg,JM as Ng,Wa as Og,Bm as Pg,Ka as Qg,s$ as Rg,a$ as Sg,c$ as Tg,d$ as Ug,l$ as Vg,u$ as Wg,nc as Xg,oc as Yg,Qm as Zg,v$ as _g,E$ as $g,k$ as ah,S$ as bh,O$ as ch,A$ as dh,cc as eh,op as fh,I$ as gh,T$ as hh,C$ as ih,RO as jh,R$ as kh,ap as lh,xO as mh,Fe as nh,L$ as oh,NO as ph,DO as qh,kr as rh,dp as sh,XO as th,ej as uh,tj as vh,rj as wh,dA as xh,pi as yh,jt as zh,Tn as Ah,fA as Bh,mA as Ch,jp as Dh,Or as Eh,Aj as Fh,Ec as Gh,hi as Hh,Lp as Ih,kc as Jh,Ij as Kh,zp as Lh,Up as Mh,Tj as Nh,Cn as Oh,Rn as Ph,qp as Qh,AA as Rh,gi as Sh,Fj as Th,Sc as Uh,bi as Vh,zj as Wh,Uj as Xh,Gp as Yh,wi as Zh,Xp as _h,Ft as $h,MA as ai,Hj as bi,qj as ci,ct as di,zt as ei,rL as fi,nL as gi,oL as hi,e_ as ii,iL as ji,sL as ki,aL as li,Cc as mi,_L as ni,lt as oi,$L as pi,iI as qi,m_ as ri,jL as si,Ii as ti,$I as ui,x_ as vi,LL as wi,FL as xi,Ni as yi,ft as zi,Ci as Ai,M_ as Bi,WL as Ci,GI as Di,KI as Ei,GL as Fi};
113
- //# sourceMappingURL=chunk-KBSVPUFD.js.map